# CUI > Experimental portable C11 UI: immediate frame composition, persistent application models, themed components and independent host/renderer adapters. All 78 comparison entries remain in scope; gallery presence is not complete component parity. Use catalog.json for feature status and limitations. Public headers define the API; examples must state their tested host. Source revision: `4752885b8a8f8eec40d1c91964f1f57e4d8d37e1`. Build profile: `web-default-icons-regex`. [Exact input hashes and build metadata](./build-info.json). --- ## CUI Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/README.md # CUI An experimental C11 native UI framework: Clay layout, unstyled interaction primitives, themed controls, and independent renderer adapters. Embed it in an existing host or run the SDL3 workbench. No browser engine, JavaScript VM, Rust runtime, or platform types in the public core API. **Development snapshot; full component parity remains unfinished.** All 78 component families have real C/WASM gallery stories and explicit [feature status](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/gpui-parity.json). The library includes themed controls, Unicode editing, retained docking and virtual lists, charts, Markdown and composed application examples. Native accessibility, full language services/IME/bidi and exact platform behavior remain in progress; a tested subset does not verify a whole family. [**Beta roadmap and remaining work**](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/BETA_VERSION_ROADMAP.md) — current delivery status, priorities and completion gates. [**Open the browser component gallery**](https://matteo.merola.co/cui/) — all 78 catalog entries, with interactive stories compiled from the same C11 implementation to WebAssembly. The HTML/Canvas browser host is an optional gallery adapter; native applications do not depend on it. See [browser build and validation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/WEB_GALLERY.md). ![CUI workspace composed from real components and rendered from C in WebAssembly](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/screenshots/readme-workspace.png) The current [composed application](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMPOSED_APPS.md) uses CUI navigation, account menus, cards, forms and pricing actions. This capture shows the real C/WASM draw list rendered by the browser adapter; it is not a mockup. Download the [alpha.4 native starter kit](https://github.com/mattmezza/cui/releases/download/v0.1.0-alpha.4/cui-0.1.0-alpha.4-native-starter.tar.gz) with CUI source, fonts and editable native examples. Build a real window with the [native app starter guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NATIVE_APP_STARTER.md): dependencies, CMake/Make/linker flags, sidebar pages and a bottom account menu. For a standalone native source bundle, run `make native-dist`. Unpack `build/cui-native.tar.gz` outside this checkout, then run `make` and `./build/native_starter`. The archive includes CUI sources and Inter Regular/Bold; the consumer needs a C11 compiler, GNU Make, `ar`, pkg-config, SDL3 >= 3.2, FreeType and HarfBuzz development packages. See the guide for platform limits. ## Build and run ```sh cmake -S . -B build -G Ninja cmake --build build python scripts/test_local.py --build-dir build ./build/cui_gallery ./build/cui_gpu_demo --font /path/to/font.ttf ``` On Linux, automated tests use the wrapper above to run in invisible Xvfb; they must never use your desktop display. The example executables below intentionally open windows when launched manually. Core/software need a C11 compiler and CMake; Python3 checks generated headers and the manifest. Native examples optionally discover SDL3 >=3.2, FreeType and HarfBuzz through pkg-config. Set `CUI_FONT` or `--font` for an explicit font. Missing native dependencies leave portable targets available; they do not create a fake native gallery. ```sh cmake --preset headless && cmake --build --preset headless python scripts/test_local.py --build-dir build-headless cmake --preset sanitize && cmake --build --preset sanitize python scripts/test_local.py --build-dir build-sanitize ./build/cui_gallery --headless --section text --dark --screenshot build/text.ppm ./build/cui_gallery --smoke 3 --screenshot build/native.bmp ``` The SDL_Renderer compatibility adapter reports its actual renderer name. It requests high pixel density windows, keeps layout and pointer coordinates in logical window units, and rasterizes text, rounded shapes, images and shadows at the current renderer density. Text shaping and caret positions remain stable when moving between displays; the text library also exposes explicit `*_scaled` paint APIs for other hosts. Rounded fills and borders retain bounded batches of up to 128 scanline strips through SDL_RenderFillRects, with no added antialiasing. The separate SDL_GPU implementation uses a borrowed device/window, SPIR-V/Vulkan shaders, antialiased geometry and a bounded glyph atlas. It has been exercised on Linux Xorg with an Intel Graphics device reported by SDL. Metal/D3D shader formats remain pending; SDL_GPU backend selection alone does not establish hardware acceleration. GPU tests register only with `-DCUI_GPU_TESTS=ON`, requiring an actual device/window. The independent Sokol GLCORE adapter borrows a host OpenGL context and framebuffer and has actual pixel/cache tests on the same Intel/Mesa device; see [its contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/backends/sokol/README.md). It has no SDL dependency. ## A small application ```c #include "cui/cui_components.h" void settings_frame(cui_context *ui, bool *notifications) { cui_theme theme = cui_theme_light(); cui_begin_frame(ui, 640, 480, 1.0f / 60); cui_begin_box(ui, cui_id_from(ui, "settings"), (cui_box){ .width = -1, .height = -1, .padding = 24, .gap = 12, .background = theme.background }); cui_label(ui, &theme, cui_string("Settings")); cui_switch(ui, cui_id_from(ui, "notifications"), &theme, cui_string("Notifications"), notifications, false); cui_end_box(ui); cui_draw_list list = cui_end_frame(ui); /* Consume list synchronously using your renderer before the next frame. */ (void)list; } ``` Create/destroy the context in the host; queue input before begin. Width/height 0 fit, negative grow, positive fix logical pixels. Stable scoped keys retain identity when lists reorder. Strings are copied to a bounded frame arena; returned draw/semantic pointers expire at the next begin. Read [API ownership](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/API.md) and [the core contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CORE.md). ## Header-only distribution `dist/` covers portable/headless composition, not a complete native window host. It is reproducibly generated from modular sources and includes pinned Clay. In one C translation unit: ```c #define CUI_IMPLEMENTATION #include "cui.h" #define CUI_BASE_IMPLEMENTATION #include "cui_base.h" #define CUI_COMPONENTS_IMPLEMENTATION #include "cui_components.h" ``` Other translation units include those headers without implementation macros. Base includes the editor implementation; styled components include theme, overlay, virtual and plot implementations. Standalone optional models also have their own implementation macros. The single-TU test starts with the snippet above without a declaration pre-pass; multi-TU executables are also tested. Conventional static library targets use `include/cui/`. C++ and Zig host examples are in [examples/embedding](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/embedding). For every portable implementation, including effects and the theme registry, use this alternative in one dedicated implementation file: ```c #define CUI_IMPLEMENTATION_ALL #include "cui_all.h" ``` Other files include `cui_all.h` without the macro. The generated [implementation inventory](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/dist/implementations.json) lists individual headers, macros and source files. This umbrella excludes native adapters and the optional Rust regex provider, which are separately linked libraries. Component declarations, including Sidebar, are available through the umbrella. Compile the implementation file once into a static library and link your app sources against it. Keep implementation macros out of app headers so ordinary app edits do not rebuild the amalgamation. Regenerate only when vendored CUI changes; the modular CMake build already compiles separate source files in parallel. For a native SDL3 app, use the installed `cui-sdl3` pkg-config package and the [native starter](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NATIVE_APP_STARTER.md). CMake supplies the transitive static libraries and FreeType/HarfBuzz/SDL3 dependencies. If assembling sources manually, the adapter also needs `cui_text.h`, `cui_bidi.h`, `cui_sdl3.h`, `cui_accessibility.h`, `src/text/cui_text.c`, the bidi implementation, `backends/sdl3/cui_sdl3.c`, and its private software bitmap/shadow/shape headers. Include the portable effects implementation (`CUI_EFFECTS_IMPLEMENTATION`) for shadow support; `CUI_IMPLEMENTATION_ALL` includes it. Copying only `dist/` does not supply those native sources or third-party native libraries. `python scripts/amalgamate.py` regenerates; `make dist-check` checks exact reproducibility. `python tools/component_vendor/vendor.py /empty/destination --layer components` copies the layer dependency closure and licenses. This currently vendors all implemented controls in that layer; per-component source slicing is pending. No CLI is required to consume the library. ## Validation and scope `make check lint format-check dist-check`, `make bench`, and `make gallery` are available. Tests cover previous-frame ordered routing, nested capture/clips/focus scopes, Unicode scalar editing and history, randomized keyed virtualization, independent semantics, software pixels, shaped text, SDL cache/clipboard services, actual GPU readback, embedding, and gallery bounds. [Platform matrix](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PLATFORM_MATRIX.md) distinguishes runtime evidence from authored CI. Windows/macOS portable CI jobs are configured; results and limitations are recorded in the matrix. Fifteen headless modules also run in a pinned [WASI runner](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/WASI.md); this is separate from browser support. Read [the nightly report](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NIGHTLY_REPORT.md), [full component reference](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMPONENTS.md), [architecture](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/ARCHITECTURE.md), [component authoring](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMPONENT_AUTHORING.md), and [remaining maintainer actions](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MAINTAINER_ACTIONS.md). All performance figures include workload context in [PERFORMANCE.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PERFORMANCE.md); none compare to other frameworks. For a compact view of all 78 families, read [component status](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMPONENT_STATUS.md). Run `python scripts/cui_status.py Input Icon Sidebar` to inspect selected families' features, evidence and limitations directly from the manifest. Original CUI source is MIT. Vendored Clay and Sokol are zlib-licensed. upstream kit 0.7.1 is a pinned functional reference, not linked or copied into the C runtime; see [upstream baseline](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/upstream-baseline.md) and [dependency inventory](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/third_party/dependencies.json). For macOS development, see [native Mac builds and `.app` packaging](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MACOS.md) and [Linux-to-macOS cross compilation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MACOS_CROSS.md). These workflows still require Mac runtime acceptance. --- ## Build CUI applications with an AI agent Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/AI_AGENTS.md # Build CUI applications with an AI agent Give an agent your application requirements and the repository's current API and tests. CUI is a portable C11 library with optional host/renderer adapters. The live gallery covers 78 entries, while the feature manifest still records incomplete reference behavior. For repository development, use [the beta roadmap](https://github.com/mattmezza/cui/blob/main/BETA_VERSION_ROADMAP.md) as the maintained delivery checklist. Update it when completing a slice or discovering a gap; keep implementation, validation, integration and publication status distinct. ## Install the CUI skill ```sh npx skills add mattmezza/cui --skill cui ``` The repository distributes `skills/cui/SKILL.md` with Python 3.9+ standard-library helpers and generated offline references. Ask your agent to use the CUI skill to build your app. It covers native C11, browser/WASM, embedding and language builders, including backend selection, fonts, responsive layout and limitations. The skill checks prerequisites without installing packages. Setup pins a source commit; subsequent discovery must use that project's `--source` path to avoid mixing API revisions. See the skill for search, API lookup, vendoring, existing example setup and integrity-check commands. Python helpers need no pip packages. Maintainers regenerate resources with `python scripts/generate_agent_skill.py`; CI checks freshness and exercises an installed copy outside the repository. When editing `docs/component-usage.json`, synchronize `docs/COMPONENT_USAGE.md` and run `python tests/test_component_usage.py`; the website metadata and human guide must describe the same state, interaction and lifetime contracts. ## Consumer setup prompt ```text Build my UI using the CUI repository at https://github.com/mattmezza/cui. My application requirements: [describe the screens, interactions and host]. Start by reading README.md, docs/START_HERE.md, docs/IMMEDIATE_AND_STATE.md, docs/INTERFACES.md and docs/component manifest. For adaptive layouts read docs/RESPONSIVE_LAYOUT.md and docs/LAYOUT_GUIDE.md. For reusable text styles read docs/TYPOGRAPHY_TOKENS.md and docs/TYPOGRAPHY.md. Use the current public headers as the API authority; do not invent symbols. Check the feature status and limitations for every component you choose. Use portable C11 for CUI integration. Keep platform and renderer code in host adapters. Keep application values, buffers and explicit component models alive across frames. Use stable IDs and balance every successful begin/end pair. Render borrowed draw data before starting the next frame. Connect actions using return-value events or the documented controlled callbacks. For the native source bundle, read README.md and vendor/include/cui/cui.h. Edit app.c for portable UI; main.c owns the native host. Run make with warnings. Use APP_SOURCES for additional C files and TARGET for the executable name. For Linux automation use an invisible Xvfb display; never DISPLAY=:0 or the maintainer's Wayland session. Browser automation must be headless. For browser work build the real WASM gallery and exercise actual interactions. Report what ran, what remains incomplete, and which renderer/platform was tested. Do not claim full parity or platform support from an API declaration, compilation or a screenshot alone. ``` Replace the application-requirements line before sending the prompt. The source repository's AGENTS.md and your current task instructions determine the engineering workflow. ## Repository maintainer workflow Consumers need the bundle's compiler/Make/system-library prerequisites, not the repository toolchain. Maintainers additionally read `AGENTS.md`, use isolated worktrees for workers with explicit file ownership, and let only the integrator merge. Preserve unrelated changes and all 78 manifest entries. Add meaningful headless tests for behavior changes and compile with warnings: ```sh cmake -S . -B build -G Ninja cmake --build build python scripts/test_local.py --build-dir build ``` The wrapper runs CTest under invisible Xvfb on Linux; never fall back to the maintainer's desktop. GPU hardware checks unsupported there remain deferred. For distribution changes run `python scripts/amalgamate.py` and the repository's lint, format and distribution checks. Use current public headers as API authority, then [Layout](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/LAYOUT_GUIDE.md), [IDs/lifetimes](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/IDS_AND_LIFETIMES.md) and [Debugging](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DEBUGGING.md). Respect Core → base → components; adapters depend on Core. Do not introduce platform/Clay types into public APIs. Feature umbrella distribution tests share a private implementation object; `dist_all` independently compiles implementation and consumer together. Standalone and module-entry tests remain independent. Preserve this coverage and the existing Release optimization, assertions and warning policy; see [distribution test compilation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DISTRIBUTION_TEST_BUILD.md) for the coverage tradeoff. ## Download documentation without browser rendering The built website publishes: | File | Contents | | --- | --- | | `llms.txt` | A concise overview and Markdown links to documentation | | `llms-full.txt` | The documentation bundle with source attribution and current catalog data | | `llm.txt` / `llm-full.txt` | Aliases using the filenames requested for this website | | `markdown/…` | Plain Markdown documents generated from the same repository content | | `catalog.json` | All 78 entries, feature statuses and limitations | | `headers/.h` | Exact byte copies of this build's public headers; API authority | | `api-index.json` | Public symbol names and declarations with links to exported headers | | `build-info.json` | Source revision, build profile and header/document SHA-256 hashes | | `tasks/native-app.md`, `tasks/layout.md`, `tasks/debugging.md` | Focused guide bundles for common tasks | | `docs-index.md` | Full document index, including historical material | | `docs.json` | Document Markdown links, descriptions, keywords and historical flags | Start with `llms.txt` or a focused task bundle, then fetch the exact public header for a declaration. `api-index.json` supplies a `source_revision` and a `symbols` array with `name`, `declaration` and relative `header` links. `build-info.json` records `source_revision`, `build_profile`, `headers_sha256`, `documentation_sha256` and `api_authority`; use these to identify the exported revision rather than mixing headers from another release. Source links are pinned to that revision. Use the full bundle when your tool can accommodate it. `llms-full.txt` excludes documents marked historical, including development/validation reports. They remain available through `docs-index.md` and their `markdown/docs/*.md` exports; `docs.json` carries the `historical` flag. Historical reports are evidence for their recorded checkpoint, not current API or platform guarantees. The current headers and feature manifest take precedence. The index follows the [llms.txt proposal](https://llmstxt.org/). Publishing these files supplies readable documentation; it does not establish a search-ranking result or guarantee that an agent understands every API. ## Ask for evidence For a UI change, request the triggering interaction, expected result, meaningful test and actual running screenshot. For a host integration, request a buildable example, its memory/lifetime contract and the observed backend. For another language, distinguish a tested FFI or WASM example from a proposed binding. ## Keep API documentation synchronized When changing a public API, update both the human guide and agent-facing references in the same change. Add or refresh a guide when composition requires more than a signature, update examples and meaningful tests, and verify the website exports the exact public header plus its `api-index.json` declaration. Header-only inline APIs belong in that index too. The generated `llms.txt`, `llms-full.txt` and focused task bundles must expose the relevant guide; do not edit generated website files instead of the repository sources. For responsive UI, query current container widths in logical units and preserve one application state across breakpoint changes. Omit hidden control subtrees or use the documented input/semantic suppression contracts. For typography, resolve caller-owned roles and register actual faces on the shared measurement/render font owner. Report unsupported tracking, variable-axis or gradient-paint requests as roadmap work rather than inventing token fields. The responsive dashboard's native launcher depends on the SDL3 callback runner. Consult `cui_sdl3.h` and the native starter guide for the shipped runner/manual pump and live-resize contract. A passing portable layout test validates neither a native event loop nor a browser rendering backend. For SDL3 applications, prefer `cui_sdl3_run` for callback-driven composition during OS-managed modal resize. Manual `cui_sdl3_poll` loops remain supported, but their next frame can wait until the operating system releases its modal event pump. Inside runner callbacks, `cui_sdl3_poll` synchronizes IME/cursor state without recursively pumping events. See [Live resize](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/LIVE_RESIZE.md) for lifecycle, threading, frame scheduling and scoped native validation details. --- ## Build your first native CUI app Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NATIVE_APP_STARTER.md # Build your first native CUI app Download the [versioned alpha.4 starter kit](https://github.com/mattmezza/cui/releases/download/v0.1.0-alpha.4/cui-0.1.0-alpha.4-native-starter.tar.gz) from GitHub Releases. It includes the source, bundled fonts and examples described below. For the smallest standalone build, use the **native source bundle**. [Download the archive](https://matteo.merola.co/cui/downloads/cui-native.tar.gz) and its [SHA-256 checksum](https://matteo.merola.co/cui/downloads/cui-native.tar.gz.sha256). Given a C11 compiler, GNU Make, `ar`, pkg-config, SDL3 >= 3.2, FreeType and HarfBuzz development packages, unpack it and run: ```sh tar -xzf cui-native.tar.gz cd cui-native make ./build/native_starter ``` This path includes CUI's portable sources, native SDL3 adapter, text/bidi implementation, generated assets, and Inter 4.1 Regular/Bold fonts with licenses. It requires no installed CUI package or repository checkout. The default renderer is SDL3's `SDL_Renderer`; Sokol and SDL_GPU are separate optional integrations. Linux X11 is the validated native target; Windows, macOS and Wayland native runtime support remains unverified. External system libraries remain prerequisites. See [macOS native builds and bundles](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MACOS.md) and [Linux-to-macOS cross compilation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MACOS_CROSS.md) for the new workflows and their validation limits. Before building, check their visibility: ```sh cc --version make --version ar --version pkg-config --atleast-version=3.2 sdl3 pkg-config --modversion sdl3 freetype2 harfbuzz ``` The archive's README explains the dependency layers and font policy. Ordinary application edits compile only app objects and relink; compiler-generated header dependencies trigger the appropriate CUI recompilation when headers change. `make` never acquires dependencies. To produce the archive from this checkout, run `make native-dist` (Python 3.9+ for this workflow), which writes `build/cui-native.tar.gz`. The shared `cmake/sources.json` drives CMake, the portable header generator and native source selection. Native packaging tests generate twice, compare bytes, unpack outside the repository, verify checksums, build, check incremental rebuilds and render a bounded Xvfb capture through `scripts/test_local.py`. ## Edit the two-file bundle app The archive's `main.c` is the host: it loads both font faces, creates the context, polls input, begins/ends each frame, renders and cleans up. `app.c` is the portable UI: `app_frame` submits boxes, text and the button. Its `bool *clicked` points to state owned by the host across frames. Change the greeting or button in `app.c`, then run `make`; only that application object and executable rebuild. ```sh make APP_SOURCES="main.c app.c" TARGET=build/my_app ./build/my_app ``` Add new relative `.c` paths to `APP_SOURCES`. Keep the executable directly in `build/` for automatic font discovery, or provide both font paths explicitly. The [bundle README](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/native_bundle/README.md) is the canonical consumer build contract. Read [Layout](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/LAYOUT_GUIDE.md), [IDs and lifetimes](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/IDS_AND_LIFETIMES.md) and [Debugging](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DEBUGGING.md) before growing the application. The existing installed-library starter below remains useful for projects that prefer an installed CUI package and a larger three-page example. Start with [examples/native_starter](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/native_starter/README.md). It is an ordinary C11 desktop app: a left sidebar selects Home, Projects and Settings; an account menu stays at the sidebar bottom; Settings edits a name, toggles notifications and saves local state. Sign-in/out is a demo state change, with no credentials or network request. ![Native starter Home page](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/native_starter/screenshots/home.png) ## Prerequisites Use a C11 compiler (GCC, Clang or another conforming compiler), CMake 3.20 or newer, Ninja, pkg-config, SDL3 **3.2 or newer**, FreeType and HarfBuzz development packages, and a readable `.ttf` or `.otf` font. The Make path additionally needs Make. Building CUI itself also needs Python 3; its optional C++ ABI example can be disabled as below, so this path only requires a C compiler. SDL2 is not interchangeable with SDL3. A desktop display/session is needed to open a window; Xvfb can provide an automated Linux test display. The commands below assume those tools and libraries are already installed. Check what pkg-config sees before building: ```sh cc --version cmake --version ninja --version pkg-config --atleast-version=3.2 sdl3 pkg-config --modversion sdl3 freetype2 harfbuzz ``` ## Get the source ```sh git clone https://github.com/mattmezza/cui.git cd cui ``` ## Build CUI, then the app From the CUI repository root, install into a directory owned by your user: ```sh cmake -S . -B build -G Ninja -DCUI_BUILD_NATIVE=ON \ -DCMAKE_C_COMPILER=cc -DCUI_BUILD_CPP_EXAMPLE=OFF \ -DCMAKE_INSTALL_PREFIX="$PWD/build/prefix" cmake --build build cmake --install build export PKG_CONFIG_PATH="$PWD/build/prefix/lib/pkgconfig${PKG_CONFIG_PATH:+:$PKG_CONFIG_PATH}" pkg-config --exists cui-sdl3 cmake -S examples/native_starter -B build/starter -G Ninja cmake --build build/starter python scripts/test_local.py --build-dir build/starter ./build/starter/native_starter --font /absolute/path/to/your/font.ttf ``` For example, this machine uses `/usr/share/fonts/noto/NotoSans-Regular.ttf`. Choose a font that exists on your machine; CUI does not discover an OS font by family name. If `cui-sdl3` is missing, inspect CUI's CMake output and confirm the SDL3/FreeType/HarfBuzz development packages are visible through pkg-config. The starter opens one regular face. CUI does **not** synthesize bold, semibold or italic. Register the matching files before measuring or drawing styled text; otherwise an unavailable style falls back to the regular face: ```c /* font is the regular face returned by cui_font_open. Check both results. */ bool bold_ok = cui_font_register_style(font, (cui_text_style){.weight = CUI_TEXT_WEIGHT_BOLD}, "/path/to/NotoSans-Bold.ttf"); bool semibold_ok = cui_font_register_style(font, (cui_text_style){.weight = CUI_TEXT_WEIGHT_SEMIBOLD}, "/path/to/NotoSans-SemiBold.ttf"); if (!bold_ok || !semibold_ok) { /* report missing assets to your host */ } ``` Ship these faces with your app or supply explicit paths; filenames vary between font families and installations. For a single-executable distribution, compile font bytes into static arrays and open them with `cui_font_open_memory` instead. See [embedding fonts](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TEXT.md#embed-fonts-in-a-native-executable) for a complete header-generation example, buffer lifetime rules, and style/fallback registration. The example's CMake project consumes **installed** packages and does not build the repository as a subdirectory. You can copy the whole `native_starter` folder elsewhere and run `cmake -S /path/to/copied/folder -B /path/to/app-build -G Ninja` with the same `PKG_CONFIG_PATH`. ## Make or a direct compiler command With the same installed prefix exported above: ```sh make -C examples/native_starter make -C examples/native_starter test ./examples/native_starter/build/native_starter --font /absolute/path/to/your/font.ttf ``` Or, from the example directory, compile the two app sources directly: ```sh cc -std=c11 -Wall -Wextra -Wpedantic \ $(pkg-config --cflags cui-sdl3) main.c app.c \ $(pkg-config --static --libs cui-sdl3) -o native_starter ./native_starter --font /absolute/path/to/your/font.ttf ``` Choose Clang with `-DCMAKE_C_COMPILER=clang` when configuring a fresh CUI build and `CC=clang` for Make; `cc` normally selects your system compiler. CMake uses C11 without compiler extensions. Keep libraries **after** source/object files. CUI installs static archives, so use `--static`: it includes private adapter/font dependencies. In the tested prefix, the output included `-lcui_sdl3 -lcui_text -lcui -lm`, `-lcui_bidi`, `-lSDL3`, FreeType/HarfBuzz and their platform dependencies. Use pkg-config's actual output rather than copying one machine's entire linker line. This includes `-lm` where required. The CMake example likewise uses `CUI_STATIC_*` results. ![Bottom account popup](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/native_starter/screenshots/account.png) ## Where to change the app Read [app.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/native_starter/app.h) for the small application state and stable control IDs, then [app.c](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/native_starter/app.c) for layout and callbacks. Each frame submits the current page. The sidebar uses actual `cui_sidebar_menu` activation callbacks; the account popup uses `cui_menu` with an above-trigger anchor. A growing spacer places its trigger at the bottom. Settings uses `cui_input_ex`, `cui_checkbox` and `cui_button`. `changed()` in [main.c](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/native_starter/main.c) is a concrete callback seam for your persistence or application services. State currently lasts only until exit. `main.c` opens the font, installs styled measuring and font metrics, creates the SDL3 host and Core context, then polls input, gets the logical window size, submits the app, applies its cursor and renders. The clipboard interface is passed into the text input. The SDL adapter starts native text input, forwards composition/commit events and synchronizes the prior frame's caret rectangle on poll; the input owns its preedit state. This uses the supported SDL adapter, without asserting every OS IME has been tested. Rendering and all font/SDL operations stay on the main thread. Destruction runs in reverse ownership order. The loop uses a simple 16 ms step to keep the starter readable. A production app can use an actual clock delta, persist state, add scrollable content and responsive navigation, and supply fonts covering its text. The fixed 220 px sidebar targets desktop-sized windows; this starter does not implement mobile navigation. ## Verify it `test_app.c` exercises real Core/component reducers without opening a window: navigation callbacks, bottom-account geometry, sign-in/out, menu settings, Escape dismissal, text-model editing, notification changes and save callbacks. Run the app for a bounded native capture with: ```sh ./build/starter/native_starter --font /absolute/path/to/font.ttf \ --frames 3 --capture build/starter/home.bmp ``` Linux automation can prefix that command with `xvfb-run -a -s "-screen 0 1600x1000x24" env SDL_VIDEODRIVER=x11 SDL_RENDER_DRIVER=software`. Use a screen at least as large as the app window for coordinate-based interaction. The screenshot above is from the actual SDL3 window, not a browser mockup. Historical starter validation (before the current usability additions) checked an actual local installation: standalone CMake/CTest, Make with warnings treated as errors, the direct compiler command, and a Core-only build of `app.c` plus `test_app.c` all passed. At that historical checkpoint, integrated repository CTest passed 96/96, sanitizer checks 96/96 and portable WASI suites 80/80. An Xvfb SDL3 window exercised Projects navigation, bottom-menu sign-in/out, Settings navigation, editing the name to Grace, disabling notifications and saving; callbacks reported the resulting state. These checks cover the starter, not every platform, font or IME. ![Actual native settings after saving](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/native_starter/screenshots/settings.png) For a daemon-style native host, create the window hidden from its first instant: ```c cui_sdl3 *host = cui_sdl3_create_with_options("Notifications", 480, 320, font, (cui_sdl3_window_options){.initially_hidden = true}); /* Later, on the main thread: */ if (host) cui_sdl3_set_visible(host, true); ``` The option sets SDL's hidden flag in the window constructor; no visible window is created and then hidden. Zero options and `cui_sdl3_create()` preserve visible creation. `cui_sdl3_is_visible()` queries SDL's hidden flag; it does not establish whether a window is occluded or minimized. Visibility operations are main-thread only and the OS may map/unmap asynchronously. The old constructor ABI is unchanged; the new options type does not extend any existing by-value structure. Sokol and SDL_GPU adapters do not own windows: their host must request hidden creation. Bridge and language builder native runners expose opt-in hidden creation through independent window options; see [binding builders](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BINDING_BUILDERS.md). Linux X11/private-Xvfb validation does not establish Wayland, Windows or macOS behavior. --- ## Resizable visible-divider regression Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/RESIZABLE_DRAG_AUDIT.md # Resizable visible-divider regression The reported failure reproduced on the actual HTTPS gallery revision `44819c1` at a 1920 × 1080 viewport. Normal desktop mouse and actual Chromium CDP touch contacts began on the visible divider. Both pane bounds stayed at Explorer 300 px and Editor 600 px, with zero width change after dragging. Before/after screenshots and pane rectangles were captured in `/tmp/cui-resizable-wide` during the audit. At 1280 px, the same gestures worked (212 → 260.5 → 300 px), explaining why previous narrower browser tests missed the problem. The gallery configured hard maxima of 300 and 600 px while its responsive group could be wider than their combined 900 px. Both panes reached their maxima. A split conserves space by transferring it between panels; neither pane had any capacity to accept the transfer. The model correctly returned `INFEASIBLE` and preserved the declared constraints. This was gallery configuration, not a mouse capture or Core touch routing defect. The Explorer keeps its 80–300 px range. The Editor now has maximum capacity equal to the responsive group extent, so it can fill and accept transfers at large widths. Vertical mode starts with a balanced 105/105 px split in its 210 px group; changing orientation resets that story's split to the appropriate initial sizes. Resizing within the same orientation retains user state. Both minima remain 80 px, and normal movement stops at a bound. The underlying `INFEASIBLE` policy, callback semantics, capture and touch drag priority are unchanged. ## Strict browser checks Run against a locally built gallery: ```sh uv run tests/web/test_resizable_drag.py --directory build/web \ --chromium /path/to/chromium ``` Without `--directory`, the script uses the actual HTTPS gallery. It fails on any geometry assertion. It uses DOM controls only to configure the story, real mouse input for desktop cases and `Input.dispatchTouchEvent` for touch cases; it never calls reducer exports to resize. The touch cases focus the keyboard fallback with a real touch tap. The matrix contains 24 independent cases: 390/1280/1920 px viewport widths × horizontal/vertical × comfortable/compact density × mouse/touch. Each asserts actual Explorer growth, Editor shrinkage and boundary movement, enabled content following horizontal pane widths, disabled geometry remaining fixed, and arrow-key resizing. The wide cases save actual screenshots before/after. The JSON report records pane rectangles. Resizable does not expose a size variant or rounded option in its API/story; these were not fabricated as tested selectors. The integrator is handling separate gallery option presentation. ## Headless and sanitizer checks `tests/unit/test_resizable.c` adds eight actual styled split scenes: narrow/wide extent × both orientations × mouse/touch. They assert changed panel bounds, content bounds following the panel, conserved total extent, and exactly one completion callback on release. Existing disabled, keyboard, overlays, clipping, nested geometry and model constraint tests remain intact. These verify the responsive configuration contract; the pre-fix production failure is the strict HTTPS wide browser reproduction, not a claim that valid Core constraint behavior needed changing. Warning-enabled native build passed. Full CTest passed 93/94, with only the root-owned generated-distribution check stale after the public header comment. Resizable and base-only Resizable passed ASAN/UBSAN (2/2). The fixed local strict browser matrix passed 24/24; the existing component touch suite passed 42/42 and rendered all 78 stories. Headless Chromium/CDP does not establish physical mobile device coverage or every consumer's custom appearance/constraint setup. --- ## Start building with CUI Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/START_HERE.md # Start building with CUI CUI composes a user interface in portable C11. Your application supplies state and calls components during a frame; CUI produces a draw list and a semantic tree. A renderer paints the list, and a host supplies window events, time, clipboard and other platform services. CUI is experimental. The gallery contains all 78 comparison entries, but the [feature manifest](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/gpui-parity.json) records incomplete behavior. Begin with the controls you need and check their documented limits. ## Start with a native application Follow [Build your first native CUI app](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NATIVE_APP_STARTER.md) for a complete three-page desktop starter, sidebar navigation and a bottom account menu. It explains dependencies, compiler choice, CMake, Make, static linker flags and native launch commands. The source is small enough to copy into your own app. ## Try a headless C program From the repository root: ```sh cmake -S . -B build -G Ninja -DCUI_BUILD_NATIVE=OFF cmake --build build python scripts/test_local.py --build-dir build ./build/hello_world ``` This portable example creates real CUI draw commands and prints their count. It exercises layout without opening a window. A C11 compiler, CMake, Ninja and Python3 are needed for these commands; core CUI itself uses the standard library and vendored Clay. ## Choose your host | Path | What it does | Next reference | | --- | --- | --- | | Existing native application | Send events to a context and paint its draw list in your renderer | [Embedding contracts](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/INTERFACES.md) | | SDL3 workbench | Opens the native gallery when SDL3, FreeType and HarfBuzz are available | [Repository setup](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/README.md) | | Browser | Compiles C to WebAssembly; JavaScript supplies browser input and canvas rendering | [Web gallery build](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/WEB_GALLERY.md) | | Portable/headless | Runs layout, interaction and renderer tests without a window | [Core lifecycle](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CORE.md) | The browser gallery is an example host. Applications using CUI do not need a browser engine. Native adapter availability and actual runtime evidence are listed in the [platform matrix](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PLATFORM_MATRIX.md). ## Compose a frame The following function belongs in a host that already created `ui` and a theme. The host owns `clicks`, calls this function for each frame, then passes the returned draw list to its renderer before the next frame starts. ```c #include "cui/cui_components.h" cui_draw_list draw_counter(cui_context *ui, const cui_theme *theme, unsigned *clicks, float width, float height, float elapsed_seconds) { if (!cui_begin_frame(ui, width, height, elapsed_seconds)) return (cui_draw_list){0}; cui_begin_box(ui, cui_id_from(ui, "counter"), (cui_box){.width = -1, .height = -1, .padding = 24, .gap = 12, .background = theme->background}); if (cui_button(ui, cui_id_from(ui, "increment"), theme, cui_string("Increment"), false)) { ++*clicks; cui_invalidate(ui); } cui_end_box(ui); return cui_end_frame(ui); } ``` Stable IDs connect this frame's controls to the previous frame's hit regions. Keep domain state outside this function. Frame-owned draw data remains borrowed until the next frame; render it before advancing the context. ## Adapt a real application Use [responsive containers](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/RESPONSIVE_LAYOUT.md) for named mobile-first width policies, container-local pane fitting, and a runnable dashboard with navigation/account callbacks. Keep one application state while switching between stacked content, a Menu disclosure and a persistent sidebar. The guide explains native launch and headless geometry/interaction tests. Use [reusable typography tokens](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TYPOGRAPHY_TOKENS.md) for body/heading/code roles and per-call overrides; [Typography](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TYPOGRAPHY.md) explains actual family and variant registration. These shipped helpers compose existing CUI layout/text APIs. They do not imply a CSS engine or advanced typography roadmap completion. ## Learn the interaction model Read [state and callbacks](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/IMMEDIATE_AND_STATE.md) for immediate frame composition, retained values/models, return-value events and controlled callbacks. Component headers and the gallery Usage section show the concrete types for each control. Each code block in website documentation has a Copy button. ## Work with an AI coding agent Use the [copyable agent setup prompt](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/AI_AGENTS.md). The website also publishes `llms.txt` as a documentation index and `llms-full.txt` as a plain-text bundle. Both are generated from these repository documents, alongside the component-status manifest. The requested `llm.txt` and `llm-full.txt` names are aliases. ## Build with another language Use [Python, JavaScript, TypeScript, Go or Rust component builders](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BINDING_BUILDERS.md) to author UI trees and callbacks in your own language. The guide includes native window build commands and examples; the [coverage table](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_COMPONENTS.md) records supported controls and the limits of each binding. The full component catalog is still being bound and validated. The [C-host examples](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/LANGUAGE_BINDINGS.md) also demonstrate embedding an existing C-authored application. For composition, start with [Layout](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/LAYOUT_GUIDE.md), then [IDs and lifetimes](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/IDS_AND_LIFETIMES.md) and [Debugging](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DEBUGGING.md). The [two-file native bundle](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NATIVE_APP_STARTER.md) is the standalone consumer path; [agent guidance](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/AI_AGENTS.md) separates consumer and maintainer workflows. --- ## Accessibility Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/ACCESSIBILITY.md # Accessibility Controls submit an independent semantic snapshot with identity, role, accessible name, bounds, disabled/checked/focused state and scalar value. Compound controls also expose relationships, selection, scroll ranges and modal scopes. Headless tests validate named subsets of these states and keyboard interactions; they do not establish complete family acceptance. The browser gallery projects these snapshots into DOM controls for focus and assistive technologies. Its hidden native text-input bridge supports composition for Input, Textarea, Editor and Questionnaire, plus Numeric, OTP and Combobox; per-consumer filtering and history differ. Caret/selection painting, pointer positioning and Unicode grapheme/word editing have tests. Bidirectional caret geometry, full browser screen-reader testing and mobile virtual-keyboard acceptance remain unfinished. See [IME](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/IME.md) and [editing](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/EDITING.md). Native Windows UIA, macOS AX, Linux AT-SPI, Android/iOS accessibility bridges and AccessKit integration remain unimplemented. Real screen-reader, contrast, text scaling, reduced-motion and touch-target acceptance is required before v1.0. High contrast is a token theme with tested control colors, not platform certification. See [v1 readiness](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/V1_READINESS.md) and [platform evidence](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PLATFORM_MATRIX.md). --- ## Targeted accessibility actions (Core prerequisite) Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/ACCESSIBILITY_ACTIONS.md # Targeted accessibility actions (Core prerequisite) Portable Core now queues `CUI_ACCESSIBILITY_FOCUS` and `CUI_ACCESSIBILITY_ACTIVATE` by stable `cui_id`, without pointer coordinates or synthetic keyboard input. This is an action-routing prerequisite; it does not register a native accessibility tree or provide an OS/screen-reader bridge. ```c if (cui_accessibility_action_supported(ui, button_id, CUI_ACCESSIBILITY_ACTIVATE)) { bool admitted = cui_queue_accessibility_action(ui, button_id, CUI_ACCESSIBILITY_ACTIVATE); /* Check admitted and cui_last_error(ui); admission is not execution. */ } ``` Call both APIs between frames on the context's owning thread. The query reads only the last completed semantic snapshot and returns false during an open frame. Queueing during a frame reports `CUI_ERROR_LIFECYCLE`. Invalid action enums, zero, missing, disabled, modal-blocked or unsupported targets report appended `CUI_ERROR_INVALID_ACTION`. The shared input queue holds 256 events; a valid action when full reports `CUI_ERROR_CAPACITY`. Failure appends nothing and changes no focus, activation, pointer or capture state. Errors follow the existing sticky Core error contract; `cui_clear_error` permits callers to acknowledge rejected external requests without poisoning later work. No platform/Clay types or borrowed payload are needed. Existing enum ordinals and zero event initializers remain intact. The new event type is `CUI_EVENT_ACCESSIBILITY_ACTION`; its appended `accessibility_target` and `accessibility_action` fields provide distinct source provenance. Direct `cui_queue_event` submission of that event uses identical validation, and unrelated pointer/key/text fields are discarded. No OS callback may call these APIs concurrently; a future native adapter must copy requests and drain them on the main thread. ## Supported targets and delivery Focus uses Core's normal focusability rules, including explicit `focusable` containers and programmatic-only (`tab_index == -1`) controls. `no_focus` and disabled IDs are rejected. It makes focus visible, preserving pointer and Space captures, and respects the published modal scope. Passive label focus proxies are not silently redirected; submit their actual eligible target ID. Default Activate roles are Button, Link, Checkbox, Switch, Radio, MenuItem, MenuItemCheckbox and MenuItemRadio. An explicit `pointer_activatable` semantic also opts in, including `no_focus` pointer-only controls. Activate does not move focus, pointer position or capture. Textbox, Slider, Scrollbar, Tab, Option, TreeItem, table headers/grid cells and passive containers have no default Activate capability in this first increment. Focus remains available where eligible. Consumers that opt into a custom activation capability must implement that action rather than rely on keyboard-only handlers. Dispatch revalidates the completed target and produces normal `cui_event_target`/`cui_event_activation` metadata and pending activation slots. Widget submission checks current disabled state, semantic role and active modal scope. Current inert/layout-only or removed targets cannot retain a pending action into another frame; completion withdraws their metadata. A removed or newly disabled Focus target restores the prior surviving focus where possible, without overriding a subsequent explicit focus change. Removal of multiple queued Focus targets unwinds in reverse order. Accepted queue admission therefore does not guarantee the widget will still be eligible or submitted in that frame. Stable IDs represent stable logical widgets: use a new ID for a new widget identity. Core cannot distinguish replacement with an identical ID/role and no intervening completed removal. Capability details are declared in semantic submission after `cui_interact`; admission follows their published snapshot. Current disabled/role/scope checks are immediate, while final semantic withdrawal occurs at frame completion. Applications should keep published action capability consistent with their current reducer and must not perform speculative external side effects during layout-only passes. ## Consumption and existing activation semantics Simple controls consume pending activation through their normal `cui_interact` path; actual styled button and checkbox tests verify callback/value changes. No request is replayed on an idle frame. Multiple same-ID pending activations coalesce into one `activated` boolean in a frame, exactly as existing pointer/key activations do. Individual event-aware reducers can inspect each event. Queue requests across frames if separate callbacks are required from a boolean API. A deferred/capture-phase owner may handle the event and call `cui_consume_event`. For the new accessibility event, consumption also cancels its pending activation and clears activation metadata, so a subsequently submitted widget cannot replay that callback. Ordinary input consumption behavior is unchanged. `cui_cancel_event_activation` suppresses activation alone while retaining the event target, matching its existing capture-phase contract. Deferred handlers must check consumption and validated activation, not event type alone. ## Compound reducer audit and verification Read-only source audit found Tabs and List selection reducers keep an event-local cursor and reset it to the explicit target only for pointer-up. Multiple targeted accessibility activations can select an earlier cursor; these roles are therefore Focus-only by default pending assigned base fixes. Menu reducers generally use activation metadata but have not received native accessibility acceptance here. Tree/table reducers also inspect activation metadata; full selection, expansion, scroll and value/text actions need independent family tests. No base/component implementation was changed, and no full compound-family support is claimed. Headless Core tests exercise actual styled button/checkbox scenes, separate target and focus, same-ID coalescing, consumed/deferred/cancelled activations, invalid enums, queue capacity, programmatic-only stops, Tab and pointer-only eligibility, removed/reintroduced/changed-role targets, current-frame disabled/modal/inert rejection, ordered Focus plus keyboard events, focus rollback, and preserved pointer/Space capture. Full warning build and CTest run: 90/91 pass; only expected stale generated distribution fails. Four focused sanitizer checks (Core, base, components, choice) pass. Native transport/screen-reader validation belongs to the optional bridge implementation, not this prerequisite. --- ## Alert and Bubble slots Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/ALERT_BUBBLE_GUIDE.md # Alert and Bubble slots Source audit: upstream kit 0.7.1, commit `87d10ae5e1299d1be18670a37570c5402f952e34`, `crates/component/src/alert.rs` and `bubble.rs`. This is an original C implementation inspired by those contracts. Alert retains INFO as its zero kind. `CUI_ALERT_DEFAULT` adds a neutral surface. Info, success, warning and error use the corresponding theme foreground, border and tinted surface. A banner removes the border/radius and omits title text and the title callback. `title_content`, `content`, and `action` replace or extend the text slots in that order. Dismissal still returns activation and optionally changes caller-owned `visible`. `cui_bubble()` accepts message text or a custom `content` callback, incoming/outgoing alignment, an optional reaction callback and top/bottom ordering. Filled text uses `on_primary`; semantic variants use their kind foreground. Secondary/muted use a subdued neutral surface; outline uses background and border; ghost removes surface and padding. `cui_bubble_foreground()` supplies the same foreground when composing through the legacy begin/end API. ```c cui_bubble(ui, id, theme, (cui_bubble_options){ .variant = CUI_BUBBLE_SUCCESS, .alignment = CUI_BUBBLE_OUTGOING, .width = 400, .message = cui_string("Saved successfully"), .announcement = CUI_BUBBLE_ANNOUNCE_POLITE }); ``` Callbacks run synchronously with borrowed context/theme and a semantic foreground. Use percentage-width boxes to fit the current parent; a callback must balance all begin/end calls and must provide its own controls through base-backed components. Custom text chooses the supplied foreground explicitly. Supply `accessible_name` when custom content has no message text. Callback/user storage remains caller-owned; no retained allocation occurs. Invalid Bubble enums omit the component. The convenience Bubble reserves up to 80% of its row for the surface (100% for ghost) and aligns its content within that region. A positive width specifies row width; zero uses parent width. With `state == NULL`, reactions occupy normal flow above/below, aligned along the row. Supply a unique zero-initialized caller-owned `cui_bubble_state` to measure the first frame and settle an overlapping pill on the selected surface edge. The pill extends three quarters of its height outside the surface, reserves room within the row to keep adjacent bubbles from covering controls, and inherits ancestor clipping. Geometry changes request a bounded measurement redraw; changes to custom slot content require incrementing `content_revision`. Width, variant, alignment, reaction presence and theme font/padding changes trigger measurement automatically. The cache must not be shared between IDs. Exact first-frame anchored placement is not promised: Core has no current-frame measured-anchor attachment primitive. There is no separate BubbleGroup API; compose a column using existing layout boxes. These remain explicit parity gaps. Alert publishes ALERT; Bubble defaults to a passive GROUP, with POLITE mapping to STATUS and ASSERTIVE to ALERT. These roles request semantics only. Actual announcements depend on host/native/browser accessibility adapters and are not proven by headless role tests. No reaction area itself becomes a tab stop; controls composed within it preserve their own button semantics. Headless evidence: `tests/unit/test_alert_bubble_slots.c` exercises both themes, every Alert kind/Bubble variant, slot ordering, incoming/outgoing placement, top/bottom reactions, first-frame measurement and settled overlap without perpetual redraw, passive status semantics and disabled action controls. Existing content tests cover controlled dismissal. The gallery Bubble story demonstrates semantic kinds, alignment and measured reaction pills. `tests/web/test_alert_bubble_slots.py` checks actual WASM paint colors, placement and reaction ordering at desktop/mobile widths. Pointer/Enter activation is covered headlessly and real Chromium CDP touch toggles are covered in the browser. Native screen-reader announcement delivery remains unverified. --- ## Alert completed-dismiss observations Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/ALERT_EVENTS.md # Alert completed-dismiss observations Include `cui/cui_alert_events.h` and call `cui_alert_events` to observe the built-in Dismiss action. This additive native C facade calls the existing `cui_alert` once. Its original options, Button style, content/action slots, visibility assignment, drawing and bool result remain unchanged. ```c static void dismissed(void *user, const cui_alert_dismissal *event) { app_state *state = user; state->last_dismissal = *event; /* Pointer-free copy. */ state->dismissals++; } cui_alert_dismiss_result result = cui_alert_events( ui, alert_id, &theme, (cui_alert_options){.kind = CUI_ALERT_INFO, .message = cui_string("Saved"), .visible = &state.visible, .dismissible = true}, (cui_alert_dismiss_handler){dismissed, &state}); ``` The [standalone headless example](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/alert_events/main.c) shows the complete setup. Link the usual `cui` library; no new dispatch service or retained listener registration is required. `legacy_dismissed` is exactly the old aggregate bool. `dismissal_count` is zero or one for an eligible completed built-in dismissal, including when no callback is installed. A callback runs at most once per invocation, even when multiple accepted inputs activate Dismiss. Choose the callback or result for each side effect; reading the result never invokes or replays a callback. Observation occurs synchronously after the old function has ended its Alert box and, if supplied, assigned `*visible=false`. `visibility_assigned` records that assignment, even if a render slot already set the value false. It does not claim a transition or closed lifecycle. Without visibility storage, accepted dismissal still returns true and can notify; `visibility_assigned` is false. The owner still decides whether to omit the Alert next frame. Visibility is checked once at entry. Title/body/action slots retain their old order and may change owner visibility or consume input before the Dismiss Button. A slot changing visibility alone does not synthesize a completion. Consuming an input uses existing Core policy: it cancels the tested accessibility action but does not revoke an ordinary already-accepted Enter-down activation. The facade adds no general input-cancellation promise. The observer can set visibility true again; no second assignment or veto follows, and the frozen completion result stays unchanged. Slot `options.user` and handler `user` are independent. Invalid arguments produce `valid=false`; initially hidden Alerts are valid omissions with `submitted=false`. Passive inert/layout-only submission preserves legacy behavior but has no eligible observation/count. The payload's common metadata has `kind=ACTIVATE`, public Alert ID, actual entry frame, `UNKNOWN` source, and only `HAS_FRAME`. There is no per-input event index, activation snapshot, pointer/touch coordinate, source, close reason or timestamp. Even a single accepted input does not upgrade this aggregate metadata. Actual input routing stays in the existing Button. Custom action-slot child events are separate and are not Alert dismissals. Options, handler and active eligibility/frame are copied at entry. Payload views are borrowed synchronously; a copied payload outlives the frame/context. Keep visibility, UI/theme, slot resources and users alive through their existing submission/rendering lifetimes. Do not recurse into UI submission, destroy the context, free/rebind active resources or unwind through C callbacks. Request teardown in application state and perform it after the frame. This native slice does not provide per-input callbacks, controlled dismissal, veto/default cancellation, retained open/close policy, AlertDialog forwarding, async listeners or a Python/Node/TypeScript/Go/Rust observer binding. The retained bridge's existing Alert does not configure native dismissibility/visibility; its foreign queued notifications do not implement this observer contract. See the [design checkpoint](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/ALERT_EVENTS_SLICE.md) and [binding coverage](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_BINDINGS.md). The focused headless regression covers pointer/touch, Enter/Space, genuine Core accessibility activation, multiple accepted inputs, callback-independent counts, no visibility storage, slot/observer owner writes, omission/passive submission, custom actions, copied payload lifetime, legacy shape/SVG software pixels, text command geometry/style/content and semantics. Font rasterization is not exercised by the portable no-font fixture. This is portable software/Core evidence, not native screen-reader, GPU or full Alert event parity. Run CTest on Linux through `python scripts/test_local.py --build-dir `. --- ## API and ownership Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/API.md # API and ownership Public headers live in `include/cui/`; generated embeddable headers in `dist/`. ```c cui_context *ui = cui_create((cui_config){.width=800, .height=600}); cui_theme theme = cui_theme_light(); cui_begin_frame(ui, 800, 600, 1.0f/60); cui_begin_box(ui, cui_id_from(ui, "root"), (cui_box){ .width=-1, .height=-1, .padding=24, .gap=12, .background=theme.background }); if (cui_button(ui, cui_id_from(ui, "save"), &theme, cui_string("Save changes"), false)) { /* Save application data here; explicitly invalidate if changed UI requires another frame. */ } cui_end_box(ui); cui_draw_list list = cui_end_frame(ui); /* renderer.render(renderer.user, &list, theme.background); */ cui_destroy(ui); ``` Width/height zero fit contents, negative grow, positive fix logical-pixel size. Begin/end pairs must balance. Frame text and accessible names are copied into a bounded context arena. The draw list and semantic tree remain valid until the next begin; consume them synchronously or copy to host-owned storage. User strings can be transient because CUI copies them during submission. The error state is sticky until explicitly cleared; capacity errors do not authorize reuse of truncated output as complete UI. Stable nonzero `cui_id` values are supplied by applications or derived from scoped keys. Identity follows keys when lists reorder. Duplicate public IDs and folded layout-ID collisions are errors. CUI retains focus/capture and previous regions; it does not own arbitrary domain objects or provide a general widget state registry yet. Persistent domain data and edit buffers remain app-owned. Queue input before begin. Events are interpreted against the prior frame, then consumed once by matching controls. Multiple activations of one control in a single frame coalesce into its boolean return. The first frame has no hit regions; initialize layout before accepting interaction. Removal/disable cancels retained focus and capture. Core handles Tab/reverse Tab, Enter and release-of-Space activation. See CORE.md, EDITING.md and OVERLAYS.md for exact limits. UI context and optional font objects require single-thread ownership. Independent contexts may be interleaved on that thread; Clay's internal current-context pointer prohibits concurrent UI calls. Host asynchronous work must hand results back on the UI thread. Optional renderers own GPU resources with their device's thread affinity; borrowed host device/window/font must outlive the renderer. The default text measurer is approximate and unsuitable for international text. The native text adapter supplies contextual geometry, explicit font fallback and optional bidirectional analysis; register matching measurement and paint callbacks. Editing offsets are UTF-8 byte indices. Explicit legacy scalar operations remain available, while interactive editing uses grapheme/Unicode-word operations. Consumer and platform coverage remains partial: see [editing](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/EDITING.md), [contextual text](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CONTEXTUAL_NATIVE_TEXT.md), [Unicode wrapping](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/UNICODE_WRAP.md) and [the platform matrix](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PLATFORM_MATRIX.md) for the tested contracts. ## Responsive layout and typography roles Two header-only utilities compose existing Core behavior without global style state or new host dependencies: | Header | Shipped API | Guide | | --- | --- | --- | | `cui/cui_responsive.h` | `cui_responsive_query`, `cui_responsive_at_least`, `cui_responsive_value`, `cui_responsive_fits` | [Responsive containers](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/RESPONSIVE_LAYOUT.md) | | `cui/cui_typography.h` | `cui_typography_token_valid`, `cui_typography_resolve`, `cui_typography_text`, `cui_typography_text_colored` | [Reusable typography tokens](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TYPOGRAPHY_TOKENS.md) | Responsive queries use the caller's current logical container width and named BASE/SM/MD/LG/XL/2XL thresholds. They select ordinary C box properties or whether to submit a subtree; they do not implement CSS or own application state. Typography roles copy caller-owned body/heading/code tokens containing supported family/style, size, line-height, alignment and wrapping options. They do not load fonts, synthesize faces, or add tracking/variable axes. The additional `cui_typography_text_painted` helper supports [linear gradient text](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TEXT_GRADIENT.md) on renderers advertising the corresponding capability. Use the same font mapping for measurement and rendering; see [Typography](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TYPOGRAPHY.md). The native dashboard launcher uses the SDL3 callback runner; consult the current `cui_sdl3.h` and [native application guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NATIVE_APP_STARTER.md) for host lifecycle and live-resize constraints. Portable width policy and text roles do not provide a native event pump themselves. For SDL3 applications, prefer `cui_sdl3_run` for callback-driven composition during OS-managed modal resize. Manual `cui_sdl3_poll` loops remain supported, but their next frame can wait until the operating system releases its modal event pump. Inside runner callbacks, `cui_sdl3_poll` synchronizes IME/cursor state without recursively pumping events. See [Live resize](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/LIVE_RESIZE.md) for lifecycle, threading, frame scheduling and scoped native validation details. ## Decoded video frames `cui/cui_video.h` exposes a caller-owned timeline and a borrowed RGBA frame surface. The host supplies elapsed time and already-decoded frames, handles decoder/audio synchronization, and retains pixels until renderer consumption completes. Generation checks reject frames retired by a seek, restart or loop. See [the video guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/VIDEO_GUIDE.md) for ownership, commands and reproducible headless tests. [Controlled playback controls](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/VIDEO_PLAYER.md) add typed host requests and optional controls above the surface. The [optional FFmpeg example](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/video_player/README.md) demonstrates silent local-file decoding; audio, browser playback and general decoder integration remain planned in [the video roadmap](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/VIDEO_PLAN.md). --- ## Practical application recipes Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/APP_RECIPES.md # Practical application recipes The runnable [mail fixture](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/native_bundle/mail.c) uses the same host as the two-file starter. Build it from the extracted native bundle: ```sh make APP_SOURCES="main.c mail.c" TARGET=build/mail_demo ./build/mail_demo ``` It demonstrates three independent scroll states, scoped repeated avatars/tags, clipped long subjects, a fixed trailing star action, message selection and a Compose/Discard preview. It has no message editor, storage, network or delivery. It uses a desktop pane layout; narrow windows clip rather than switch navigation. The packaging test drives real Core pointer activation for Compose/Discard, selection and starring, then builds and captures the native executable on Xvfb. For a mail row, cap the growing subject column as well as clipping it: an unwrapped child's minimum width can otherwise push the timestamp/star beyond the viewport. Keep the action column fixed. Word-wrap the reader body inside a width-constrained scroll viewport. Give each pane its own `cui_scroll_state`. Use `cui_scrollable_end_ex` only after a successful `cui_scrollable_begin`. The [layout guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/LAYOUT_GUIDE.md) is the canonical sizing reference. Use stable record keys and local IDs for repeated content; see [IDs and lifetimes](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/IDS_AND_LIFETIMES.md). Use exact icon registry names from `cui_icon.h`, check lookup results, and retain text labels for actions when an icon is unavailable. Emoji are not a portable substitute for missing artwork. ## Sidebar custom content callbacks `cui_sidebar_content_fn` has **four arguments**, with the user pointer last: ```c static void folder_label(cui_context *ui, const cui_theme *theme, bool collapsed, void *user) { const char *label = user; if (!collapsed) cui_text(ui, cui_string(label), 14, theme->sidebar_foreground); } ``` Assign it to `label_content` and put the live label pointer in `label_user` on a `cui_sidebar_menu_item`. Its activation callback is a different signature: `void on_activate(void *user)`. The menu's top-level `user` feeds activation, while `label_user`, `icon_user` and `suffix_user` feed their respective content callbacks. Do not cast a three-argument function to the content callback type; use the exact typedef in `include/cui/cui_sidebar.h`. Content callbacks submit children; they do not confer generic click handling on those children. --- ## Architecture Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/ARCHITECTURE.md # Architecture CUI is an experimental C11 framework with an explicit context and Clay layout adapter. `cui.h` has no SDL, OS, GPU or raw Clay API types. `cui_base.h`, editing and overlay models provide behavior; `cui_components.h` adds theme-driven painting. Platform and renderer interfaces are independent of widgets. Optional adapters are compiled integrations. ```mermaid flowchart TD Host[Application / existing host] --> Components[Styled components + tokens] Host --> Base[Unstyled controls / edit / overlays] Components --> Base Base --> Core[Context / IDs / Clay / input / semantics] Core --> Draw[Versioned C draw list] Draw --> Software[Deterministic software] Draw --> SDL2D[SDL3 Renderer compatibility] Draw --> GPU[SDL_GPU / SPIR-V] Draw --> Sokol[Sokol / GLCORE] Platform[Host or SDL3 events / clipboard] --> Core Text[Optional FreeType + HarfBuzz] --> Core Text --> Software Text --> SDL2D Text --> Sokol Text --> GPU ``` The SDL_GPU adapter borrows an existing GPU device and claimed window. It owns its pipeline, offscreen target, glyph atlas and transfer buffer. Window input remains host responsibility. Its initial shaders are SPIR-V/Vulkan; Metal/D3D shader builds remain pending. The SDL_Renderer adapter supplies the convenience window/event loop and caches bounded glyph textures. The software renderer accepts the same command stream without a GPU. Contexts own fixed-budget Clay memory, commands, copied frame strings, semantics and prior hit regions. UI operations are confined to one thread; switching between contexts is supported, simultaneous thread access is not. Draw-list and semantic strings expire at the next begin frame. A text editor owns bounded scratch/history while its text buffer belongs to the application. Heavy models expose explicit handles. Events queue before begin and dispatch in order against the previous completed layout. The initial frame establishes hit regions. Core focus scopes keep modal events inside the prior top scope, route dismissal to its reducer, and restore an enabled submitted trigger. Current composition then consumes activation and builds the next semantic and paint snapshots. Native widgets and semantic adapters remain future work. Single-TU distribution is generated from modular source; the same source compiles into a static library. Third-party source stays pinned and attributed. No JavaScript or Rust runtime is required. All 78 families remain in the status manifest; tested partial APIs are not full family verification. The independent Sokol adapter borrows a current OpenGL context and framebuffer descriptor. It owns bounded GPU buffers, shaders and a glyph LRU; it can borrow the host Sokol runtime or initialize its own. The adapter has no SDL dependency. GLCORE is the implemented backend, with actual Intel/Mesa pixel evidence; upstream backend availability is not CUI backend support. See backends/sokol/README.md for commit ordering and ownership. The virtual-list and dock handles retain data between frames with fixed configured capacity. Dock owns its split/tab tree and transactional restore bank; the application owns panel content. Plot scales and clipped geometry are allocation-free value operations. These are base models; their styled widgets and compound keyboard/accessibility behavior remain pending. --- ## Attachment action observers Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/ATTACHMENT_EVENTS.md # Attachment action observers Include `cui/cui_media_events.h` and call `cui_attachment_events` with the same arguments as `cui_attachment`, plus a borrowed `cui_attachment_handler`. It returns `control` (the legacy `cui_attachment_result`) and actual callback counts `activation_count`, `remove_count`, `retry_count` (each zero or one). The old options/state/result layouts and entrypoint remain unchanged. ```c static void remove_requested(void *user, const cui_attachment_action_event *event) { bool *remove_after_frame = user; /* Unrelated host flag, not active card state. */ *remove_after_frame = true; /* Copy *event to retain action/metadata. Do not destroy active resources here. */ } /* During UI submission using existing caller-owned options/state/theme: */ /* cui_attachment_event_result result = cui_attachment_events( ui, id, theme, &state, options, (cui_attachment_handler){.on_remove = remove_requested, .user = &pending_remove}); */ ``` Typed handlers are `on_activate` (OPEN), `on_remove` (REMOVE), `on_retry` (RETRY). Each enables only its corresponding existing action path even if its legacy callback is absent. Absent typed handlers retain original availability. With no typed handlers, the facade uses the legacy operation directly. Original callbacks always receive the untouched `options.action_user`; typed callbacks receive `handler.user`. Other callbacks (images, children, actions, overlays) retain their own userdata and behavior. The complete old operation runs once. At its original callback point after paint and tooltip work, callbacks run in fixed category order: old click, typed OPEN; old remove, typed REMOVE; old retry, typed RETRY; then the original focus scope ends. Absent callbacks are skipped. Repeated input coalesces into one callback per category; media and description retry together still yield one RETRY. This is category order, not global input order. Reading returned flags does not replay callbacks. These are requested application actions, not proof that deletion, opening or network retry has completed. They cannot veto an already observed action, consume it retroactively, or become CHANGE/COMMIT/SUBMIT/lifecycle events. Availability remains the existing planner's decision. OPEN needs an identified card and matching handler. REMOVE also needs touch/hover and tracked card bounds. RETRY needs identified FAILED status and matching handler. Media retry requires media/tracked bounds; description retry is the first eligible non-title/non-custom child. A description's individual status override does not independently gate the retry link. Loading does **not** globally disable OPEN or REMOVE. Custom child buttons and custom action clusters do not become these attachment actions. ACTIVATE metadata targets the compound attachment. Genuine unique accepted activation snapshots are copied at the actual root/button/link interaction seam, before later custom rendering or old action callbacks can change live evidence. `activation.target` retains the actual control ID: card, remove, media retry, or its distinct description retry link. Multiple accepted activations/control origins coalescing into a category produce proven-frame UNKNOWN source with no index or activation; unavailable evidence uses the same conservative fallback. No arbitrary first/last input is chosen. Flags establish which evidence exists. Current Core supports LINK accessibility ACTIVATE and pointer-activatable GROUP ACTIVATE, including the clickable card, once previous semantics register the control. Admission before first registration fails with INVALID_ACTION. This facade does not change routing, focus, supported actions or keyboard behavior. Actual passive/layout-only/inert calls do not notify, while preserving legacy work. Invalid options/pointers retain old validation behavior. No hidden heap allocation, retained registration or input replay is added. Payload is pointer-free and may be copied by value beyond the callback/frame. Handler/user/payload pointer are borrowed synchronously. Legacy callbacks retain all original side effects and must keep resources required by the remaining operation and observers live. Typed observers must not mutate/free/rebind active state/options/children/input/context, recursively submit UI or destroy the context. Unrelated application flags and payload copying are allowed. Defer removal and teardown until outer return plus renderer consumption. Resource/render callbacks are not action observers and must retain their existing contracts. `tests/unit/test_attachment_events.c` checks legacy/facade equivalence, availability, userdata/order, real pointer/key/accessibility evidence, description/media retry, ambiguity, late callback changes, custom child isolation, passive/inert scopes and copied payload/deferred omission. The existing `media` suite covers image, Attachment and AttachmentGroup regressions. Run native tests only through `scripts/test_local.py`; browser/binding/full family parity is not implied. Foreign languages retain their existing queued generic notifications; this direct C facade does not add typed callback wrappers to them. --- ## Avatar activation observation Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/AVATAR_EVENTS.md # Avatar activation observation `cui_avatar_events.h` adds an opt-in direct C observer to `cui_avatar_ex` behavior. It does not change legacy Avatar options/layouts or the aggregate bool API. `interactive` still enables BUTTON semantics and routing: supplying a handler to a passive IMAGE does not turn it into a button. ```c static void open_profile(void *user, const cui_component_event_metadata *event) { /* Copy *event if needed. Update application state; defer active teardown. */ profile_owner *owner = user; owner->last_activation = *event; owner->open_requested = true; } /* owner remains alive through this call and the frame's render boundary. */ cui_component_action_result result = cui_avatar_events( ui, id, &theme, cui_string("Taylor Reed"), (cui_avatar_options){.interactive = true, .design_size = CUI_DESIGN_MD, .identity_colors = true}, (cui_component_activation_handler){open_profile, owner}); /* Inspect counts for diagnostics; do not open the profile again from result. */ ``` The complete [portable owner example](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/avatar_events/README.md) contains a real owner definition and runnable model. It demonstrates a copied payload and next-submission omission. Its synthetic accessibility input is not native assistive-technology evidence. The facade runs one original Avatar submission. It observes each matching event at the existing explicit event loop after photo/icon/initial paint submission and semantic/focus/cursor updates. Evidence is copied immediately before original consumption; callback runs after consumption, then the loop checks the next event live. Multiple inputs produce multiple notifications in event-index order, including when the legacy bool would only report true once. Consuming later input in a callback can suppress later callbacks; events are never prequeued. `valid` reports argument preflight, not successful rendering. `submitted` reports ordinary active paint-enabled, non-inert submission, including disabled and passive avatars. `activation_count` counts observed legacy activation-loop matches when submitted; a missing handler still counts and consumes as before. `request_count` is always zero. Counts saturate at `SIZE_MAX`, setting `count_overflow`; callback delivery continues. Copying/reading results does not redispatch. Omission, disabled/passive/inert/layout-only work does not invent a notification. The legacy API's own return/consume behavior remains unchanged. Metadata kind is ACTIVATE and target is the Avatar ID. Genuine accepted snapshots preserve frame, event index, input source and contact/key evidence. When the old activation gate matches but Core cannot establish accepted evidence, notification has proven frame only with UNKNOWN source and no index/activation flags. A regression reproduces this honestly using a genuine pointer event plus a sticky duplicate-semantic Core error. It does not fabricate a snapshot or claim that preflight validity clears a Core error. Avatar preserves default Core keyboard behavior: Enter nonrepeat key-down and Space release after capture. It does not adopt source Button's different release policy. Accessibility ACTIVATE needs prior supported semantics; failed admission before registration is not an activation. Core evidence is separate from tested native screen-reader integration. Handler/user/payload pointers are borrowed synchronously; metadata is pointer-free and copyable beyond frame/context lifetime. Existing pixels, caches, labels, icons and users retain their rendering lifetimes. Updating unrelated application flags and consuming later input are supported. Do not rebind/free active resources, recursively submit the same component/frame or destroy context in a callback. Request omission/teardown in application state, then apply it after outer return and renderer consumption. No runtime destruction guard, owner veto, CHANGE/COMMIT/SUBMIT, image loading lifecycle or foreign-language callback facade is introduced. ## Stack activations `cui_avatar_stack_events` adds the separately reviewed stack observer while `cui_avatar_stack` retains its old aggregate index API: ```c static void choose_person(void *user, const cui_avatar_stack_activation *event) { team_owner *owner = user; owner->chosen_index = event->index; owner->chosen_key = event->key; owner->last_activation = event->event; } cui_avatar_stack_event_result result = cui_avatar_stack_events( ui, id, &theme, people, people_count, (cui_avatar_stack_options){.size = 48, .interactive = true}, (cui_avatar_stack_handler){choose_person, owner}); ``` Callbacks follow visible child submission order, then that child's event-index order. They are not sorted across the compound by input chronology. For events on children 2, 0 and 1 in that time order, callbacks report children 0, 1 and 2; `result.control` is 2, preserving the highest activated visible index returned by the old API. Several events on one child generate several callbacks. `result.action` uses the same validity/submission/count/overflow fields as the single Avatar; request_count stays zero. A missing handler still counts and preserves the legacy aggregate index and consumption. The payload's metadata target is the stack ID, while genuine activation evidence retains its child target. Index and application key are copied from the actual visible iteration, including an original zero key. Nonzero keys retain stable child identity across reorder; zero retains the existing index-based identity rule. The payload does not replace zero with a generated key. A frame-only fallback has no claimed child activation snapshot; index/key still identify the actual legacy iteration. The regression exercises this with real routed input and a duplicate-semantic Core error. Width-limited hidden items and passive overflow never notify. Existing overlap hit order, default visible count, images, semantics and appearance remain unchanged. Active item arrays are borrowed and must not be mutated/rebound/freed inside callbacks. Consuming later input can suppress later events/children; no queue or replay is introduced. Resource lifetimes and deferred teardown rules are identical to the single-Avatar observer. The [checkpoint](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/AVATAR_EVENTS_SLICE.md) remains the reviewed design history. Complete Avatar parity is not claimed. Integrator work includes test/ module registration, generated SDK/API/skill exports and honest binding availability; a C declaration copied into an SDK does not expose a working foreign callback facade. --- ## Profile images and compact conversations Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/AVATAR_MESSAGE_EXAMPLES.md # Profile images and compact conversations Avatar now accepts a borrowed RGBA bitmap through `cui_avatar_ex`. The legacy `cui_avatar` initials API is unchanged. The gallery uses three original fictional portraits, processed by the pinned `scripts/generate_avatar_assets.py` script. The same masked pixels enter the native and WASM draw lists; no DOM image is used. Initialize a caller-owned cache once, outside the frame loop. Retain the source pixels, cache object and destination storage until rendering has completed. Changing the source pointer, dimensions, stride or revision rebuilds the cache. Increment the source revision when its pixels change. There is no per-frame heap allocation and no cleanup function: the application owns all storage. A diameter of 1–512 is supported; storage requires diameter × diameter × 4 bytes. Source and cache storage must not overlap. Missing or invalid images fall back to initials. A failed preparation leaves the last successful cache intact, but `cui_avatar_ex` uses the current preparation result and never displays that stale photo for an invalid source. To represent acquisition/decode failure or a pending download, pass a zero bitmap; retry with valid borrowed RGBA pixels when available. Recovery can reuse the same cache. Acquisition, decoding and retry policy belong to the host; there is no network or asynchronous source-status API. The supplied full name labels both photo and initials frames; it is not shortened for assistive technology. An empty name becomes “Anonymous” in `cui_avatar_ex`. Passive avatars expose image semantics and interactive avatars expose button semantics. Read semantic records within the current frame lifetime; copy names before retaining them across frames. These names are a CUI accessibility policy: the frozen upstream Avatar does not define an equivalent automatic name policy. See `docs/AVATAR_FAILURE_AUDIT.md` for the precise frozen upstream distinction. ```c #include static unsigned char circle_pixels[96 * 96 * 4]; static cui_avatar_image circle; bool profile_init(void) { return cui_avatar_image_init(&circle, circle_pixels, sizeof circle_pixels, 96); } bool profile_draw(cui_context *ui, const cui_theme *theme, cui_bitmap borrowed) { return cui_avatar_ex(ui, cui_id_from(ui, "profile"), theme, cui_string("Alex Morgan"), (cui_avatar_options){.size = 48, .ring_width = 2, .image = borrowed, .image_state = &circle, .interactive = true}); } ``` Opt into named initials colors with `.identity_colors = true`. The palette uses `theme.dark` and the frozen twelve 30-degree OkLCH hues. The default assignment hashes the UTF-8 bytes of CUI's initials using 32-bit FNV-1a; this is stable within CUI but differs from upstream's private hash and initials rules. Set `.custom_identity_hue = true, .identity_hue = 0` to choose a hue index in 0–11. Invalid overrides retain legacy colors. Explicit `custom_background` and `custom_foreground` override the palette; initials keep the identity outline. Photos and anonymous placeholders keep neutral outlines. `cui_avatar_identity` exposes the same palette for application composition and leaves output untouched on invalid arguments. `.anonymous_icon = true` replaces the empty-name question mark with the default User SVG. `.placeholder_name = cui_string("building-2")` selects a named icon; a borrowed `.placeholder` points to an existing `cui_icon_state` for custom SVG. The typed state wins over a name. A supplied name still selects initials, and a valid photo still wins over both. All icons remain decorative within the existing Avatar image/button semantic record; the anonymous accessible name stays “Anonymous”. SVG loading errors follow the existing Icon contract and do not silently substitute a different glyph. Keep borrowed icon state and mask versions alive until rendering finishes; collect or destroy only afterward. Named icons use the bounded context cache, whose draw borrows expire at the next frame. `.design_size` opts into the shared `CUI_DESIGN_XS` through `CUI_DESIGN_9XL` scale. An explicit variant wins over `.size`; `INHERIT` keeps the existing custom diameter and .38 text ratio. `.rem_size = 0` uses 16 logical pixels per rem; positive values up to 512 scale variant geometry and typography. No fonts are loaded implicitly. Use `cui_avatar_measure` to inspect the resulting diameter, text size and weight. | Variant | Diameter at rem=16 | Initials text | Weight | | --- | ---: | ---: | --- | | XS | 16 | 10.4 | normal | | SM | 24 | 12 | normal | | BASE / MD | 48 | 14 | normal | | LG | 80 | 30 | semibold | | XL through 9XL | 2 × shared control height, capped at 512 | shared font size × 30/18 | semibold | The first four sizes reproduce frozen Avatar preset geometry and text sizes. BASE aliases MD. XL through 9XL extend CUI's shared design scale; they are not upstream presets. Their diameters are 96, 112, 128, 160, 208, 256, 304, 400 and 512 at rem=16. The overall scale is capped when the raw diameter would exceed 512, reducing both diameter and font size together to preserve their ratio. This also applies to 9XL at rem=16, whose raw diameter is 528. Custom upstream `Size` sets initials-child dimensions; CUI does not claim identical custom text layout. Invalid variants or rem values fall back to legacy metrics. These opt-ins do not change `cui_avatar` or `cui_avatar_stack` defaults. `cui_avatar_stack` takes up to 64 items with stable application keys. Its default shows three portraits and a passive overflow count. Later portraits paint and receive pointer hits above earlier portraits. Positive `width` reduces the number shown to fit; zero uses the intrinsic width. Interactive stacks return the selected item index, or `SIZE_MAX`. Disabled items retain their semantics and reject activation. Cursor and interaction state use the shared Core hooks. The image name is its accessible name; interactive portraits use button semantics. Message separates avatar, header, body and footer callbacks. Put sender and time in the header, one message in the body, and delivery/reaction controls in the footer. The gallery demonstrates incoming and outgoing rows, portrait callbacks, controlled acknowledgement and an actual reaction callback. `max_bubble_width` caps the content column while preserving the available row width and START/END alignment. Zero preserves the existing layout. The footer inset uses the actual avatar width and row gap. MessageScroller uses the same row composition with stable IDs and a virtualized conversation model. Slots are inferred present from `present`, nonempty text or a render callback; omit a slot by clearing all three. Scroll deltas that change MessageScroller position are consumed, allowing an ongoing touch pan to remain internal; refused boundary deltas can reach the host. ```c #include void conversation_row(cui_context *ui, cui_id id, const cui_theme *theme, cui_message_options slots) { cui_message_body body = { .slot = {.text = cui_string("Can you review the release notes?")}, .typed_bubble = true, .bubble = CUI_BUBBLE_SECONDARY}; slots.header.text = cui_string("Alex Morgan · 09:30"); slots.body = &body; slots.body_count = 1; slots.footer.text = cui_string("Delivered · 09:30"); slots.width = 600; slots.max_bubble_width = 280; slots.alignment = CUI_MESSAGE_START; slots.name = cui_string("Message from Alex"); cui_message(ui, id, theme, slots); } ``` The reusable API accepts pixels supplied by the application; it does not decode PNG files or manage image downloads. Applications own conversation/session state and callback lifetimes. These examples do not implement a network messaging service, attachments or a complete messaging accessibility model. Validation includes headless cover-crop/alpha/cache/revision checks, native software rendering, overlap hit order, keyboard activation, disabled and cancelled touch activation, and actual compact message bounds in both alignments. The Chromium suite uses CDP touch contacts for profile selection, reactions and virtual scrolling, checks actual WASM portrait pixels and circular alpha, all seven bubble variants and 390px layouts. This is Chromium evidence, not physical iOS/Android or full platform parity. --- ## Portable backgrounds and bitmap effects Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BACKGROUNDS.md # Portable backgrounds and bitmap effects `cui_effects.h` generates reusable RGBA8 pixels in caller-owned storage. It uses only core CUI types and portable C11, with no allocation or platform dependency. All functions return false for invalid input before writing output. Row padding is preserved. The caller must provide actual storage matching the declared sizes; source `cui_bitmap` follows the core borrowed-storage contract. `cui_effect_linear_gradient` accepts ordered color stops and a finite angle in degrees. Zero runs left to right, 90 top to bottom, 180 right to left. Angles span the projected pixel-center bounds, so the first and last projected corners sample 0 and 1 exactly. One-pixel images sample 0. Stops must increase strictly within [0,1]; colors outside the stop interval extend to the edges. Interpolation uses premultiplied sRGB values, then writes straight-alpha RGBA8. This avoids hidden transparent colors leaking into visible gradient pixels; it is not linear-light or Oklab interpolation. `cui_effect_opacity` scales alpha without scaling RGB, which is correct for the straight-alpha pixels required by `cui_bitmap`. Use `cui_bitmap_paint.opacity` for draw-time fading when regenerated pixels are unnecessary. Existing `cui_box` opacity also applies to descendants. Color fills use `cui_box.background`. `cui_effect_blur` is a separable box blur with replicated edge samples. Its radius is a pixel radius, not a CSS Gaussian blur length. It processes premultiplied RGBA in caller-owned float scratch, then returns straight-alpha pixels; fully transparent results have RGB zero. Query scratch with `cui_effect_blur_scratch_floats`, allocate that many floats once, and reuse them. Zero from this query indicates invalid dimensions or size overflow. Scratch must be float-aligned, large enough, and disjoint from both images. Source/destination may use identical pointers and strides, or disjoint storage; partial overlap is rejected. Radius zero copies the original bytes, including transparent RGB. The sliding-window implementation runs in O(width * height), including for very large radii. This is a single box pass, not a Gaussian approximation. Paint generated pixels through `cui_paint_bitmap` with an explicit opacity of 1 and a box radius for rounded corners. Alternatively use the existing bitmap underlay API to place them behind content. Keep the pixels alive through renderer completion; increment bitmap revision whenever pixels change so adapters can refresh cached uploads. Reuse generated backgrounds instead of recalculating unchanged gradients or blurs every frame. A backdrop blur requires the host to capture the pixels behind the element and supply that bitmap to `cui_effect_blur`. These primitives do not capture a native window, sample earlier draw commands, or provide automatic CSS backdrop-filter behavior. They can blur an image, a generated background, or a host-supplied capture. Host capture coordinates, timing, and upload remain host responsibilities. `examples/effects/background.c` provides a reusable slate-to-teal gradient tile and a rounded painting helper. Initialize its caller-owned state once, then paint it inside a CUI frame. This example has no host or renderer dependency. --- ## Bidirectional text analysis Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BIDI.md # Bidirectional text analysis `cui_bidi_resolve` resolves one UTF-8 paragraph as one unwrapped line using vendored SheenBidi 3.0.0, commit `cfe430e7375a7845b679adae9d51dac6deaa8858` (Apache-2.0). The upstream [release](https://github.com/Tehreer/SheenBidi/releases/tag/v3.0.0) updates its property tables to Unicode 17.0.0. Vendored files are unmodified; `third_party/sheenbidi/manifest.json` records their SHA-256 checksums. The engine applies paragraph detection/base levels, explicit embeddings and isolates, weak types including numbers, paired brackets, neutrals, implicit levels, line resets, and visual run ordering. The wrapper returns logical scalar levels after L1, visual runs, a visual-to-logical scalar permutation, and mirrored code points where odd-level characters have a Unicode mirror mapping. It follows [Unicode 17 UAX #9 revision 51](https://www.unicode.org/reports/tr9/tr9-51.html). Explicit direction overrides P2/P3; auto modes choose the requested fallback when no outside-isolate strong character determines paragraph direction. All offsets are Unicode scalar indices, not UTF-8 byte positions. Strict UTF-8 validation rejects overlong, truncated, surrogate, and out-of-range encodings. Input containing more than one paragraph is rejected atomically. Empty input succeeds. A final paragraph separator is accepted. Control characters, including X9-removed characters, remain in the output permutation; consumers must suppress formatting controls when painting. Odd-level runs are read from their logical end toward their start. Mirrored output is analysis data; choosing the corresponding mirrored glyph still belongs to the shaping engine. Callers provide disjoint output buffers and a scalar decoding workspace. Each capacity must be at least the UTF-8 byte length, a conservative bound sufficient for every scalar/run. A capacity error, invalid input, or backend allocation failure leaves all outputs and the result unchanged; workspace is scratch and may change. Input and arrays must be valid for their declared sizes. The backend uses transient heap objects, so the workspace contract does not promise an allocation-free algorithm. The wrapper never changes SheenBidi's global allocator. Do not change that global allocator concurrently with processing. Upstream reference counts and scratch allocation are thread-safe by default; scratch buffers may be retained in the backend's global pool after a call. The headless test accepts paths to the pinned Unicode `BidiCharacterTest.txt` and `BidiTest.txt`. It checks every expected level and visual position after filtering X9-removed characters. The full suites pass 91,707 character cases and 770,241 property/direction cases. Property tests use one representative Unicode scalar per bidi class as permitted by the Unicode test instructions. They cover isolates, embeddings, numbers, neutral/bracket resolution and deep nesting. Additional checks cover malformed UTF-8, conservative capacities, atomic failure, paragraph rejection, empty input and mirroring. This API does not yet connect to rendering, font fallback, shaping, grapheme cluster ordering (L3), wrap-position selection, caret navigation, hit testing, or selection. In particular, reversing scalar indices in a run is not sufficient to render a cluster correctly: shaping and cluster handling must follow. No claim of complete international-text rendering parity is made. CMake builds this as the optional `cui_bidi` static library by default. Disable it with `-DCUI_BUILD_BIDI=OFF`; Core does not link it implicitly. Installed consumers can use `pkg-config --cflags --libs cui-bidi`. Its archive contains the private backend objects, so consumers do not need a separate SheenBidi library. For manual integration compile `Source/SheenBidi.c` with `SB_CONFIG_UNITY` and private include paths `third_party/sheenbidi/Headers` and `third_party/sheenbidi/Source`. Only the CUI header is public. Preserve upstream notices and LICENSE in bundles. ## Reusable paragraph and wrapped-line analysis `cui_bidi_paragraph_create` analyzes the complete paragraph through I2 once, copying decoded scalars into an owned immutable object. The caller can reuse both input and decoding workspace immediately. `cui_bidi_paragraph_destroy` releases the object and backend references; NULL destruction is accepted. No vendor type appears in the CUI public API. Creation leaves the output pointer unchanged on invalid UTF-8, insufficient workspace, multiple paragraphs, or allocation failure. `cui_bidi_paragraph_levels` returns the paragraph levels before L1, scalar count, and paragraph base. `cui_bidi_paragraph_line` takes a nonempty scalar range inside that paragraph and applies L1/L2 to that line using the original paragraph analysis. The caller chooses ranges after determining wrap positions. A Latin continuation of a Hebrew paragraph consequently retains the Hebrew base; resolving the continuation alone with auto direction would change that base. Explicit embeddings and isolates crossing a wrap retain their paragraph context. Line-local trailing whitespace resets to the paragraph base under L1. Line output levels use indices relative to the requested range. Mapping entries and run logical starts remain absolute paragraph scalar indices. Result scalar count is the requested line length. Output capacity needs only that scalar length, and every output and result remains unchanged on any failure. Paragraph level output capacity needs the paragraph scalar count. Empty paragraphs are valid objects but have no nonempty line range. Neither function mutates the paragraph, so independent output buffers can be used concurrently, provided no thread destroys the object or changes the backend global allocator. Tests compare paragraph levels and every wrapped-line run, level, mirror and visual scalar position with the pinned upstream paragraph/line API, across Hebrew, Arabic, numbers, paired brackets, an isolate spanning wraps and explicit embeddings. They also verify the L1 trailing-space reset, retained RTL base, caller-buffer independence, bounds including SIZE_MAX, insufficient capacities, empty objects and atomic preservation of every output buffer. This adds wrapped-line bidi analysis, not a complete wrapping or shaping system. Offsets are scalars, and callers must choose boundaries between whole grapheme and shaping clusters. The API does not enforce those boundaries or apply L3. Shaping, font fallback, painting, caret/selection and hit testing remain separate integration work; no rendering parity is claimed. --- ## Optional bidirectional glyph layout Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BIDI_SHAPING.md # Optional bidirectional glyph layout `cui_font_layout_line` adds an explicit bidirectional shaping path alongside the existing `cui_font_measure*` and `cui_font_draw*` functions. When enabled, those ordinary calls also use this shaping path with automatic paragraph direction. The explicit line API returns an owned `cui_text_layout`, a borrowed view of visual glyphs and runs, and `cui_text_layout_draw` to rasterize that positioned layout. Public types contain only portable CUI and C types. The full UTF-8 paragraph is analyzed by the pinned Unicode 17 bidi module. The caller then selects a scalar line range (SIZE_MAX length means through the end). L1/L2 use the full paragraph context, including embeddings and isolates crossing wraps. Visual directional runs are split into logical script subruns. Script properties come from the linked HarfBuzz Unicode functions. Common/Inherited/ Unknown characters adopt a preceding strong script in the directional run, or the next strong script when none precedes them; a wholly weak run remains Common. This is basic script itemization, not full UAX #24 Script_Extensions resolution. RTL script subruns are placed in reverse subrun order. Each logical UTF-8 subrun is shaped with an explicit HarfBuzz direction, script, language (BCP47 or default `und`) and `MONOTONE_GRAPHEMES` cluster level. HarfBuzz's output glyph order is preserved, including ligatures and combining glyphs sharing one cluster. There is no scalar-level reversal of shaped glyphs. The shaping input uses the selected line as pre/post context; BOT/EOT flags mark the line's actual boundaries. Bidi paragraph context is retained, but Arabic joining does not cross a line boundary. Default ignorables, including bidi formatting controls, affect shaping but are removed from the final glyph stream. HarfBuzz handles direction-dependent glyph mirroring; the scalar mirror output from the bidi analyzer is not reshaped. Glyph `cluster_byte` values are absolute byte offsets into the original UTF-8 paragraph, including for a wrapped line starting after byte zero. They may repeat or skip source bytes; they are not scalar indices or one-to-one caret positions. Run byte ranges use the same source coordinates. Glyph `x/y` are final origins relative to the line baseline, with y increasing downward; advances use that same coordinate convention. Width is the sum of absolute horizontal subrun advances, not an ink bounding box. Height/ascent come from the primary and used fallback face metrics. View arrays remain valid until layout destruction. Creation owns all glyph/run storage and releases transient paragraph/shaper buffers before return. Input text may be reused immediately. Allocation and validation failures preserve the caller's layout output pointer. The layout retains its selected and fallback faces independently of caller references: closing fonts or replacing registrations does not invalidate it. Borrowed fallback/style registrations still require their source handles to stay alive for future layout creation until the registration is cleared. Fonts are UI-thread confined, as in the existing text adapter. Draw coordinates refer to the line top-left; partial raster failure can already have emitted glyph callbacks. The renderer can instead consume the portable glyph view. Drawing another glyph size between layout creation and drawing is safe: the saved layout size is reapplied to the face. ## Integration When both optional native text and bidi targets exist, define `CUI_TEXT_BIDI` for `cui_text` and link it privately to `cui_bidi`. Without that definition, the new creation function returns `CUI_TEXT_LAYOUT_UNAVAILABLE` without modifying its output; plain text needs no bidi link. No public compile definition is necessary. The normal native text adapter still requires FreeType and HarfBuzz. Register `tests/unit/test_text.c` as a new test linked to `cui_text`, `cui_bidi` and the existing FreeType/HarfBuzz package target, with a private include path `third_party/sheenbidi/Headers`. Define `CUI_TEXT_BIDI` for the test target when enabled, and keep assertions active. Without that definition, the same test checks the atomic UNAVAILABLE contract and needs no bidi/HarfBuzz reference include or link. The test uses `CUI_TEST_FONT` or a portable Noto/DejaVu/Liberation font search, and `CUI_TEST_ARABIC_FONT` or Noto Sans Arabic/DejaVu Sans. The Arabic case checks character coverage and explicitly logs any untested joining/mark raster case. It compares visual directional coverage/levels directly to pinned SheenBidi, then glyph IDs, source clusters, offsets and advances directly to HarfBuzz. It checks mixed Latin/Hebrew/Arabic/numbers/brackets, isolates, nonzero wrapped-line source offsets, RTL script-subrun ordering, actual Arabic mark clusters and joining with a supporting face, style face selection, invalid UTF-8 and atomic failure. Existing ASCII metrics and raster checksums match the plain interface. Both enabled and disabled builds compile with strict warnings; enabled tests pass with address and undefined-behavior sanitizers. The linked HarfBuzz and selected font determine shaping/version coverage. These headless comparisons demonstrate the tested shaping and bidi behavior, not complete international-text rendering parity. No system font installation is performed. ## Limits The caller chooses line breaks at complete grapheme/shaping-cluster boundaries; this API accepts scalar ranges and does not enforce cluster-safe boundaries, compute wrapping widths, or expose unsafe-to-break glyph flags. Script/directional itemization is basic and is not a full cluster-aware script resolver. Existing style registration selects the primary face; an explicit caller chain can supply complete script/directional subruns. There is no OS font discovery or per-grapheme mixed-face fallback inside a subrun. There is no language detection, vertical layout, justification, caret mapping, selection or hit testing. Core, widgets and backend commands using the native text adapter benefit from the enabled ordinary-call routing. No other Core/widget behavior is changed. The shaping contracts follow the primary [HarfBuzz buffer documentation](https://harfbuzz.github.io/harfbuzz-hb-buffer.html) and [cluster documentation](https://harfbuzz.github.io/working-with-harfbuzz-clusters.html); paragraph/run rules follow [Unicode 17 UAX #9](https://www.unicode.org/reports/tr9/tr9-51.html). ## Ordinary text and hard lines With `CUI_TEXT_BIDI` enabled, ordinary styled/unstyled measure and draw calls analyze each P1 paragraph with auto-LTR fallback, use script/direction shaping, and paint its visual glyph stream. These calls support every Unicode B paragraph separator (LF, CR, U+001C/U+001D/U+001E, NEL and U+2029). CRLF is one break. U+2028 creates a hard line inside the same paragraph, preserving the complete paragraph direction/isolate/embedding context across that break. Separators produce no glyphs. Empty and trailing lines still occupy one face line height. Measurement returns maximum line advance width and the sum of line heights. Drawing resets horizontal origin to the caller's x for each line and advances the top/baseline by that face's line height. Empty text occupies one empty line, as in the existing measurement interface. Every line is fully laid out before any raster callback: malformed UTF-8 or allocation failure emits nothing and returns false; measurement returns {0,0}. Raster failures can still be partial. The explicit glyph-layout API permits an empty scalar range and retains that paragraph's base and metrics, allowing empty U+2028 continuation lines. Tests independently reproduce the original FreeType/HarfBuzz ASCII shaping and raster loop to compare legacy single-line glyph pixels, metrics and baselines, including ligatures/kerning. Ordinary mixed RTL/multiline rendering is compared against explicitly selected paragraph-line layouts, whose run/glyph data is checked against the upstream references. Tests cover all B separators, CRLF, U+2028 context, empty/trailing lines, baseline progression and invalid input following a valid line. Real Arabic joining/mark raster checks also call the ordinary adapter APIs. Disabled builds retain the original adapter path. This is hard-line processing, not automatic word wrapping or a caret system. The simple script itemization/fallback limitations above still apply. Each explicit U+2028 line currently reanalyzes its paragraph; large numbers of such lines may warrant caching reusable analysis in a future text-layout object. ## Explicit caller-registered font fallback `cui_font_set_fallbacks` installs an ordered borrowed chain of actual CUI font handles; `cui_font_register_fallbacks` opens and owns an ordered list of file paths. Both replace the complete chain transactionally, accept zero entries to clear, and reject counts above `CUI_FONT_FALLBACK_MAX` (32), NULL entries, duplicates/self handles for the borrowed setter, and failing paths. A failed call leaves the old chain working and releases partially opened owned faces. Current owned entries cannot be reborrowed into the replacing chain. The chain belongs to the root handle passed to layout/measurement/drawing, not to a style variant. Existing style-selection rules are applied to the primary and each direct fallback entry. Chains are not recursively traversed. Borrowed fallback and style handles must remain alive while registered for future calls. Owned entries are released on replacement/owner close. Font close releases a reference, and layouts retain each actual candidate face independently: a layout can still be painted after chain/style replacement or caller font close. Its view exposes borrowed retained CUI handles in `faces`; never close those view handles. `run.face_index` identifies the face whose glyph IDs the run contains. All font/registration operations remain confined to the UI thread. Coverage is chosen for each entire script/directional subrun. The first face that shapes the complete subrun without glyph zero is selected. This keeps joining Arabic letters and their marks together and never switches faces inside a HarfBuzz output cluster. HarfBuzz's REMOVE_DEFAULT_IGNORABLES flag lets joining controls, CGJ, variation selectors and tags affect shaping without requiring standalone cmap entries. Coverage uses actual shaped output, not nominal cmap checks: valid normalization/composition can cover combining sequences even when a standalone mark has no cmap entry. Every visible shaped glyph must be nonzero. No complete covering face, or any shaped glyph zero, yields explicit `CUI_TEXT_LAYOUT_MISSING_GLYPH` and preserves the output pointer. Ordinary draw returns false with no callbacks if layout/coverage fails; ordinary measure returns {0,0}. Missing-glyph tofu is not reported as a successful fallback layout. Runs use their selected faces for both HarfBuzz shaping and FreeType rasterization. All glyph origins share one baseline. If fallback is actually used, ascent and descent are maxima across the primary and used faces, and line height is the maximum of all used native line heights and combined ascent/descent. No-fallback lines preserve the existing primary face height exactly, including rounded metric conventions. Unused registered fallback faces do not enlarge the line. Hard-line baseline progression uses each computed line height. `cui_font_get_metrics` remains the selected primary face's generic metrics, since it has no text argument; text-specific fallback extents are available from layout/measurement. Tests verify a Noto Latin primary actually lacks Arabic/Hebrew, then compare successful fallback glyph IDs, marks, advances and pixels with direct HarfBuzz/ FreeType shaping on the registered script faces. They verify original source clusters, script run order, mixed baseline maxima, Arabic joiners/marks/VS/CGJ, missing coverage failures, first-fit selection, invalid/capacity registration, partial owned-open cleanup, style-face selection, and retained raster stability after owned/borrowed chain replacement and root/variant font close. ASCII metrics and raster regressions remain unchanged. Font lookup also accepts portable DejaVu faces and explicit `CUI_TEST_FONT`, `CUI_TEST_ARABIC_FONT` and `CUI_TEST_HEBREW_FONT`; cases already covered by the primary are explicitly logged as untested missing-primary cases rather than inventing missing-glyph evidence. Without bidi enabled, chain registration/lifetime APIs still work and are tested, but the existing legacy ordinary shaping path does not consult the chain; explicit layout creation remains UNAVAILABLE. There is no automatic system font discovery, color-emoji rendering, per-grapheme mixed-face segmentation, automatic word wrapping, or caret/selection/hit-test implementation. Whole-run coverage may fail when separate fonts collectively cover a run but no one font covers it completely. ## Renderer fixture validation The native software renderer test no longer treats nonempty `.notdef` pixels as multilingual evidence. Its Arabic and Hebrew samples first create layouts on explicit optional fixture faces and assert every source glyph ID is nonzero. Those validated faces are registered in the primary font's fallback chain, and ordinary drawing is checked against the explicit layout's raster checksum, coverage and measurement. Existing ASCII/ligature and renderer geometry checks remain independent. Tests search known portable Noto/DejaVu/Liberation fixture paths, or honor `CUI_TEST_ARABIC_FONT` and `CUI_TEST_HEBREW_FONT`; missing or unsupported fixtures explicitly report the script case skipped. With bidi OFF, the test reports source-glyph proof unavailable and keeps its ordinary ASCII regressions. Legacy nonempty tofu pixels are never labeled successful RTL proof. This fixture search is test setup, not production OS font discovery. The native line layout also exposes a cluster-boundary geometry foundation. `view.clusters` partitions each shaped directional/script subrun into complete HarfBuzz monotone grapheme clusters, sorted by visual advance position. Byte ranges remain offsets into the original paragraph, including caller-selected wrapped lines. Geometry uses glyph advance pens, not ink extents or glyph offsets; selection rectangles use the layout's common baseline line height across actual fallback faces. Layout ownership retains both these arrays and their faces. `cui_text_layout_carets` reports the preceding logical cluster's end (upstream) and following logical cluster's start (downstream). At directional transitions these affinities can have distinct visual positions. Results sort by x, then upstream before downstream. Empty lines provide both affinities at x=0 and the original line offset. `cui_text_layout_hit_test` projects finite coordinates onto this single line and chooses the nearest cluster edge; equal distances prefer the requested affinity, then the first cluster in visual order. The y coordinate is validated but does not choose another line. Default-ignorable bytes omitted by shaping attach to the adjacent logical cluster; a wholly omitted subrun has one zero-width cluster. Zero-width edges follow the same deterministic tie rule. `cui_text_layout_selection` normalizes reversed logical endpoints and emits one rectangle per complete selected cluster, in visual order, including zero-width rectangles. Callers can merge adjacent rectangles for painting. Caret and selection endpoints inside a cluster (including interior ligature or combining mark offsets) are rejected. NULL output with zero capacity queries the count; INVALID and CAPACITY leave both output and count unchanged. Hit-test invalid inputs also preserve output. All three APIs return UNAVAILABLE without changing outputs in BIDI-off builds. This is not full editing caret parity: there are no GDEF ligature interior carets, independent stops inside omitted controls, cross-run grapheme analysis, visual keyboard navigation, multi-line hit-testing, or Core/Edit/Textarea wiring. Fonts can shape several characters into one cluster, so a valid UTF-8 character boundary need not be an accepted geometry boundary. Actual automatic word wrapping and editor selection/caret policies remain caller responsibilities. The cluster grouping follows [HarfBuzz's cluster model](https://harfbuzz.github.io/working-with-harfbuzz-clusters.html); interior ligature carets would additionally require the optional [OpenType GDEF ligature caret list](https://learn.microsoft.com/en-us/typography/opentype/spec/gdef#ligature-caret-list-table). --- ## Build a native UI in Python, JavaScript or TypeScript Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BINDING_BUILDERS.md # Build a native UI in Python, JavaScript or TypeScript For installable local wheel, npm, Go module and Rust crate artifacts, see the [packaging guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PACKAGING.md). Linux alpha packages are tested outside the checkout; registry publication and other platform packages remain pending. The component builders let you author a UI tree in your language. CUI performs layout and input handling in C; the optional SDL adapter draws a native window. Native builder windows default to visible creation. Python `initially_hidden=True` and JavaScript/TypeScript `initiallyHidden: true` request hidden creation directly in SDL's constructor, before the first frame. See [native visibility](#native-window-visibility). The bridge exposes tested API subsets for all 78 catalog families through native CUI renderers and app services, plus rows, columns, radio groups and composite items. Python, JavaScript, TypeScript, [Go](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/GO_BUILDERS.md) and [Rust](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/RUST_BUILDERS.md) construct these components in their own language and receive copied events after C frames. This is a tested API subset for each family. The [component coverage and limitations](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_COMPONENTS.md) identify unsupported options; the [machine-readable coverage](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/binding-coverage.json) keeps all 78 entries. Clipboard and Theme are app services; the other families have component builders. This is language authoring coverage, not complete option or feature parity. ## Dependencies and compiler Build from the repository root with CMake 3.20+, Ninja, a C11 compiler and Python 3.10+. GCC and Clang work on Linux. Python uses standard-library `ctypes`, without pip dependencies. Node additionally needs Node 18+ and its development headers (`node_api.h`); no npm packages or node-gyp are required. The TypeScript example uses Node's built-in type stripping, tested here with Node 25. Native windows additionally require installed SDL3 3.2+, FreeType, HarfBuzz, pkg-config and an existing TrueType/OpenType font. CMake discovers and links these libraries. Set the font path explicitly. A missing native adapter reports an error when you request SDL; it does not silently select headless mode. The portable C bridge and Python have Linux, macOS and Windows CI evidence for the previously published control subset. Node, Go and Rust runtime validation uses Linux. The expanded model tests run headlessly on Linux; native Windows and macOS binding applications have not been validated. Windows DLL exports, Node import library discovery and macOS Node linker settings are provided. See the [platform matrix](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PLATFORM_MATRIX.md). ## Python: build and launch ```sh cmake -S bindings/bridge -B build-bridge -G Ninja cmake --build build-bridge --target cui_bridge test_bridge_core test_bridge_components ctest --test-dir build-bridge -R '^bridge_' --output-on-failure export CUI_BRIDGE_LIBRARY="$PWD/build-bridge/libcui_bridge.so" export PYTHONPATH="$PWD/bindings/python" export CUI_TEST_FONT=/path/to/your/font.ttf python bindings/bridge/examples/save_changes.py ``` The example opens a native window with a Save button and a status label. Clicking Save updates the label. Its UI is defined in Python: ```python import os from cui_bridge import App, button, label, row status = label("Ready", key="status") save = (button("save").primary().rounded_md().size("base") .label("Save changes").on_click(lambda event: status.label("Saved"))) with App(backend="sdl", title="My CUI app", width=480, height=240, font_path=os.environ["CUI_TEST_FONT"]) as app: app.mount(row().gap_units(2).children(save, status)) app.run() ``` For a window-free check, use `App()` without SDL. After mounting, call `app.step()`, obtain `(x, y, w, h) = app.bounds(save)`, queue pointer down/up inside that rectangle, call `app.step()` and then `app.dispatch()`. The checked-in [Python tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/python/test_bridge.py) demonstrate this using actual CUI hit testing. Headless mode computes layout and draw commands; it does not paint a window or provide native font metrics. ## JavaScript and TypeScript: build and launch ```sh cmake -S bindings/node -B build-node -G Ninja cmake --build build-node --target cui_node_bindings test_bridge_core test_bridge_components ctest --test-dir build-node -R '^(bridge_|node_)' --output-on-failure node bindings/node/examples/save.cjs --headless export CUI_FONT_PATH=/path/to/your/font.ttf node bindings/node/examples/save.cjs node bindings/typescript/examples/save.ts ``` The shared bridge and Node addon are built together. CMake supplies include paths and linker flags; the addon remains in the build directory. If you choose another directory, set `CUI_NODE_ADDON` to its absolute `cui.node` path. On Windows the Node project also requires `node.lib` and reports an actionable configure error if it is unavailable. Maintainers can repeat the Linux native checks without desktop windows by configuring the Node build with `-DCUI_BRIDGE_NATIVE_TESTS=ON` and `-DCUI_TEST_FONT=/path/to/font.ttf`, then running `python scripts/test_local.py --build-dir build-node -- -R '^(bridge_|node_)'`. These opt-in checks need Xvfb, xwininfo, xwd, xdotool and ImageMagick's convert. The runner clears inherited desktop sockets and launches a disposable display; native probes refuse to run without that isolation marker. ```js const {App, row, label, button} = require('./bindings/node'); const status = label('Ready'); const save = button('save').primary().rounded_md().base() .label('Save changes').on_click(() => status.label('Saved')); const app = new App({backend: 'sdl', width: 480, height: 240, title: 'My CUI app', fontPath: process.env.CUI_FONT_PATH}); app.mount(row().gap_units(2).children(save, status)); app.start(); ``` `start()` schedules frames with Node timers so other timers and I/O can run. Closing the native window disposes the app. Use `stop()` to stop scheduling, `close()` to request closure, and `dispose()` to release resources explicitly. The [TypeScript example](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/typescript/examples/save.ts) uses the same builders and [type declarations](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/typescript/index.d.ts). Node type stripping executes the example; it does not perform static type checking. ## Styling, state and callbacks Buttons support primary, secondary, outline and ghost variants, disabled state, theme rounding or an explicit radius, and custom hover colors for primary, secondary and outline variants. Sizes cover `xs`, `sm`, `base`, `md`, `lg`, `xl`, `2xl` through `9xl`; `base` is the default. Python uses `.size("sm")`; JS/TS also offer `.sm()`, `.md()` and `.lg()`. `rounded_md()` maps to the existing larger rounding preset. Arbitrary CSS properties and per-button padding overrides are not exposed yet. `gap_px(8)` means eight logical pixels. `gap_units(2)` also means eight logical pixels, using four pixels per unit. `gap(8)` retains the explicit-pixel meaning. Python's `step()` and `dispatch()` are separate; JS `step()` performs both. Callbacks execute after the C frame has finished, so exceptions remain in your language. A callback can update labels, disable a button or close the app. The language layer retains its tree; the bridge owns copied strings, stable IDs and button state and composes immediate CUI frames. Nodes belong to one app. Disposed or stale handles are rejected. Keep each app on one thread and serialize **all calls across all apps**: the core uses a process-global Clay context. Explicitly release each app, and drain its bounded event queue. Most strings must be valid UTF-8 without embedded NUL, at most 4096 bytes. Clipboard accepts 64 KiB; Settings search accepts 256 bytes; chart labels and table cells accept 128 bytes. Trees support up to 128 levels including their root; deeper construction is rejected before frame submission. See the [C ABI guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/bridge/docs/README.md) and [public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_bridge.h) for capacities and status codes. [Go builders](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/GO_BUILDERS.md) and [Rust builders](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/RUST_BUILDERS.md) now construct real component trees in their own language and dispatch copied native events. The older [C-host examples](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/LANGUAGE_BINDINGS.md) remain useful for embedding an existing C-authored application. ## Form controls and copied change events `on_change` receives a snapshot captured when the C component changed. Read `event.checked`, `event.value`, or `event.text`; these remain accurate even when multiple frames are queued before Python dispatch. JavaScript dispatches after each `step()`. Programmatic setters update the model without emitting user events. `radio` is standalone; use `radio_group` with `item` children for exclusive choice. ```python from cui_bridge import App, column, checkbox, input, label, slider status = label("Ready") notifications = checkbox("notifications", "Enable notifications").checked() name = input("name", "Alex").on_change(lambda event: status.label(event.text)) volume = slider("volume").range(0, 100, 1).value(50) with App() as app: app.mount(column().gap_units(2).children(name, notifications, volume, status)) app.step() # Headless layout; choose backend="sdl" and font_path for a native window. ``` ```javascript const cui = require('./bindings/node/index.cjs'); const status = cui.label('Ready'); const name = cui.input('name', 'Alex').on_change(event => status.label(event.text)); const app = new cui.App(); app.mount(cui.column().gap_units(2).children( name, cui.checkbox('notifications', 'Enable notifications').checked(), cui.slider('volume').range(0, 100, 1).value(50), status )).step(); app.dispose(); ``` The Python and Node `test_components` fixtures exercise real pointer hit testing, disabled behavior, numeric ranges, UTF-8 edits, grouped selection and panel visibility. Design sizes, rounding, and custom hover styling currently apply to Button; other component styling APIs are a separate unfinished bridge capability. ## Dialogs, trees, images and date entry Surface builders use `open()` and `on_close()`; popovers and hover surfaces require a live `anchor(node)`. Dialog, Sheet and Popover accept child components. AlertDialog uses its native confirmation actions. A Tree uses up to 64 flat Item children in preorder; Item `step_status(depth)` sets depth and `checked(True)` starts a branch expanded. In JavaScript use `checked(true)`. `image_rgba(pixels, width, height, stride)` accepts decoded RGBA8 bytes. Both the builder and C bridge own copies. Dimensions are 1–2048, stride is at least `width * 4`, and byte count must equal `stride * height`, at most 16 MiB. Decode PNG/JPEG files in your application. Attachment currently exposes metadata and progress; its bridge has no file transfer, remove or retry actions. Calendar and DatePicker accept `date_value(year, month, day)`, including old dates, and expose `current_date()`. The current bridge uses English single-date mode. TimeField uses `time_value(hour, minute, second)` and `current_time()`. ColorPicker uses packed `0xRRGGBBAA` with `color_rgba()` and `current_color()`; its event copies both the packed number and `#RRGGBBAA` text. OTPInput uses `total(cells)` and `current_text()`; send one cell per queued text-input event. The runnable workspace examples compose navigation tabs, account fields, notification preferences, date entry and a confirmation dialog. They create actual component trees. Use `--headless` for their deterministic interaction checks or omit it for a native window: ```sh export PYTHONPATH="$PWD/bindings/python" export CUI_BRIDGE_LIBRARY="$PWD/build-bridge/libcui_bridge.so" python bindings/bridge/examples/workspace.py --headless # Native: set CUI_TEST_FONT to an existing font first. python bindings/bridge/examples/workspace.py node bindings/node/examples/workspace.cjs --headless # Native: set CUI_FONT_PATH to an existing font first. node bindings/node/examples/workspace.cjs ``` Only Button exposes the bridge's design sizes, rounding and hover-color styling at this stage. Other families use native defaults and the specific options listed in the coverage guide; a constructor does not imply all native options are mapped. Headless tests cover events and lifetime; they do not prove native pixel rendering on every operating system. Form accepts Item fields whose children are real controls; Item label/detail supply field metadata. Disabling Form or a field suppresses its child controls. InputGroup uses editable text and Item button addons; Item `step_status(0..3)` chooses the addon alignment and `on_click` receives addon presses. Notification is an in-app card. It uses title/detail, `open`, `is_open`, click and close callbacks. Cards share one stack; there is no OS notification delivery, autohide or action-button API in this bridge subset. The close callback arrives after the close animation completes; `is_open()` becomes false when dismissal starts. Set the title/detail before opening. FocusTrap accepts children and `open()`/`is_open()`. Its open modal focus scope blocks pointer actions outside the subtree; closing restores outside interaction. ## Native fonts and fallback faces Pass an existing font file that covers your text. Missing glyphs cause a render error. Python and JavaScript/TypeScript let you replace the SDL font's ordered, owned fallback chain with `app.font_fallbacks(["/absolute/path/symbols.ttf"])`. The chain accepts at most 32 paths; `[]` clears it. Configure it before frames. Go provides `Options.FontFallbacks` and `SetFontFallbacks`; Rust provides `app.font_fallbacks(&["/absolute/path/symbols.ttf"])`. The bridge opens and owns the fallback faces and rejects an invalid replacement without discarding the previous chain. Fallback registration requires SDL; headless mode reports that the backend is unavailable. It does not scan your machine for fonts. ## Sidebar navigation with editable pages These examples define their layout and controls in Python or JavaScript. The Sidebar selects Account or Preferences; Tabs provides the page content. Account contains a native Input and a Save callback that reads its current text. No C-authored application is launched behind the language API. ```sh # Use the bridge and addon builds from the earlier sections. python bindings/bridge/examples/sidebar_workspace.py --headless node bindings/node/examples/sidebar-workspace.cjs --headless # Open native windows when you want to interact with the example. CUI_TEST_FONT=/absolute/path/font.ttf python bindings/bridge/examples/sidebar_workspace.py CUI_FONT_PATH=/absolute/path/font.ttf node bindings/node/examples/sidebar-workspace.cjs ``` ```python from cui_bridge import (button, checkbox, column, input, item, label, root_view, row, sidebar, tabs) status = label('Ready', key='status') name = input('name', 'Alex Morgan') email = checkbox('email', 'Email notifications').checked() save = button('save').label('Save changes').primary().rounded_md().on_click( lambda event: status.label('Saved account: ' + name.current_text())) account = item('account-page', 'Account').children( column().gap_units(3).children(label('Account details'), name, save, status)) preferences = item('preferences-page', 'Preferences').children( column().gap_units(3).children(label('Notifications'), email)) pages = tabs('pages').children(account, preferences).select(account) account_action = item('account-action', 'Account').on_click(lambda event: pages.select(account)) preferences_action = item('preferences-action', 'Preferences').on_click(lambda event: pages.select(preferences)) navigation = sidebar('navigation').visual_size(180, 280).children(account_action, preferences_action) root = root_view().padding(24).children(column().gap_units(4).children( label('CUI workspace'), row().gap_units(6).children(navigation, pages))) ``` Mount `root` on the SDL `App` described above and run its event loop. The checked-in [Python example](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/bridge/examples/sidebar_workspace.py) includes both the window loop and a deterministic headless interaction check. The [JavaScript example](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/node/examples/sidebar-workspace.cjs) builds the same UI; [Go](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/GO_BUILDERS.md) and [Rust](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/RUST_BUILDERS.md) each include a composed workspace with navigation, editing, callbacks and a confirmation dialog. ## Retained models and native interaction The language builders retain a tree and owned data. CUI renders immediate frames from that tree and manages native state for editors, scrolling, selection, dock layouts, questionnaires and Settings. Event callbacks run after each C frame, using copied snapshots rather than live pointers. With Python, dispatch events explicitly after stepping; Node dispatches as part of `step()`. MessageScroller contains Item messages; `detail` is the sender and `step_status(0/1)` selects incoming/outgoing. It follows the newest message on its initial frame. Carousel contains Item slides and provides `select` and `selected`. Resizable contains Item panels with `panel_size(100..4096)` widths; real divider dragging updates the panel and emits its numeric change event. VirtualList contains up to 64 keyed Item rows in a fixed-height vertical viewport. `scroll_to` and `scroll_offset` work on MessageScroller and VirtualList. Editor owns multiline text and exposes `current_text` and copied change events. TextView supports `text_format("markdown"|"html"|"plain")`, rendered UTF-8 byte selection with `select_text`, and copied `selection_text`. Neither currently exposes completion providers or clipboard shortcuts through the bridge. Chart copies `chart_data([["Label", value], ...])` and accepts `chart_kind("line"|"area"|"bar"|"pie")`. Table contains Item rows with Item text cells; the first row is the header. DataTable copies `table_data(headers, rows)` and supports `selection_mode("row"|"column"|"cell")`. Its change event text is JSON containing `reason`, `row`, `column`, `sortColumn` and `sortDirection`. Indices are one-based, with zero meaning none. Sort events request an order; replace the matrix yourself to apply it. Plot copies `plot_points([[x,y], ...])`; its bridge subset draws dots and does not yet expose axes, pan/zoom or hit tests. Command contains Item actions. `label` changes the native filter query; `current_text` and `selected` read it back. An Item's `detail` adds a filter keyword, and its click callback receives native confirmation. Sidebar contains Item navigation actions and supports `open`, `select`, `selected` and copied navigation events. RootView can be the sole root and adds `padding(0..256)`. Questionnaire contains Item questions with Item choices. Before mounting, use `question(required=True, multiple=False)` in Python or `question(true, false)` in JavaScript. The first frame freezes the schema. `questionnaire_next`, `questionnaire_previous`, `questionnaire_submit`, `questionnaire_state` and `choice_selected` expose progress. Submission enforces native answer rules; change events contain copied JSON snapshots of answers and navigation. Dock contains Item panels with child controls. After its first frame, `dock_activate`, `dock_move_split`, `dock_active` and `dock_panel_bounds` expose its retained layout. `dock_serialize` returns copied opaque `CUIDOCK 1` text, not JSON. Panel metadata freezes on the first frame; restoring serialized layouts and floating OS windows are not exposed yet. ## Settings pages and reset defaults Settings uses Item pages, nested Item groups, then Switch, Checkbox, Input or NumberInput fields. Input/NumberInput `detail` supplies the field title; Input `label` supplies editable text and NumberInput `value` supplies its number. The first successful frame captures reset values and freezes titles and topology. Only fields support disabled state. ```python from cui_bridge import App, column, input, item, settings, switch updates = switch("updates", "Automatic updates").checked() name = input("name", "Alex").detail("Display name") general = item("general", "General").children( item("account", "Account").children(updates, name)) preferences = settings("preferences").visual_size(760, 400).children(general) with App(width=900, height=600) as app: app.mount(column().children(preferences)) app.step() # First frame captures defaults. name.label("Changed") preferences.settings_reset(general) app.dispatch() # Reset delivers copied field change events. assert name.current_text() == "Alex" ``` `settings_query(text)` copies a search string of at most 256 UTF-8 bytes. `settings_page()` reads the selected Item; `settings_select(page)` navigates and emits a copied page event. `settings_field_bounds(field)` locates a visible control for host input. `settings_reset(page)` restores all fields in that page, including programmatic edits. The same method names work in JavaScript/TypeScript. Limits are eight pages, 32 total groups and 128 total fields. Persist preferences in your application; custom setting fields and dropdowns are not mapped yet. ## Theme, clipboard and speech services `app.theme_presets()` returns native preset names. `app.theme_preset(index)` changes one app's theme; `app.current_theme_preset()` is empty until an explicit choice. The bridge does not automatically watch the host's appearance preference. SDL apps support `clipboard_set(text)` and copied `clipboard_get()` on the owner thread, outside a frame. Headless mode reports backend unavailable. Clipboard text is valid UTF-8 without NUL, up to 64 KiB. Speech exposes `speech_start`, `speech_report(text, final)`, `speech_finish`, `speech_transcript` and `speech_active`. The host supplies recognition results; this component does not capture audio or include a speech recognition provider. Copied lifecycle events distinguish start, transcript and finish. The [coverage guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_COMPONENTS.md) documents capacities and unsupported features for every family. [Validation receipts](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/validation/component-builders-expanded-78.txt) record the combined checks and their platform limits. For native callback loops, live resizing, callback failure containment and the manual-loop compatibility contract, see [binding native runners](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BINDING_NATIVE_RUN.md). The optional `cui_date_time_picker.h` single civil date/time API is C-only in this revision. Generated source SDKs carry its header/implementation, but Python/JavaScript/TypeScript/Go/Rust builders and bridge records do not expose its typed value/state, assignment, options, helpers or result. Do not pass legacy date-only builder storage to it. See `docs/DATE_TIME_PICKER.md`. Stepper builders opt into non-centered connectors and per-Item RGBA icons with `stepper_visual(true, false, "md")` (Python uses `True`/`False`; Go uses `StepperVisual(true, false, cui.StepperMD)`; Rust uses `stepper_visual(node, true, false, StepperDensity::Md)`). The default remains legacy rendering. Density is `md/xs/sm/lg`; shared `design_size` also accepts Stepper. Connectors have no independent toggle in the current C visual API. Use the existing Item `image_rgba` method (Go `RGBA`, Rust `image_rgba`) to supply straight-alpha RGBA icons. Builders and bridge copy bytes; use white RGB for monochrome foreground tint. Only Item children of Stepper accept this image storage; other Item parents reject it at mount/update. Replacement validates and allocates before releasing the previous copy; removing the Item releases it. Missing icons use ordinals, while XS hides icons and ordinals. Existing image limits remain 2048 per dimension and 16 MiB including stride padding. The bridge keeps its 64-Item limit, selected Item and aggregate CHANGE phase. Visual paint uses a selection snapshot; accepted selection appears on the next submission. Selecting the already selected Item emits no CHANGE; accepted changed selection queues one existing aggregate CHANGE after rendering. This is not the C controlled REQUEST callback surface. Legacy mode preserves its prior behavior. Use matching bridge/addon/SDK revisions for the additive methods. See [Stepper navigation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/STEPPER_NAVIGATION.md) and the [binding design contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/STEPPER_BINDING_VISUAL_DESIGN.md). The C-only `cui_stepper_presentation.h` facade adds non-centered fill, indicator interaction and a typed custom palette. Its layout/palette/options types and `cui_stepper_present` entry are omitted from every language builder/bridge; source SDK inclusion does not imply authoring support. ## Native window visibility ```python with App(backend="sdl", font_path=font, initially_hidden=True) as app: app.mount(row()) app.step() # stays hidden app.set_window_visible(True) assert app.window_visible() ``` ```javascript const app = new App({backend:'sdl', fontPath:font, initiallyHidden:true}); app.mount(row()); app.step(); // stays hidden app.set_window_visible(true); console.assert(app.window_visible()); ``` The same JavaScript methods are declared for TypeScript. Defaults remain visible; there is no show-then-hide fallback. The bridge uses independent version-1 `cui_bridge_window_options` through `cui_bridge_create_with_window_options`; `cui_bridge_options`, its exact-size check, ABI version and old constructor stay unchanged. Query returns SDL's hidden flag, not occlusion/minimization. OS mapping may be asynchronous. Headless hidden requests and visibility operations return backend unavailable; default headless creation is unchanged. Calls belong on the native window's owning UI thread, outside an active Core frame. Application event handlers dispatched after a completed frame by the native callback loop may show/hide/query; `step` and `run` themselves never show the window. Closed apps reject visibility operations. Python resolves the new window symbols optionally; default apps do not require these exports. Hidden creation/control fails explicitly if they are absent. Missing-export fixtures verify this feature boundary, not compatibility with every historical ABI1 build. Node addon and native library must match. Focused Linux private-Xvfb tests cover C, Python, JavaScript, compiled/executed TypeScript, Go and Rust, including the actual SDL constructor flag and first presentation flag, explicit show/hide, default visible creation and after-frame callbacks. This is not Wayland/Windows/macOS or physical GPU validation. Run with an existing native bridge build, installed tooling and an explicit font: ```sh python scripts/test_window_visibility_bindings.py --build-dir build --font /absolute/font.ttf # --tsc /existing/typescript/lib/tsc.js accepts an already installed compiler. ``` The helper downloads nothing, builds only focused dynamic tests/addon and a Linux test-only SDL interposer, then uses `scripts/test_local.py` for private Xvfb. Sokol and SDL_GPU renderer-only hosts retain ownership of their own windows. The dedicated native-binding workflow also runs this focused visibility helper against its existing bridge build, with pinned TypeScript5.8.3 and Rust1.85.1. Hosted CI results remain separate from the local private-Xvfb evidence above. ## Bounded typed root shadows See [typed root shadow authoring](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_SHADOWS.md) for the six-kind implementation, owned values, canonical CSS/preset factories and explicit clear/reset behavior. Focused portable runtime tests cover this subset; integration remains pending. This does not expose compound parts or portals. For bounded semantic ROOT/MAIN/indicator/track/thumb authoring, read [typed part shadows](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_PART_SHADOWS.md). Slider has no thumb; owner topology, whole-group naming and separate reset are explicit parts of that contract. ## Python controlled Single/Range Slider The unreleased additive `slider_model(key, config, confirmed)` builder owns frozen double Single/Range request records and uses explicit receipt acceptance after step. Read [the exact Python contract and complete authored UI](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PYTHON_SLIDER_MODEL.md). The old `slider()` examples above preserve scalar float/autocommit CHANGE behavior. Rust controlled builders remain pending. The matching [Node/TypeScript controlled subset](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NODE_SLIDER_MODEL.md) adds owned frozen records, exact BigInt identities and explicit receipt acceptance. Its JS and compiled TS examples author actual nested control UIs; close requests shutdown while dispose destroys the App. Direct C custom Styled state remains unbound. Rust controlled builders remain pending. The [Go controlled subset](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/GO_SLIDER_MODEL.md) adds owned double value copies, uint64 identities and private receipt authority. Its complete authored UI accepts or rejects whole pairs after Dispatch; existing Step/Close/RequestClose OS-thread semantics remain. Rust controlled authoring remains pending. --- ## Native callback runners in language bindings Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BINDING_NATIVE_RUN.md # Native callback runners in language bindings Python `App.run()`, Go `App.Run(dt)`, Rust `App::run()` / `run_with(...)` and Node/TypeScript `App.run()` delegate to `cui_bridge_run`. The SDL callback loop owns event pumping and frame scheduling so native modal resizing can continue layout and paint. Call from the app's creating UI thread. Mount a tree first. Python/Go retain and validate the legacy positive finite `dt` argument for source compatibility; the native host supplies actual frame timing. Application handlers execute after a completed native frame. They may update nodes or request close. Nested run and step calls are rejected. Python and Node retain the original exception, Go recovers a panic, and Rust uses `catch_unwind`; all stop the C runner before rethrowing/resuming in the language caller. Rust builds using `panic=abort` retain the toolchain's abort behavior. No language may unwind through a C callback. A normal window close returns normally. After the runner exits, its native host is released and the app is terminal: release the app owner as usual. Python `close()`, Node `dispose()` and Go `Close()` may also destroy the owner inside a handler; the bridge defers actual destruction until the runner exits. These wrappers invalidate their handles immediately and avoid using them afterward. Rust ownership prevents dropping a mutably borrowed app while `run` is active; use `run_with(|app| app.close())` for a safe close request/update hook. Manual APIs remain: Python `step`/`dispatch`, Go `Step`/`Dispatch`, Rust `step`/`dispatch`/`frame`, and Node `step`. Node `start`/`stop` still use timers and keep the JavaScript event loop responsive. The synchronous native `run()` blocks Node timers/I/O until closure; choose it when native modal-resize behavior is needed. It cannot be combined with `start()` on the same app. Dynamic wrappers resolve the new optional runner lazily. Older bridges can still use manual APIs; runner use fails clearly when unavailable. Portable/headless backends do not support the native runner. Rust's existing dynamic packaging support is Linux; static Go/Rust builds require refreshed canonical SDK sources containing the runner. No generated SDK snapshot is changed by this wrapper patch. Validation lives in Python `test_run_native_virtual.py`, Node `test/run-native.test.cjs`, Go `TestNativeRunLifecycle`, and Rust `tests/run_native.rs`. Native tests require the isolated-display marker and font path and must be launched through `scripts/test_local.py`; never point them at the desktop display. They cover callback delivery, normal close, foreign failure containment, terminal lifecycle and reentrancy; Python additionally exercises a real X11 resize through the native runner. Underlying SDL live-resize behavior and C deferred destruction are separately covered by native bridge/runner tests. --- ## Controlled boolean Base requests Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BOOLEAN_EVENTS.md # Controlled boolean Base requests `cui_boolean_events.h` adds `cui_base_switch_events` and `cui_base_toggle_events`. These portable C11 Base reducers draw nothing; submit one inside its same-ID layout box. Switch retains `CUI_ROLE_SWITCH`; Toggle retains `CUI_ROLE_BUTTON`. Neither is implemented by remapping Check semantics. The separate shared `cui_control_events.h` provides the result and metadata types. `cui_components.h` adds Styled `cui_switch_events` and `cui_toggle_events`. Language bindings and generated build/export registration remain separate work. ```c #include typedef struct { bool enabled, allow_change; } model; static void requested(void *user, const cui_component_boolean_request *request) { model *state = user; if (state->allow_change) state->enabled = request->requested; /* Otherwise reject by leaving it alone. */ } /* Caller submits the same-ID box during an ordinary frame. */ cui_component_action_result submit_flag(cui_context *ui, cui_id enabled_id, model *state) { return cui_base_switch_events(ui, enabled_id, cui_string("Enabled"), state->enabled, (cui_boolean_event_options){0}, (cui_component_boolean_handler){requested, state}); } ``` The bool argument is an immutable entry snapshot. Each supported accepted event invokes the optional callback synchronously with typed `current` and `requested` values: `current` is the entry bool and `requested` its inverse. Two accepted activations produce two identical value proposals, even when the owner accepts the first. Semantics retain the entry snapshot during that submission; the next submission observes owner assignments. There is no hidden write, getter, retained value, acceptance return flag, or synthesized CHANGE notification. Missing callback means read-only. `activation_count` still reports accepted attempts; `request_count` counts callbacks actually delivered. Rejecting a request does not undo Core input consumption or reroute it to the parent. Counts are per invocation, saturate at `SIZE_MAX`, and set `count_overflow` if an increment would overflow. Saturation does not stop dispatch. Reading or copying the result has no event effects. `valid` reports argument preflight: nonnull context, nonzero ID and readable-name descriptor (nonempty names require nonnull data). It does not establish that the frame will finish without layout/capacity/duplicate-ID errors. `submitted` means ordinary active submission was reached, including disabled controls; it is false outside an active frame, under inert/layout-only ancestry, and in protected measurement/prepaint phases. Disabled/inert/omitted submissions dispatch nothing. No loading state is added. Options preserve role-default keyboard and pointer focus unless explicitly modified. `no_pointer_focus` retains pointer activation and explicit/keyboard focus; `skip_tab` and `tab_index` configure tab navigation. Base disabled Switch and Toggle preserve their existing parent routing; they do not add Check's required/focusable/disabled-hit-barrier policy. Existing mutable Base entry points remain aggregate: several accepted events still produce one legacy bool flip. Existing Styled aggregate callbacks are unchanged by this slice. Request metadata comes from genuine accepted activation snapshots in event-index order, frozen before the callback. It includes pointer/touch contact/device identity, keyboard evidence or accessibility origin as present; never fabricate pointer evidence for keyboard/accessibility. Request and metadata structs are pointer-free and can be copied beyond callback/frame/context lifetime. The callback pointer, user storage and name bytes remain borrowed for their existing synchronous submission/frame boundaries. The loop checks eligibility immediately before each delivery; it does not queue all future callbacks. A callback consuming a later accessibility event can prevent its later delivery. Core may already have accepted events during `cui_interact`: `cui_cancel_event_activation` then returns false rather than undoing acceptance. Cancellation before reducer submission remains effective. This API does not alter Core's event-specific consumption rules. Callbacks may update owner/unrelated state, omit later siblings through ordinary caller control flow, or mark close/removal pending. **Destroying the active context, recursively submitting the same component/frame, or freeing active storage during a callback is unsupported.** Defer teardown until submission/frame completion. No destruction guard, asynchronous callback registration, global routing, or bridge-runner destruction guarantee is introduced. The unit fixture exercises mouse/touch, Enter/Space/repeat filtering, accessibility multiplicity and later-event consumption, both initial bool values, owner acceptance/rejection, no-handler read-only behavior, invalid arguments, protected phases, inert/layout-only/omitted/disabled submissions, exact role/focus policy, disabled-parent routing, and legacy aggregate compatibility. Build registration and generated SDK resources must be integrated by the module owner; this guide does not claim those snapshots already contain the new API. ## Styled Switch and Toggle The additive Styled facades accept the same bool snapshot and typed handler as Base, plus existing appearance options and optional presentation state: ```c /* During an ordinary frame, inside the application's parent layout box: */ cui_component_action_result submit_styled_flag(cui_context *ui, cui_id id, const cui_theme *theme, model *state, cui_switch_state *motion) { return cui_switch_events(ui, id, theme, cui_string("Enabled"), state->enabled, motion, (cui_switch_options){.size = CUI_CONTROL_SMALL}, (cui_component_boolean_handler){requested, state}); } ``` Switch owns its root, track, thumb and label/content layout. Optional `cui_switch_state` retains spring and tooltip presentation; it never owns the boolean model. Toggle uses existing `cui_toggle_paint` and optional `cui_hover_state` for its tooltip. Accessibility names, size/design metrics, custom content, focus styling, disabled appearance and tooltip options retain their existing roles. Do not wrap these Styled calls in another same-ID box; that same-ID box requirement applies to the headless Base entry points. Both legacy `on_change` **and** `change_user` option fields must be NULL, even when the new handler is absent. Any conflict fails preflight with `valid=false` before semantic submission, content callbacks, spring/tooltip mutation or paint. Missing new handler remains read-only, rather than selecting legacy mutation. A handler assignment changes application state immediately, while all requests, semantics and paint in this invocation keep the original bool. The next submission reflects the assignment. Passive inert/layout-only composition can still measure/paint content, but emits no requests and does not mutate caller spring or tooltip storage. Outside submission/protected phases the new facades return without invoking content or touching presentation state. Legacy `cui_switch_ex` and `cui_toggle_ex` remain aggregate. Their callbacks still run before reading the external bool for semantic/paint updates. Switch's private paint extraction retains its old dereference sequence: label-left content may change the external value after spring-target calculation and before track-color selection. The new facade deliberately supplies a local entry snapshot to that same paint path; it does not retime legacy behavior. `test_boolean_styled_events.c` checks controlled accept/reject painting and semantics, pointer/key/accessibility multiplicity, read-only and disabled behavior, all frozen size metrics and an explicit design size, custom content geometry, all callback/user conflict combinations, passive storage preservation, and legacy callback/content mutation timing. Existing Button/Check and Base boolean fixtures remain independent regression coverage. Active-context destruction and recursive submission remain unsupported as documented above; no cross-language event coverage is implied. --- ## C bridge component coverage Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_COMPONENTS.md # C bridge component coverage The bridge ABI remains version 1. Existing numeric enum values, option layout, event layout, and functions are unchanged. New kinds are appended. | Kind | Native CUI renderer | State and events | Current limit | | --- | --- | --- | --- | | Row, Column | `cui_begin_box` | gap | One root; depth 128 | | Label | `cui_text` | copied UTF-8 text | Text only | | Button | `cui_button_ex` | copied text, click | Existing options | | Checkbox | `cui_checkbox` | checked, change, disabled | Boolean only | | Radio | `cui_radio` | checked, change, disabled | Standalone radio; no group exclusivity | | Switch | `cui_switch_ex` | checked, change, disabled | Boolean only | | Toggle | `cui_toggle` | checked, change, disabled | Boolean only | | Slider | `cui_slider` | value, range, step, change, disabled | Float native precision | | SliderModel (kind81, C/Python/Node/TypeScript/Go) | `cui_styled_slider_model_events_v1` | owned double Single/Range, separate copied request FIFO, explicit receipt acceptance | [Exact contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_SLIDER_MODEL.md); [Python builder](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PYTHON_SLIDER_MODEL.md); [Node/TypeScript builders](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NODE_SLIDER_MODEL.md); [Go builder](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/GO_SLIDER_MODEL.md); Rust typed builders, native numeric AT, V2 adapter and typed shadows pending | | Progress | `cui_progress` | value in [0,1] | Width fixed at 160 | | Badge | `cui_badge` | copied UTF-8 text | Legacy text badge | | Input | `cui_input_ex` | per-node edit model, text, change, disabled | 4096 UTF-8 bytes | | Textarea | `cui_textarea` | per-node multiline edit model, text, change, disabled | 4096 UTF-8 bytes, 512 layout lines | | NumberInput | `cui_number_input` | per-node numeric editor, value, range, step, change, disabled | Finite values; 127-byte draft | | Collapsible | `cui_collapsible` | open state, change, disabled | Child subtree is panel | | Alert | `cui_alert` | copied title/message | Static informational alert | | RadioGroup | `cui_radio_group` | selected Item, change, disabled | Up to 64 Items | | Tabs | `cui_tabs` | selected Item, change, disabled | Up to 64 Items; Item subtree is panel | | Accordion | `cui_accordion` | per-Item open state, change, disabled | Up to 64 Items; multiple expansion | | Item | Composite descriptor | label, disabled, optional panel children | Must belong to group | | Select | `cui_select` | selected Item, change, disabled | Up to 64 Items; viewport is app surface | | ComboBox | `cui_combobox` | query edit model, selected Item, change, disabled | Up to 64 Items, 4096 UTF-8 query bytes | | DropdownButton | `cui_dropdown_button` | action click, selected menu Item, change, disabled | Up to 64 leaf menu actions | | Dialog | `cui_surface_begin` | open, close result, child body | Native modal surface | | AlertDialog | `cui_alert_dialog` | open, accept/cancel/close result | Native confirm/cancel content | | Sheet | `cui_surface_begin` | open, close result, child body | Default right edge | | Popover | `cui_surface_begin` | open, close result, anchor, child body | Anchor must be a live node | | Tooltip | `cui_tooltip` | native hover lifecycle, open/close change, disabled | Anchor must be a live node | | HoverCard | `cui_begin_hover_card` | native hover lifecycle, open/close change, disabled, child body | Anchor must be a live node | | Avatar | `cui_avatar` | copied name, size | Initials avatar | | Bubble | `cui_bubble` | copied message | Default variant | | Empty | `cui_empty` | copied title/description, width | Static state | | GroupBox | `cui_begin_group_box` | copied title, width, child tree | Native group container | | Kbd | `cui_kbd` | copied chord | Default platform-neutral text | | Skeleton | `cui_skeleton` | width/height, frame-time motion | Default style | | Spinner | `cui_spinner` | size, frame-time motion | Default style | | Tag | `cui_tag` | copied text | Default style | | Marker | `cui_marker` | copied text, retained state | Single text child | | Shimmer | `cui_shimmer_text` | copied text, retained state | Single line | | List | `cui_list` | selected Item, change, disabled | Up to 64 Items | | Menu | `cui_menu` | menu Item action, change, disabled | Up to 64 leaf actions | | Pagination | `cui_pagination` | current page, total, change, disabled | One-based page, total <= 1,000,000 | | Rating | `cui_rating` | value, maximum, change, disabled | Maximum <= 10 | | Stepper | `cui_stepper` / opt-in `cui_stepper_visual_navigation` | selected Item, status, aggregate change, disabled; opt-in density/orientation/shared size and copied RGBA Item icons | Up to 64 Items; visual selection paints on next submission; no foreign controlled REQUEST handlers | | DescriptionList | `cui_description_list` | Item label/value pairs | Up to 64 Items, default columns | | Scrollable | `cui_scrollable_begin/end_ex` | child tree, viewport/extents, wheel change | Vertical viewport | | StatusBar | `cui_status_bar` | Item labels in left/center/right regions | Set Item step status to 0/1/2 for region | | Toolbar | `cui_toolbar` | Item child controls, inherited disabled state | Up to 64 Items; child controls own actions | | TitleBar | `cui_title_bar` | Item text labels, retained title state | No native window host controls | | Icon | `cui_icon_named` | Copied catalog name, width/height | Embedded catalog assets; unknown name fails the frame | | Message | `cui_message` | Copied body/header, width | Incoming filled bubble, one body | | Attachment | `cui_attachment` | Copied title/description, status, progress, width | Metadata chip; no host file or remove/retry actions | | Image | `cui_image` | Owned RGBA8 pixels, revision, description, size | At most 16 MiB; no path, URI, animated loader | | Tree | `cui_tree` | 64 flat Item records with preorder depth, expansion and selected Item events | Item step status is depth 0..63; no custom row content | | TimeField | `cui_time_field` | HH:MM:SS state, keyboard change, copied event text, disabled | 24-hour fixed format | | ColorPicker | `cui_color_picker` | Packed RGBA, hue/plane/alpha input, copied hex event text, disabled | Default picker, no custom palette | | Calendar | `cui_calendar` | Single selected date, pointer/keyboard change, disabled | Default English labels, one month | | DatePicker | `cui_date_picker` | Retained popup, single selected date, open state and copied change text | Default English labels, no range mode | | OtpInput | `cui_otp` | Owned value buffer, target length, text input and copied change text, disabled | 1..256 cells, 4096 UTF-8 bytes; default six cells | | Form | `cui_form` | Item field labels/descriptions, child controls, inherited disabled state | Up to 64 fields; no built-in validation or nested Form | | Input Group | `cui_input_group` | Owned editor, Item button addons, alignment, copied text/change, disabled | Up to 64 addons; Item step status 0..3 selects position | | Notification | `cui_notifications` | Shared retained in-app stack, one card per node, copied title/message, open/dismiss, pointer click and close events | Up to 128 active cards; no OS delivery, action button, or auto-hide | | Focus Trap | `cui_begin_focus_scope` | Modal scope around child nodes, explicit open state, pointer/focus exclusion outside scope | Child content only; no backdrop or automatic close | | MessageScroller | `cui_message_scroller` and `cui_message` | Up to 64 Item message records, native virtualized viewport, retained scroll/follow, Item sender/body and direction, copied scroll CHANGE | Fixed default bubble style; no host message store or custom row callback | | Carousel | `cui_carousel` | Up to 64 Item slides, native horizontal wheel/drag/key navigation, retained selection, copied selected Item CHANGE, disabled | Fixed slide text/child content; no nested carousel, custom controls, or looping | | Resizable | `cui_resizable` | Up to 64 Item panels with native draggable handles, retained sizes, explicit panel size and copied resize CHANGE, disabled | Horizontal split, default min 100px; no hidden panels or custom handle appearance | | TextView | `cui_text_view` | Owned Markdown/HTML/plain document parser, native read-only selection, copied selection CHANGE, plain copy, disabled | Source up to 4096 bytes; bounded parser workspace, no image/URL callbacks or host clipboard | | Editor | `cui_editor` | Owned multiline UTF-8 model, native line-numbered editing, copied text CHANGE, language label and disabled state | 4096 UTF-8 bytes and 512 layout lines; no host syntax-highlighting, completion, search, or clipboard callbacks | | Chart | `cui_chart` | Copied up to 64 labeled numeric data points, native line/area/bar/pie raster and hover, data readback, disabled | Up to 512×512 pixels; one series, default native tooltip; no custom callbacks, candle, radar, or Sankey | | Table | `cui_table_begin_ex`, checked row/cell APIs | Item rows and nested Item cells with copied text, native table semantics and layout; first row is header | Up to 64 rows/64 cells per row; fixed equal column widths, text-only cells; no sort, selection, or virtualization | | DataTable | `cui_data_table` | Copied column headers and row-major cell matrix, native virtualized viewport, explicit row/column/cell selection mode, sortable header state, queried cell/state/bounds, copied CHANGE JSON snapshot | Up to 32 rows×16 columns, 128 UTF-8 bytes per cell; row selection by default; sort direction is a request, caller must supply reordered rows; no custom cell content | | Plot | `cui_plot_dots` | Copied up to 256 Cartesian (x,y) samples, native themed point rendering, point readback | Dot plot only; coordinates within ±16384, no path, axis, zoom, or point hit model | | Command | `cui_command` | Up to 64 Item actions, owned UTF-8 query editor, native keyword filtering, keyboard/pointer selection, copied query/selection CHANGE and Item confirm CLICK | Flat palette; Item detail is one keyword string, no grouped headings, custom row content, or host action callback | | VirtualList | `cui_virtual_list_draw` | Up to 64 keyed Item rows, native overscanned vertical viewport, wheel/keyboard scroll, copied offset CHANGE, visible Item bounds, disabled | Fixed 32px rows, vertical only; no intrinsic row sizing or host data provider | | Sidebar | `cui_sidebar`, `cui_sidebar_menu` | Up to 64 Item actions, native collapsible rail, pointer selection, copied selected CHANGE and Item CLICK, open state and disabled | One flat action menu with icon slots; no nested groups, custom callbacks, or persistence | | Theme | `cui_theme_preset_count`, `cui_theme_preset_name`, `cui_theme_preset_get` | Enumerate native palettes, copy preset names, select a palette per bridge app, and apply it to subsequent component frames | Preset selection only; no custom token import, host preference watcher, or theme-editor widget | | Root View | `cui_root_init`, `cui_root_render` | Root node owns full viewport background, renders bridge children, supports bounded padding and app theme changes | One app root with no host plugin factories, copy hook, or root-managed surface facilities; dialogs and notifications use their existing bridge paths | | Clipboard | `cui_sdl3_clipboard_interface` | Explicit UTF-8 OS clipboard write and copied read through the SDL app, with capability failure and output preservation | SDL owner thread only, outside a bridge frame; 64 KiB text limit; headless apps report BACKEND_UNAVAILABLE, no implicit widget copy/paste action | | Speech | `cui_speech_state`, `cui_speech_button` | Native retained speech lifecycle and button, externally supplied UTF-8 hypothesis/phrase/finish reports, copied transcript and CHANGE event snapshots | Bridge has no microphone or recognizer provider; host supplies reports outside a frame, 4096-byte transcript and bounded queue; no audio waveform input | | Questionnaire | `cui_questionnaire_state`, composable styled controls | Questionnaire->Item questions->Item choices, native required/single/multiple answers, current/selected queries, next/previous navigation, copied JSON event snapshots | Up to 16 questions×16 choices and 256 choices total; choice-only schema freezes after first render; no freeform input, custom validators, or host content callbacks | | Dock | `cui_dock`, `cui_dock_view` | Retained native tab and split tree over Item panels and their child content; activate, split, query bounds, serialize and copied selected Item CHANGE | Up to 64 panels; panel topology freezes after first render; center workspace only, no host panel factories or close persistence | | Settings | `cui_settings` | Settings->Item pages->Item groups->Switch/Checkbox/Input/NumberInput fields; retained native navigation, copied filter query, native field interaction, selected page and field CHANGE snapshots, reset to first-render values | Up to 8 pages, 32 groups, 128 fields; topology and titles freeze after first render; field-level disabled only; no dropdown/custom fields, host persistence, or custom search callbacks | `cui_bridge_poll_event_ex` copies queued CHANGE snapshots, including editable text. A capacity failure preserves the event for retry. The legacy event poll returns CLICK events and skips CHANGE events. The table covers all 78 manifest families plus four bridge-only structural kinds (Row, Column, RadioGroup, Item). Each row describes the supported subset; this does not imply full source component parity. Settings uses Item page and group nodes, with Switch, Checkbox, Input, or NumberInput leaves. Set page/group and boolean-field titles with `set_text`; set Input/NumberInput titles with `set_detail_text`. Set Input content with `set_text` and NumberInput values with `set_value`. The first successful frame captures reset defaults and freezes field topology and titles. `settings_set_query` copies up to 256 UTF-8 bytes; `settings_get_page` and `settings_field_bounds` require an initialized frame. Page selection CHANGE events copy the selected handle. Field CHANGE events copy the field's value or text; native reset emits one event for each field in the page, including fields already at their default. Programmatic input and number changes remain available after initialization, and reset restores the captured defaults. Only individual fields accept `set_disabled`. DataTable CHANGE events include copied JSON text with `reason` (`selection` or `sort`), `row`, `column`, `sortColumn`, and `sortDirection`. The numeric event value is the selected one-based row; use the JSON for exact column and sort snapshots when multiple changes are queued. A caller can replace the matrix after a step to implement the requested sort order. The visual families above expose their documented default variants. Avatar is an initials avatar with no image source. Marker is a single text child; Shimmer is a single line. The bridge has no arbitrary C content callback entrypoint. Scrollable currently uses a vertical viewport and caller-supplied extents. All strings are copied and all event payloads are snapshots; none of these limited variants implies full source component parity. SDL applications can call `cui_bridge_set_font_fallbacks` with up to 32 explicit UTF-8 font paths. The native font loader opens an owned replacement chain transactionally; an invalid path leaves the old chain intact. A render failure after backend creation returns `CUI_BRIDGE_CORE_ERROR` rather than reporting the backend unavailable. The optional native regression test uses `CUI_TEST_FONT_PATH` for a primary font without ✓ and `CUI_TEST_FALLBACK_FONT_PATH` for a font with ✓; run it under isolated Xvfb. ## Bounded typed root shadows See [typed root shadow authoring](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_SHADOWS.md) for the six-kind implementation, owned values, canonical CSS/preset factories and explicit clear/reset behavior. Focused portable runtime tests cover this subset; integration remains pending. This does not expose compound parts or portals. For bounded semantic ROOT/MAIN/indicator/track/thumb authoring, read [typed part shadows](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_PART_SHADOWS.md). Slider has no thumb; owner topology, whole-group naming and separate reset are explicit parts of that contract. --- ## Bridge notification snapshots (V1) Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_NOTIFICATIONS.md # Bridge notification snapshots (V1) The additive C API `cui_bridge_poll_notification_v1` returns a versioned typed view of the **existing** notification queue. It does not register callbacks, change timing, add input routing, or turn applied bridge mutations into controlled requests. The legacy ABI version, options, event structs and polling APIs remain unchanged. [The design](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/BRIDGE_TYPED_EVENTS_SLICE.md) includes future wrapper work; C, Python and JS/TypeScript manual polling are implemented here. ## Capability and polling ```c #include static cui_bridge_status next_notification(cui_bridge_app *app, cui_bridge_notification_v1 *event, char text[4097], uint32_t *required) { if (!(cui_bridge_notification_versions() & 1u) || cui_bridge_notification_v1_size() != sizeof(*event)) return CUI_BRIDGE_INVALID_STATE; return cui_bridge_poll_notification_v1(app, sizeof(*event), event, text, 4097, required); } ``` V1 capability is bit0. The size query includes native ABI padding; never pack the FFI struct manually. Exact size is required before consumption, and successful output includes `struct_size` and `schema_version=1`. Dynamically loaded consumers must look up the optional new symbols; older libraries lack them and continue supporting their old APIs. Future layouts require a new versioned symbol, not writes beyond V1 storage. Step/render still produces snapshots before foreign-language dispatch. The V1 manual poll only consumes data; reading returned records never dispatches or changes component values. Poll V1, `poll_event_ex`, or filtered `poll_event` from one consumer: all drain the **same queue**, so mixed calls consume successive events rather than independent copies. The old filtered poll still skips/discards every non-CLICK event. `kind` is ACTIVATE, CHANGE or LIFECYCLE. `payload_kind` determines the active union member. `node` and `node_kind` describe the origin captured at enqueue time; `legacy` retains the complete old checked/value/text-length/selected-handle snapshot. UTF-8 text is copied separately into caller storage. `frame_sequence` stays uint64; `HAS_FRAME` is present only for nonzero captured sequences. Identity is context-local, not a timestamp or global ordering. No input index, source, pointer/key/accessibility evidence, or Core `cui_id` is fabricated from bridge handles. ## Committed initial allowlist The table is the complete typed producer allowlist for this slice. Do not enable additional tags solely because a generic numeric/text field looks plausible. | Enqueue producer | `kind` / `payload_kind` | Typed payload | | --- | --- | --- | | Existing CLICK enqueue, including simple click adapters | ACTIVATE / NONE | No inferred input evidence. | | Checkbox, Switch, Toggle CHANGE | CHANGE / BOOLEAN | `payload.boolean_value`, exactly0/1, already applied bridge state. | | DataTable selection and sort | CHANGE / TABLE | `payload.table`: reason, row, column, sort_column, sort_direction, copied directly at the original enqueue point. | | Existing CLOSE enqueue (surfaces and notification close) | LIFECYCLE / SURFACE | `payload.surface_result`, existing ACCEPTED/CANCELLED/CLOSED constants. | | Every other CHANGE producer | CHANGE / LEGACY | Complete `legacy` fields and copied UTF-8 text; no guessed typed meaning. | DataTable indices preserve the existing bridge convention: zero means no selected row/column/sort column; selected indices are one-based. The existing bridge supports at most16 columns and32 rows. Column2 and above remain integers in V1 instead of becoming booleans. Old `legacy.checked` still contains the raw column integer and old JSON remains unchanged. Typed table fields are captured beside JSON; no poll-time parsing or latest-state getter reconstructs them. Selection reason is `CUI_BRIDGE_TABLE_SELECTION`; sort reason is `CUI_BRIDGE_TABLE_SORT`. SCALAR, TEXT and SELECTION tags/union members are reserved and **not emitted** by this slice. Input/Textarea/Editor/OTP, numeric controls, selection composites, date/time/color, questionnaire/speech/dock and other producers stay LEGACY. A selected-item handle in `legacy.selected` is a historical slot/generation snapshot. It may be stale at delivery; do not resolve it to a replacement node reusing that slot. Stale origins are dropped under the same rules as existing extended polling. ## Storage, failures and lifetime Supply disjoint fixed-output, required-size and text storage, with the declared writable extents. Success copies complete text plus NUL, publishes the fixed result, and consumes exactly once. `text_length` excludes NUL. Empty text still needs capacity1. This poll allocates nothing, truncates nothing and adds no new text limit. Existing producers have their own bounds; common editable snapshots fit4096 bytes, so4097 is a useful starting buffer, not a universal schema limit. On `CAPACITY`, only `required_capacity` changes. The live event remains queued, fixed output/text bytes remain unchanged, and retrying with that capacity retrieves the same snapshot. Preceding stale origins may already have been cleaned up; failure is not a transaction restoring stale entries. `EMPTY`, invalid size/arguments and other errors leave outputs unchanged. C callers choose allocation/retry policy. The Python and Node wrappers start with4097 bytes and retry once with the requested capacity, up to1MiB including NUL. An oversized, non-increasing or repeated capacity response raises an error without truncation; a capacity failure leaves the live event queued for another capable consumer. Memory allocation failures also propagate. Queue storage keeps the existing max-event policy (default256, maximum4096). New typed fields add fixed per-slot bytes; no second queue or per-event typed allocation is introduced. Existing queued text allocations and failure handling remain. Queue exhaustion can happen after a component has mutated: a failed step does not roll back bridge state or previously queued events. The returned struct and caller text copy remain valid after later frames, origin removal or app destruction, provided the caller storage survives. They do not own live nodes. C pointer copying is not ownership transfer, and copying arbitrary `cui_event` does not deep-copy borrowed text. ## Python and JS/TypeScript manual mode Python already separates stepping from dispatch: ```python app.step() for event in app.poll_notifications_v1(): if isinstance(event, BooleanChangeNotificationV1): print(event.value, event.frame_sequence) ``` Import `BooleanChangeNotificationV1` from `cui_bridge`. Python returns frozen dataclasses: `ActivationNotificationV1`, `BooleanChangeNotificationV1`, `TableChangeNotificationV1`, `SurfaceCloseNotificationV1`, or `LegacyNotificationV1`. Common fields include `handle` (slot/generation tuple), optional `node`, `frame_sequence` (exact Python integer), `has_frame`, `node_kind`, and frozen `legacy`. Table `reason` is `"selection"` or `"sort"`; indices remain one-based. `legacy.checked_raw` preserves the integer, `legacy.text` owns its string, and `legacy.selected_handle` preserves historical identity. Only `LegacyNotificationV1` adds optional `selected_node`. ```js app.step_only(); // submit a frame; do not dispatch callbacks let event; while ((event = app.poll_notification_v1()) !== undefined) { if (event.kind === 'table-change') console.log(event.column, event.frame); } ``` JS `step()` and `run()` retain automatic legacy callback dispatch. Choose `step_only()` and own the drain for manual mode; it has the same alive/running guards and default `dt=1/60` as `step`. Mixing default dispatch with manual polling consumes successive records from one queue; it never fans out copies. Python `dispatch()` likewise drains the same queue. JS returns frozen records with discriminants `activation`, `boolean-change`, `table-change`, `surface-close`, or `legacy`. Shared fields are `schemaVersion:1`, frozen `handle`, optional `node`, exact uint64 `frame:bigint`, `hasFrame`, `nodeKind`, and frozen `legacy` (`type`, `checkedRaw`, `value`, `text`, frozen `selectedHandle`). Boolean records add `value`; table records add `reason`, `row`, `column`, `sortColumn`, `sortDirection`; surface records add numeric `result`; legacy records add optional `selectedNode`. TypeScript exports the discriminated `NotificationV1` union and requires BigInt-capable compilation/runtime (for example ES2020/Node18). Convert BigInt explicitly when serializing JSON; converting to Number can lose precision. Text and raw handle copies survive later frames, removal and app destruction. Optional node references are resolved by exact slot **and generation** at delivery, never by slot alone; they are live wrapper objects, not independent node ownership, and may later become invalid. Returned record immutability does not freeze the referenced node. Python lazily checks optional C symbols, V1 capability and exact native struct size; older libraries remain usable through existing APIs and manual V1 polling raises an explicit unavailable/mismatch error. Node checks both addon availability and optional native symbols/layout. Neither wrapper registers listeners, auto-dispatches new views, or interprets reserved payload tags as scalar/text/selection values. ## Supported boundary and proof Python and JS/TypeScript provide owning manual views; Go/Rust availability is independent of this slice. Existing callbacks retain their after-frame timing and old payload conversions, including legacy boolean column loss and JS Number frame precision limits. There are no new dispatch/fanout hooks, listener lifetimes, promises, synchronous rejection or request bindings. The [binding audit](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_BINDINGS.md) remains authoritative for those existing limitations. No full family uniformity or parity is claimed. `tests/unit/test_bridge_notifications.c` uses the real headless bridge to verify old ABI layouts, shared-queue old/new interleaving, FIFO boolean snapshots versus later mutation, queue exhaustion without false rollback, stale origin cleanup/generation reuse, stale selected-handle retention, size/capacity failures and exact retries, UTF-8/4096-byte copies, all16 DataTable columns plus sort fields, legacy raw fields/JSON and surface close outcomes. Legacy bridge C and Python regression suites remain required. Native CTest runs use the invisible wrapper: ```sh python scripts/test_local.py --build-dir build -- -R 'bridge_notifications|bridge_core|bridge_components|bridge_python' ``` `bindings/python/test_notifications_v1.py` and `bindings/node/test/notifications-v1.test.cjs` exercise real queued boolean/table/activation records, manual versus legacy consumption and owning copies. Python additionally injects optional-symbol/layout/capacity protocol failures. The Node test-only uint64 conversion fixture checks values beyond2^53 through UINT64_MAX using the polling conversion helper; these are conversion checks, not fabricated input/frame evidence. `bindings/node/test/notifications-v1-protocol.test.cjs` reuses the test-only C provider in `bindings/tests/notification_v1_fixture.c` in fresh Linux processes (preloaded via `LD_PRELOAD`, with `CUI_NOTIFICATION_FIXTURE=edges|capacity|limit|zero|repeat|size|unavailable`). It verifies full native-to-JS uint64 conversion, large copied payload retries, explicit protocol errors, and continued legacy dispatch. These injected records are separate from the real queued tests. `bindings/node/test/notifications-v1.types.ts` checks union narrowing/read-only fields when compiled with `tsc --noEmit --strict --target ES2020 --module Node16 --moduleResolution Node16`. Build/test registration, exports/generated SDKs, and human/LLM guide indexing are integrator-owned. This guide documents implemented source behavior; wrapper availability must be checked separately. --- ## Manual queued notifications in Go and Rust Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_NOTIFICATIONS_GO_RUST.md # Manual queued notifications in Go and Rust `App.PollNotificationV1()` in Go and `App::poll_notification_v1()` in Rust drain one notification from the same native FIFO used by legacy polling and dispatch. They invoke no handlers. `Step`/`step` already leave that queue alone; no alternate step method is needed. Existing dispatch, frame and run behavior is unchanged. Choose one queue owner: mixing dispatch and manual polls consumes each entry once, in call order. These are asynchronous committed snapshots, not synchronous controlled-component requests or binding callback subscriptions. Go returns `(NotificationV1, bool, error)`; false with nil error means empty. `Kind` selects activation, Boolean change, table change, surface close or Legacy; only its applicable Boolean/Table/Surface pointer is populated. Rust returns `Result>`, with an owning enum for the same variants. Metadata contains captured raw slot/generation identity, node kind, exact `uint64` / `u64` frame, `HasFrame` / `has_frame`, and the complete owning legacy snapshot. Frames are context-local, not global timestamps or native activation identities. Go resolves an originating Node only by its complete registered handle. Rust's Node embeds its app identity and captured generation. Native polling skips stale origins. A legacy selected handle stays raw: no slot-only lookup or inference that it is still live. All protocol integers retain their unsigned widths. Only the native initial allowlist is typed: activation, Checkbox/Switch/Toggle committed Boolean changes, DataTable changes, and surface close. Input text, sliders and grouped selection remain Legacy. Reserved scalar/text/selection tags are not advertised as supported. Table columns preserve the native 1-based value (including values greater than one); zero retains its native sentinel meaning. The legacy snapshot includes the original textual table representation too. ```go notification, ok, err := app.PollNotificationV1() if err != nil { return err } if ok && notification.Kind == cui.NotificationBooleanChangeV1 { checked := notification.Boolean.Value _ = checked } ``` ```rust if let Some(cui_builders::NotificationV1::BooleanChange(meta, checked)) = app.poll_notification_v1()? { let _snapshot = (meta.frame, checked); } ``` Both wrappers verify the optional V1 symbols, advertised version bit and exact C structure size before polling. Older shared libraries still support the old APIs; new polling reports unavailable (Rust `Error(9)`) without draining legacy events. Go statically linked older libraries use weak optional references on supported GCC/Clang toolchains; Rust source builds compile the current schema. Shared-library resolution is implemented for Unix and Windows; only Linux execution was checked for this slice, not cross-platform runtime parity. Text is copied into owned strings before returning. The first buffer holds 4097 bytes, followed by at most one capacity retry, capped at 1 MiB including NUL. Oversized required capacity returns Go `ErrNotificationPayloadLimit` or Rust `NOTIFICATION_PAYLOAD_LIMIT`; that live event remains queued. Inconsistent capacity reports and malformed schema/tag/UTF-8 responses fail explicitly. Validation after a successful native read cannot undo that read; no promise of retaining malformed third-party library responses is made. No silent Legacy fallback is performed. ## Verification `bindings/go/cui/notifications_v1_test.go` and Rust `tests/notifications_v1.rs` exercise the real C queue: Boolean entry snapshots, FIFO/manual ownership, stale origin removal, copied UTF-8 text and multi-column table payloads. Go also interleaves legacy polling and verifies no automatic callbacks. `bindings/tests/notification_v1_fixture.c` is a separate test-only shared shim: its `CUI_NOTIFICATION_FIXTURE` modes `edges`, `capacity`, `limit`, `zero`, `repeat`, `size`, and `unavailable` inject protocol responses. These are not evidence that real UI producers emit oversized text or maximal frame values. Use a fresh process per mode. It exports only V1 entry points and links the real bridge for ordinary App APIs. On Linux Rust shared-library tests preload this shim; Go loads it explicitly. Production libraries contain no fixture hooks. A local external CTest harness invokes these suites through `scripts/test_local.py` with private Xvfb. The shim compiles as C11 with `-Wall -Wextra -Werror -pedantic`. The wrappers also compile against source-built static SDKs. Generated SDK copies are validation inputs only; their regeneration belongs to the integrator. Run the reproducible offline Linux matrix from a fresh, regenerated SDK checkout: ```sh python scripts/test_notification_bindings.py \ --build-dir /absolute/external/notification-checks \ --library /absolute/native-build/libcui_bridge.so ``` Requires an existing Git checkout, Go (cgo/C11), Cargo, CMake, `cc`, and `xvfb-run`; the supplied shared bridge must already implement V1. No dependency installation or network resolution is performed (`GOTOOLCHAIN=local`, Go proxy/checksum lookup disabled, Cargo offline). Use an external build directory. The script stages the binding sources without modifying SDKs, checks bridge header/source freshness, builds the existing test-only fixture with strict warnings, and runs CTest through the private display wrapper. Full Go/Rust portable static and dynamic suites cover real V1 queues and legacy compatibility; fourteen further cases cover the seven injected protocol modes in both languages. Native window lifecycle tests are explicitly excluded from this font-free notification matrix; the separate native runner suite owns those checks. Optionally pass `--older-library /absolute/pre-v1-build/libcui_bridge.so` to add two genuine missing-symbol compatibility cases (twenty total). Synthetic `unavailable` mode otherwise checks version negotiation, not missing symbols. Every compiler/test failure exits nonzero. Staged inputs, language build caches, CTest configuration and `ctest/Testing/Temporary/LastTest.log` remain under the build directory for diagnosis. Repeated runs preserve prior staged inputs; save CTest logs separately when retaining historical run evidence. --- ## Bridge value notification views (V1) Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_VALUE_NOTIFICATIONS.md # Bridge value notification views (V1) The C-only `cui_bridge_poll_value_notification_v1` opts into scalar, plain-text and selected-handle views on the **existing shared notification queue**. It preserves the shipped V1 layout, ABI version, size/version queries, old polling functions and dispatch timing. [Initial V1 notifications](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_NOTIFICATIONS.md) still define ownership and queue behavior. This API reports existing applied bridge mutations; it is not a direct-C facade, controlled request, callback registration or synchronous foreign veto. ```c #include static cui_bridge_status next_scalar(cui_bridge_app *app, cui_bridge_notification_v1 *out, char *text, uint32_t capacity, uint32_t *required) { if (!(cui_bridge_notification_versions() & 1u) || cui_bridge_notification_v1_size() != sizeof(*out) || !(cui_bridge_notification_value_payloads_v1() & CUI_BRIDGE_VALUE_SCALAR_V1)) return CUI_BRIDGE_INVALID_STATE; return cui_bridge_poll_value_notification_v1(app, sizeof(*out), CUI_BRIDGE_VALUE_SCALAR_V1, out, text, capacity, required); } ``` Dynamic consumers must resolve the two new optional symbols before calling them. Older libraries lack these symbols; retain old APIs or report unavailable without draining through another poll. The category query returns `CUI_BRIDGE_VALUE_SCALAR_V1 | CUI_BRIDGE_VALUE_TEXT_V1 | CUI_BRIDGE_VALUE_SELECTION_V1`; each bit is `1u << payload_tag`. Request only categories understood by your decoder. [Python](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_VALUE_NOTIFICATIONS_PYTHON.md) and [JavaScript/TypeScript](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_VALUE_NOTIFICATIONS_JS.md) and [Go](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_VALUE_NOTIFICATIONS_GO.md) and [Rust](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_VALUE_NOTIFICATIONS_RUST.md) owning value polling are implemented separately. Rust static builds require the paired SDK; dynamic exports are negotiated. Existing V1 manual methods retain their initial typed allowlist. Bundled Go/Rust SDK source snapshots include the C API. ## Complete scalar producer allowlist | Existing bridge producer | New opt-in payload | Precision and event boundary | | --- | --- | --- | | Slider | CHANGE / SCALAR | Existing local float is promoted to stored double; no precision beyond the actual float interaction is invented. | | NumberInput | CHANGE / SCALAR | Stored double copied directly after existing aggregate `result.changed`; numeric draft text is not a text event. | | Rating | CHANGE / SCALAR | Existing float value promoted to double. | | Pagination | CHANGE / SCALAR | Existing page stored as model double; not an arbitrary integer/ID transport. | Read `payload.scalar_value` only for SCALAR. The full `legacy` snapshot is retained, including the same double in `legacy.value`, checked/raw fields, historical selected handle, frame and text length. Typed values are captured beside those fields at enqueue, before later model mutation. Poll does not parse JSON or query current node state. Existing component aggregate counts, input ordering and render traversal stay unchanged; this does not add per-edit/per-input multiplicity or COMMIT/SUBMIT notifications. Programmatic setters and render-only Progress do not acquire notification producers. All other producers retain their existing classification: initial CLICK/BOOLEAN/TABLE/SURFACE tags are unchanged, and remaining CHANGE producers stay LEGACY. Combobox, unaudited selection composites, date/time/color and Menu/Dropdown commands remain LEGACY. No family parity claim is made. ## Complete plain-text producer allowlist Input, Textarea, Editor and InputGroup emit CHANGE / TEXT only when their existing aggregate changed result enqueues a record. Read the complete UTF-8 bytes from the separate caller buffer and `text_length`; there is no text pointer in the union. `legacy.text_length` describes the same owned queued copy. Existing input buffers hold4096 bytes plus NUL; lengths are UTF-8 bytes, not characters. Multiple edits in one frame remain a single final aggregate snapshot. No before/after selection, individual edit, submit, commit or reason is invented. InputGroup addon CLICK events retain their separate origin/order. Text classification occurs only after the existing enqueue copy succeeds; allocation/queue failure behavior is unchanged. A later setter changes the model without rewriting queued bytes or producing an event of its own. Old V1 and unrequested TEXT masks still return the complete LEGACY text. Textarea/Editor do not gain secure masking. The bridge currently exposes no masked/password configuration and copies underlying plain model bytes; direct C Input facade redaction does not carry over. OTP, Speech and TextView remain LEGACY. Future secure support must address both typed and legacy queued copies before exposing a security option; this API makes no secure-text promise. The public bridge key enum lacks Backspace/Delete/select-all keys, so the portable fixture cannot prove deletion-to-empty through that input surface. It tests initial empty model/setter silence instead of fabricating an empty edit event. The general V1 empty-text capacity contract remains one byte for NUL. ## Complete selection producer allowlist RadioGroup, Tabs, Select, List and Stepper emit CHANGE / SELECTION at their existing aggregate enqueue sites. `payload.selected` is the full uint32 slot/generation handle captured at enqueue; `legacy.selected` retains the same historical identity and `legacy.value` retains its old numeric slot snapshot. This is a bridge Item handle, not a Core uint64 ID, numeric index, previous-selection record or direct-C selection callback. No reason/input index/activation evidence is invented. Existing validation captures a nonzero selection only for a live direct child. A nonzero model value that fails that validation remains LEGACY rather than being mislabeled a clear. An explicit model0, if an existing producer enqueues it, represents an empty handle `{0,0}`. The public clear setter itself is silent; tests do not invent an empty selection input event to exercise that representation. Normal public selected setters reject stale/wrong-parent handles before mutation. The enqueue count and final-state aggregation remain unchanged. List can enqueue the same selected Item again on activation. Select's existing final comparison can suppress a complete frame that returns to its initial item; direct C's newer per-transition observer does not cause bridge records to appear. Delayed delivery preserves the captured generation after selected-item removal/reuse; it never resolves a historical slot to a replacement. Origin-staleness cleanup remains the existing poll policy. Menu and DropdownButton commands remain LEGACY even when their old selected field contains an Item handle. Combobox query and selection enqueue sites also remain LEGACY, including their text, because they share a mixed snapshot model with different reasons. Tree/Carousel/Command/Sidebar/Dock/Settings are not classified merely because their value looks like a child slot. No additional manifest family or synchronous foreign callback is introduced. ## Backward compatibility and failures Existing Go/Rust V1 decoders reject unknown/reserved tags after consuming a record. Therefore `cui_bridge_poll_notification_v1` continues returning newly captured value producers as LEGACY, with complete unchanged legacy fields/text and an inactive zeroed union. The new poll with mask0 does the same. The new poll returns SCALAR/TEXT/SELECTION only for the requested category and its explicit allowlist. Legacy `poll_event_ex` retains its original scalar snapshot; filtered `poll_event` still skips/discards CHANGE while looking for CLICK. Every path drains the **same FIFO**; it never broadcasts duplicate events. Unsupported mask bits (including bits for NONE/BOOLEAN/TABLE/SURFACE/LEGACY), wrong struct size, null fixed-output or null required-capacity pointer fail INVALID_ARGUMENT before stale cleanup or queue consumption, with outputs intact. This check does not modify the legacy poll contract. Existing stale origin/generation cleanup still happens during a valid poll. CAPACITY changes only `required_capacity`, preserving fixed/text output and the live record; preceding stale cleanup is not rolled back. Empty text requires capacity1 for NUL. Exact-capacity retry retrieves the same captured scalar. EMPTY and other failures preserve outputs. Caller storage extents must be valid and disjoint as required by V1. The poll allocates nothing, adds no text cap, truncates nothing and introduces no queue or per-event typed allocation. Existing queue-full behavior is unchanged: a control may already have mutated before enqueue fails, and prior records remain queued. No rollback is implied. Copied scalar/metadata records survive later frames, origin removal and app destruction while caller storage survives; handles do not own live nodes. `node` remains uint32 slot/generation identity; frame sequence remains exact uint64 and only HAS_FRAME is available. No input index, source, pointer/key/accessibility snapshot or Core `cui_id` is inferred. Do not convert uint64 frame identities to a lossy JS Number in future wrappers; the scalar's double representation is unrelated to frame/handle precision. ## Proof and validation [test_bridge_value_notifications.c](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_bridge_value_notifications.c) drives real headless bridge input for all four producers, including NumberInput key mutation above float precision, pointer Slider/Rating/Pagination changes, delayed capture after a later setter, disabled controls and closed Collapsible child suppression. There is no new public bridge inert/layout-only switch; the fixture exercises existing closed-content suppression rather than injecting Core routing. It freezes V1 size/offsets, verifies category negotiation, invalid mask/size/output atomicity, exact capacity retry, mask0/old-V1 downgrade, old extended/filtered poll interleaving, unchanged boolean/text classifications and queue exhaustion without false rollback. Existing initial-V1 and bridge core/component tests remain required. ```sh python scripts/test_local.py --build-dir build -- -R '^(bridge_selection_notifications|bridge_text_notifications|bridge_value_notifications|bridge_notifications_v1|bridge_core|bridge_components)$' ``` [test_bridge_text_notifications.c](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_bridge_text_notifications.c) additionally drives all four text producers with real UTF-8 input, one aggregate for two queued edits,4096-byte boundary/exact retry, delayed copies, old/masked-out/extended-poll interleaving, unchanged disabled behavior and queue-full mutation without rollback. It does not inject a secure bridge configuration or allocation-failure hook. [test_bridge_selection_notifications.c](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_bridge_selection_notifications.c) additionally drives all five selection producers, old/masked-out/extended polling, delayed selected handles, stale selected generations and slot reuse, List repeat, Select return-to-initial suppression, clear-setter silence, disabled controls, exact capacity/error atomicity and overflow without rollback. Real Menu/Dropdown commands and Combobox query/selection remain LEGACY even when value masks are requested. Native automated tests use the invisible wrapper; no desktop display is required. Build registration, generated SDK source snapshots and human/LLM indexes include this C API. Python, JS/TypeScript, Go and Rust have owning value wrappers. The [design checkpoint](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/BRIDGE_VALUE_NOTIFICATIONS_SLICE.md) describes deferred categories and compatibility decisions; it is not evidence those categories ship. --- ## Go owning value notifications Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_VALUE_NOTIFICATIONS_GO.md # Go owning value notifications `(*App).PollValueNotificationV1() (ValueNotificationV1, bool, error)` is an additive, manual owning view over the existing FIFO. `PollNotificationV1`, its struct and enum, legacy `PollEvent`, `Dispatch`, `Step` and `Run` keep their contracts. Nothing here registers callbacks, broadcasts events or makes foreign synchronous requests. ```go field := cui.Input("name") app, err := cui.New(cui.Options{}) if err != nil { panic(err) } defer app.Close() if err := app.Mount(cui.Column("root").Children(field)); err != nil { panic(err) } if err := app.Step(1.0 / 60); err != nil { panic(err) } for { event, ok, err := app.PollValueNotificationV1() if err != nil { panic(err) } if !ok { break } switch event.Kind { case cui.ValueNotificationScalarChangeV1: fmt.Println(event.Scalar.Value) case cui.ValueNotificationTextChangeV1: fmt.Println(event.Text.Text) case cui.ValueNotificationSelectionChangeV1: fmt.Println(event.Selection.Handle) } } ``` The example assumes imports `fmt` and `github.com/mattmezza/cui/bindings/go/cui`. Call `Step` after host input as appropriate; it does not automatically dispatch Go handlers. Do not also drain through `Dispatch`/`Run` when manual ownership is intended. All consumers divide the same queue rather than receiving independent copies. `ValueNotificationKindV1` is a separate enum, with activation, boolean, table, surface-close and legacy alternatives plus scalar/text/selection. Exactly the kind-selected payload pointer is nonnil; activation/legacy have no typed pointer. The new payloads are `ScalarChangeV1{Value float64}`, `TextChangeV1{Text string}` and `SelectionChangeV1{Handle Handle, Node *Node}`. The common fields mirror the existing view, including complete owning `LegacySnapshotV1`. Existing enum values/types do not acquire extra alternatives. Frames remain exact `uint64`, handles/indices exact `uint32`, scalar values binary64. NumberInput retains its double precision; Slider/Rating cannot recover precision already lost in float models. See [the C allowlist](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_VALUE_NOTIFICATIONS.md) for the four scalar, four plain-text and five selection producers. Combobox/menu and unsupported producers remain LEGACY, with no JSON parsing or invented evidence. The bridge has no secure-text configuration or inferred redaction. This API is not a forwarding layer for all direct-C event facades. Values, strings and identities are copied and survive later model mutation/removal and app disposal. Go records are caller-mutable, not frozen objects. Payload pointers point to owned Go allocations, not C storage. Optional `Node` references are live objects resolved by exact slot **and generation**, not immutable model snapshots. A removed historical selection retains its identity but resolves to nil. Both dynamic symbol lookup and the portable static weak-symbol path independently resolve size/version/category/poll capabilities. Only advertised known category bits are requested; unknown capability bits are ignored. Missing optional symbols, wrong layout/version or no known category fails before polling, without fallback to a legacy drain. Older libraries remain usable through existing polling APIs. The existing allocation policy starts at 4097 bytes, permits one strictly growing retry and caps capacity at 1 MiB including NUL. `ErrNotificationPayloadLimit` and inconsistent retries leave the live record queued. Successful native polling consumes before decoding; malformed kind/tag/metadata/UTF-8/payload errors cannot roll the record back. Decode checks include genuine frame presence, legacy identity consistency, finite scalar values, full selection identity and negotiated tags. No source/input-index/activation metadata is fabricated. ## Evidence and reproduction `bindings/go/cui/value_notifications_v1_test.go` exercises real queued NumberInput, Input and RadioGroup events in both static and dynamic builds, binary64 precision, old/new FIFO interleaving, setter/disabled silence, copied UTF-8 and actual removal of a historical selection. Go's public mounted-tree API cannot append/recreate a replacement in this fixture. A separate **synthetic registry entry** checks same-slot/different-generation lookup; this is not Go allocator-reuse proof. Actual C allocator reuse is covered separately by C/Python/JS tests. An actual older initial-V1 library proves unavailable value polling leaves queued text available to the old poll. Build test executables offline, without regenerating SDK copies: ```sh cd bindings/go GOTOOLCHAIN=local GOPROXY=off go test -tags cui_dynamic -c ./cui -o "$build_dir/go-dynamic.test" GOTOOLCHAIN=local GOPROXY=off go test -c ./cui -o "$build_dir/go-static.test" ``` Use `CGO_CFLAGS=-I/absolute/canonical/include` when testing against a newer canonical header before SDK regeneration. Register executables in an external CTest harness. Set `CUI_VALUE_REAL=1` for real producers; dynamic mode also needs an absolute `CUI_BRIDGE_LIBRARY`. For an actual older library set `CUI_VALUE_OLD=1` and run only `-test.run=^TestValueNotificationV1TextFIFO$`. Static portable checks exclude `-test.skip=^TestNativeRunLifecycle$`; SDL runner tests need their native build/font and are outside this portable slice. Existing V1 and other portable Go tests remain included. Run CTest only through `python scripts/test_local.py --build-dir "$build_dir"`. The isolated Linux provider in `cui/testdata/value_notifications_provider.c` is synthetic protocol evidence, not input evidence. Compile it with strict C11 warnings, `-fPIC -shared`, canonical `-Iinclude`, and `-Wl,--no-as-needed -L"$old_bridge_dir" -lcui_bridge -Wl,-rpath,"$old_bridge_dir"`. It depends on the actual older bridge for normal App functions; do not substitute it for production. The no-known-category and missing-query modes also retain actual queued text for the old poll. A second build with `-DCUI_VALUE_FIXTURE_MISSING` omits the category query. Point dynamic library selection to the provider and run only `TestValueNotificationV1Protocol`, fresh process per `CUI_VALUE_FIXTURE` mode: `edges`, `capacity`, `size`, `unavailable`, `missing`, `limit`, `zero`, `repeat`, `tag`, `kind`, `utf8`, `nul`, `flags`. These check exact uint64 extremes, unknown capability filtering, optional exports, malformed output and bounded copies. Rust value wrappers and generated SDK publication remain separate integration work. The repository integrator runner also stages current SDK sources and registers static, dynamic, legacy, protocol and actual older-library cases offline: ```sh python scripts/test_notification_bindings.py --build-dir /absolute/validation-dir \ --library /absolute/current/libcui_bridge.so \ --value-older-library /absolute/initial-v1/libcui_bridge.so ``` The older value library must expose initial V1 but lack the new value symbols. Without it, missing-export/older-library no-drain cases are explicitly deferred. The independent `--older-library` option tests a genuinely pre-V1 library instead. --- ## JavaScript and TypeScript owning value notifications Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_VALUE_NOTIFICATIONS_JS.md # JavaScript and TypeScript owning value notifications `App.poll_value_notification_v1(): ValueNotificationV1 | undefined` is an explicit, manual drain of the **same queue** used by `poll_notification_v1()`, legacy dispatch, `step()` and `run()`. It adds no listeners or synchronous requests. Existing V1 API/types and automatic dispatch stay unchanged. Use `step_only()` when the caller owns draining; mixing consumers divides events rather than broadcasting them. ```js const c = require('@cui/native'); const app = new c.App(); try { app.mount(c.column().children(c.input('name', ''))); app.step_only(); // call after each host input/frame as appropriate let event; while ((event = app.poll_value_notification_v1()) !== undefined) { if (event.kind === 'text-change') console.log(event.text); if (event.kind === 'scalar-change') console.log(event.value); if (event.kind === 'selection-change') console.log(event.selectedHandle); } } finally { app.dispose(); } ``` The new union extends the existing notification alternatives with: | Kind | Owning payload | | --- | --- | | `scalar-change` | `value: number`, the captured C binary64 value | | `text-change` | `text: string`, copied UTF-8 | | `selection-change` | frozen `selectedHandle: {slot, generation}`, optional `selectedNode` | See [the C allowlist](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_VALUE_NOTIFICATIONS.md) for the exact four scalar, four plain text and five selection producers. Combobox, menu and other unsupported producers retain complete `legacy` snapshots; no JSON is parsed. NumberInput retains its double precision; Slider/Rating cannot recover precision already lost in their float models. There is no secure-text configuration or inferred redaction in this bridge API. This is not uniform component-event-facade coverage. Records, legacy snapshots and handle objects are frozen. Strings/numeric values and handles survive later mutation, queue reuse and app disposal. `node`/`selectedNode` are optional live JS object references resolved by the complete slot/generation; these references are not immutable model snapshots. Removed historical selections retain their copied handles without resolving a replacement generation. Handles and indices are exact uint32 Numbers; every frame is an exact uint64 **BigInt**, including values above 2^53. JSON serialization requires an explicit BigInt conversion policy. The production addon resolves the new C exports optionally, verifies V1 size/version, and requests only advertised known bits SCALAR/TEXT/SELECTION. Unknown capability bits are ignored. Missing addon method, missing native exports, or no known categories throw without falling back to another drain. Older native libraries remain usable through existing APIs. A missing/mismatched capability is checked before polling. Storage starts at 4097 bytes, with one strictly growing retry capped at 1 MiB including NUL. Invalid/non-growing/repeated/over-limit capacity responses throw; capacity failure does not consume the live record. A successful native poll consumes before validation: malformed tags/kinds, frame/legacy mismatches, flags, scalar values, selection handles, UTF-8 or termination cause a protocol error and cannot roll that record back. No unavailable source, activation or input-index evidence is fabricated. ## Validation and reproduction `bindings/node/test/value-notifications-v1.test.cjs` uses actual queued input for NumberInput, Input and RadioGroup, old/new FIFO, setter silence, payload copies and removed/reused selection generations. Run it again with `CUI_EXPECT_OLD=1` and an addon linked to an actual initial-V1 library to prove unavailable value polling does not drain its queued text. Legacy notification/binding/component tests also pass. The separate Linux interposition fixture is **synthetic protocol evidence**, not UI input. It checks unknown capability filtering, partial exports, layout failure, malformed kind/tag/flags/UTF-8/NUL, retry limits, an 8192-byte copy and uint64 extremes. The Node CMake project registers the real-queue and Linux protocol cases: ```sh cmake -S bindings/node -B build-node -DCUI_BUILD_NATIVE=OFF cmake --build build-node --target cui_node_bindings cui_value_notification_fixture python scripts/test_local.py --build-dir build-node -R '^node_value_notifications' ``` To include actual old-library and missing-symbol cases, configure with `-DCUI_NODE_VALUE_OLD_LIBRARY=/absolute/path/to/older/libcui_bridge.so` and also build `cui_node_old_value_bindings` and `cui_value_notification_missing_fixture`. These cases are not registered without an explicitly supplied old library. The synthetic provider is test-only and never adds hooks to the production addon. For an external compatibility harness, compile the addon and fixture manually: ```sh # Set bridge_dir to the directory containing the desired libcui_bridge.so. cc -std=c11 -Wall -Wextra -Wpedantic -Werror -fPIC -shared \ -Iinclude -I/usr/include/node bindings/node/addon.c \ -L"$bridge_dir" -lcui_bridge -Wl,-rpath,"$bridge_dir" -o "$build_dir/cui.node" cc -std=c11 -Wall -Wextra -Wpedantic -Werror -fPIC -shared -Iinclude \ bindings/node/test/value-notifications-provider.c -o "$build_dir/provider.so" # Compile again with -DCUI_VALUE_FIXTURE_MISSING for the partial-export case. ``` Register Node invocations in an external CTest harness with `CUI_NODE_ADDON` selecting the addon. For each protocol mode set `LD_PRELOAD` to the fixture and `CUI_VALUE_FIXTURE` to `edges`, `capacity`, `size`, `unavailable`, `missing`, `limit`, `zero`, `repeat`, `tag`, `kind`, `utf8`, `nul` or `flags`; run `value-notifications-protocol.test.cjs` in a fresh process. The `missing` fixture must use the missing-export build and an actual older bridge library, so the real library cannot supply the omitted symbol. Run native CTest only through `python scripts/test_local.py --build-dir "$build_dir"` (private Xvfb). Both old and new type fixtures compile with pinned TypeScript 5.8.3: ```sh npm exec --yes --package typescript@5.8.3 -- tsc --noEmit --strict \ --target ES2022 --module NodeNext --moduleResolution NodeNext \ bindings/node/test/notifications-v1.types.ts \ bindings/node/test/value-notifications-v1.types.ts ``` Go/Rust value wrappers and generated package/SDK publication are separate integration work. Generated `index.d.cts` continues to re-export the canonical TypeScript file. --- ## Python owning bridge value notifications Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_VALUE_NOTIFICATIONS_PYTHON.md # Python owning bridge value notifications `App.poll_value_notifications_v1()` is an explicit manual drain of the [C value notification queue](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_VALUE_NOTIFICATIONS.md). It yields frozen owning values without invoking callbacks. Existing `poll_notifications_v1()`, `poll_events()`, `step()`, `run()` and `dispatch()` retain their behavior. All poll/dispatch paths consume successive records from the **same queue**; they do not broadcast copies. ```python from cui_bridge import ( App, column, input, TextChangeNotificationV1, ScalarChangeNotificationV1, SelectionChangeNotificationV1, ) with App() as app: field = input("message", "") app.mount(column().children(field)) app.step() # submit; Python dispatch remains explicit # After later input/steps, own the queue drain: for event in app.poll_value_notifications_v1(): if isinstance(event, TextChangeNotificationV1): print(event.text) elif isinstance(event, ScalarChangeNotificationV1): print(event.value) elif isinstance(event, SelectionChangeNotificationV1): print(event.selected_handle) ``` The additive `ValueNotificationV1` type includes the existing notification classes and three new frozen dataclasses. Shared fields remain `handle`, optional origin `node`, exact integer `frame_sequence`, `has_frame`, `node_kind` and frozen complete `legacy` snapshot. | New class / `kind` | Owning fields | C allowlist | | --- | --- | --- | | `ScalarChangeNotificationV1` / `scalar-change` | `value: float`, copied binary64 | Slider, NumberInput, Rating, Pagination. Float-based controls retain their actual float precision; NumberInput retains stored double. | | `TextChangeNotificationV1` / `text-change` | `text: str`, copied and decoded UTF-8 | Plain Input, Textarea, Editor, InputGroup only. | | `SelectionChangeNotificationV1` / `selection-change` | `selected_handle: tuple[int,int]`, optional `selected_node` | RadioGroup, Tabs, Select, List, Stepper only. | Selection handles retain full uint32 slot/generation identity, including a stale historical selection. `selected_node` is resolved only by that exact pair from the current Python registry; slot reuse cannot resolve to another generation. It is a live Widget reference, not independent node ownership, and can later become disposed. The handle, scalar, text and complete legacy snapshot remain usable after later frames and app destruction. Frozen records do not freeze referenced Widgets. Python currently has no public per-node remove API; the stale-generation test explicitly uses the C fixture boundary and updates the test registry. Existing activation, boolean, table, surface-close and Legacy classes are also returned by the new method. Combobox query/selection, Menu/Dropdown commands and unaudited families retain Legacy records. Typed values reflect existing aggregate enqueue behavior, not direct C's per-event facade semantics or new submit/commit events. The C allowlist and its secure-text limitations remain authoritative: the bridge exposes plain edit text and does not inherit direct C Input facade password redaction. No new secure input, synchronous foreign requests, registration hooks or family parity is claimed. ## Negotiation, errors and lifetime The generator resolves optional V1 size/version and value-category/poll symbols before reading any queue record. It requests only the intersection of compiled-known SCALAR/TEXT/SELECTION bits and the library's advertised bits; unknown advertised bits are never enabled. An older library lacking symbols, or a library advertising no known value category, raises an explicit `BridgeError` without draining through an old poll. Existing old APIs remain usable. A native V1 layout/version mismatch likewise fails before polling. Existing `poll_notifications_v1()` continues receiving newly captured values as complete Legacy snapshots from the old C symbol. Text starts with4097 bytes including NUL and retries once for a strictly larger requested capacity, at most1MiB including NUL. Oversized, zero/non-increasing or repeated capacity responses raise `BridgeError`; no truncation occurs. C CAPACITY leaves the live record queued; allocation failures propagate. Invalid size/version/flags/frame presence, inconsistent legacy metadata, missing NUL/invalid UTF-8, unsupported tag/kind/category or malformed typed values raise protocol errors. A decode error follows a successful consuming C poll and does not restore that record. No fallback or replay is attempted. Payloads are notifications of applied bridge behavior. Reading a record does not invoke its Widget callback; calling `dispatch()` separately drains later records through the existing legacy path. No callback fanout or ownership change is added. The borrowed C text is copied into Python strings before yielding; result reads do not reference a mutable C text buffer. ## Tests and compatibility [The new Python fixture](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/python/test_value_notifications_v1.py) covers real NumberInput key mutation beyond float precision, copied UTF-8, selection/live and historical generations, old/new shared draining, existing boolean/table views, immutable fields and snapshots surviving app close. Its synthetic Python protocol provider separately checks exact UINT64_MAX frames/uint32 handles, compiled-known capability masking, wrong layout, malformed typed output, large retry and capacity limits. These are conversion/protocol tests, not fabricated UI input evidence. Existing initial V1 and legacy Python suites remain required. The real old-library case requires `CUI_BRIDGE_OLD_LIBRARY` pointing to an actual initial-V1 library without value symbols. It queues text there, proves the new method reports unavailable, and then retrieves the same bytes through old V1 polling. Without this explicit library the old-library case skips; it must not be counted as proved merely by the synthetic provider. Adjacent NumberInput and Input composition is also exercised through real input. A renderer identity collision exposed during this work is fixed; regression tests cover both ordinary and focused fields without changing public viewport IDs. Native validation uses `python scripts/test_local.py --build-dir build`; the Python bridge backend is `none` for these fixtures. CTest registers the fixture as `bridge_python_value_notifications`; set the explicit old-library environment variable to include its compatibility case. No other language value wrapper is implemented by this change. --- ## Rust owning value notifications Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_VALUE_NOTIFICATIONS_RUST.md # Rust owning value notifications `App::poll_value_notification_v1(&mut self) -> Result>` is a separate opt-in owning view over the existing queue. The original `NotificationV1` enum and `poll_notification_v1` method remain unchanged, including exhaustive matches. This adds no listeners, foreign synchronous requests or dispatch hooks. Polling and `dispatch`/`run` divide the same FIFO; they do not broadcast copies. ```rust use cui_builders::{App, Kind, ValueNotificationV1}; fn main() -> Result<(), cui_builders::Error> { let mut app = App::headless(640., 480.)?; let root = app.root(Kind::Column, "root")?; app.child(root, Kind::Input, "name")?; app.step(1. / 60.)?; while let Some(event) = app.poll_value_notification_v1()? { match event { ValueNotificationV1::ScalarChange(_, value) => println!("{value}"), ValueNotificationV1::TextChange(_, text) => println!("{text}"), ValueNotificationV1::SelectionChange(_, selected) => println!("{:?}", selected.handle), _ => {} } } Ok(()) } ``` Call `step` after host input as needed. `step` does not dispatch Rust callbacks. Choose manual draining or the existing callback dispatch loop deliberately. The separate enum retains activation, boolean, table, surface-close and legacy alternatives, and adds `ScalarChange(MetadataV1, f64)`, `TextChange(MetadataV1, String)` and `SelectionChange(MetadataV1, SelectionChangeV1)`. The latter contains `handle: RawHandle` and `node: Option`. Full legacy snapshots remain available in common metadata. Strings/numeric values/identities are owned Rust data and survive later mutation, removal, queue reuse and app drop. Rust callers can mutate their own returned values; this is not an immutable model snapshot. Frames are exact `u64`, slots/generations/indices exact `u32`, scalar values binary64. NumberInput keeps its double precision; Slider/Rating cannot recover precision already lost in float models. Optional Node capabilities are checked against the current full C slot/generation using a read-only getter before being returned; a removed identity does not resolve to a replacement generation. Node values remain live capabilities, not retained C objects; later operations still validate them. See [the C allowlist](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_VALUE_NOTIFICATIONS.md) for the four scalar, four plain text and five selection producers. Combobox/menu and unsupported producers remain LEGACY. Nothing parses their JSON or invents input source, activation or index metadata. No bridge secure-text configuration or inferred redaction is provided. This does not establish uniform direct-C component-event-facade coverage. Dynamic builds resolve optional size/version/category/poll exports, verify layout, and request only advertised known category bits. Unknown capability bits are ignored. Missing exports, unsupported version or no known categories return `Error(9)` before polling, without fallback to another drain. A layout mismatch returns `NOTIFICATION_PROTOCOL_ERROR`. Older dynamic libraries remain usable through their existing APIs. **Static builds link strong symbols from the paired bundled SDK**, as the existing Rust V1 implementation does; rebuild the crate with its matching bundled bridge. Compatibility with mismatched older static archives is not promised. Rust stable provides no portable weak-symbol mechanism here. The shared allocation policy starts at 4097 bytes and permits one strictly growing retry capped at 1 MiB including NUL. `NOTIFICATION_PAYLOAD_LIMIT` and inconsistent capacity responses leave a live record queued. Successful native polling consumes before decode; malformed output cannot be rolled back. Validation covers schema, flags, kind/tag, legacy/frame/identity consistency, negotiated tags, finite scalar values, selected identities, UTF-8 and NUL termination. Invalid UTF-8 returns `Error(7)`; other malformed output returns `NOTIFICATION_PROTOCOL_ERROR`. ## Evidence and reproduction `tests/value_notifications_v1.rs` uses actual NumberInput/Input/RadioGroup input in both static and dynamic builds: precision, setter/disabled silence, old/new FIFO, existing Checkbox/DataTable typed alternatives, owned copies after app drop, and actual selection removal plus same-slot/new-generation replacement through Rust's public `child` API. Old and new selected identities remain distinct and the historical event has no live Node. The old enum's exhaustive-match fixture compiles unchanged. Build offline using existing pinned dependencies (this crate adds none): ```sh CUI_BRIDGE_LIB_DIR="$bridge_dir" CARGO_TARGET_DIR="$dynamic_target" \ cargo test --offline --manifest-path bindings/rust/Cargo.toml --no-run CARGO_TARGET_DIR="$static_target" \ cargo test --offline --manifest-path bindings/rust/Cargo.toml --no-run ``` Register the resulting unit, builders, callback-panic, notification and value test executables in an external CTest harness, with `CUI_VALUE_REAL=1` and `--test-threads=1`. Serialized tests respect the process-global layout runtime. Exclude `run_native` explicitly from these portable checks; SDL runner proof requires its separate native build and font. Execute native CTest only through `python scripts/test_local.py --build-dir "$build_dir"` (private Xvfb). For older-library proof, run the dynamic value executable with an actual initial-V1 library selected through `LD_LIBRARY_PATH`, `CUI_VALUE_OLD=1`, and test filter `real_text_fifo_or_older_library_no_drain`. It queues real UTF-8 input, checks value polling is unavailable, then retrieves the unchanged text with old polling. `tests/fixtures/value_notifications_provider.c` is separate Linux **synthetic protocol proof**, not UI input evidence. Compile it with strict C11 warnings, `-fPIC -shared`, canonical `-Iinclude`, and link normal App exports from an actual older bridge with `-Wl,--no-as-needed -L"$old_bridge_dir" -lcui_bridge -Wl,-rpath,"$old_bridge_dir"`. Compile another with `-DCUI_VALUE_FIXTURE_MISSING` to omit its category query. Use `LD_PRELOAD` for the provider and `LD_LIBRARY_PATH` for the old bridge; run only `synthetic_protocol` in a fresh dynamic test process per `CUI_VALUE_FIXTURE` mode: `edges`, `capacity`, `size`, `unavailable`, `missing`, `limit`, `zero`, `repeat`, `tag`, `kind`, `utf8`, `nul`, `flags`. This covers uint64 extremes, unknown-bit filtering, partial exports, malformed output and bounded 8192-byte copies. The no-known-category and missing-query modes also run the real text test to verify no drain. Generated SDK/package publication is separate integrator work; no SDK copies change in this wrapper slice. --- ## Button pointer activation barriers Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BUTTON_ACTIVATION_BLOCKING.md # Button pointer activation barriers Disabled and loading Buttons now prevent a pointer press on their visible area from activating an underlying parent. This applies to `cui_base_button` when disabled and to styled `cui_button` when disabled or loading. Existing callback, keyboard and controlled state contracts are unchanged. `cui_semantic_details.blocks_pointer_activation` is an append-only, opt-in Core flag. Zero preserves the previous behavior of other controls. The previous-frame hit graph considers a flagged element even when it is disabled, using the same clip, modal, layer and submission-order rules as other pointer targets. A topmost barrier consumes primary DOWN without moving focus or assigning capture. Primary UP over a barrier cannot create an activation, including an activation of a previously captured ancestor. Existing capture still receives motion and UP for cleanup; CANCEL still clears capture. A later unobstructed press works normally. This flag blocks pointer activation and pointer focus only. It does not disable Tab, programmatic focus or keyboard activation on an otherwise enabled element. It does not consume wheel events or prevent touch panning an actual scroll owner. It also does not clear an existing text composition when the blocked press occurs. Hover, cursor and current-frame prepaint occlusion are independent: callers that need a passive hover occluder must use the existing hover/prepaint participation contract. The flag alone is not a general visual or hover occlusion policy. The focused regressions are `test_pointer_activation_blocker.c` (Core-only) and `test_button_activation_blocker.c` (real Base and styled Buttons and Scrollable). They cover legacy zero behavior, disabled/loading mouse and touch, focus retention, release activation counts, capture cleanup, cancellation, subsequent clicks, keyboard activation, clipping, later siblings, elevated layers, modal eligibility, composition retention, hover independence and ancestor wheel/touch scrolling. `tests/web/test_button_activation_blocker.py` independently builds its real CUI WASM fixture and drives Chromium mouse, keyboard, wheel and CDP touch contacts. The unfixed frozen source failed both disabled mouse and touch assertions with parent count 1 and parent focus; the corrected source preserves the textbox focus and leaves both callback counts at zero. The browser fixture also checks enabled clicks, retained capture, cancellation and scrolling without page fallback. Run it with pinned Playwright 1.58.0 and Chromium 1208; its `--source-root` option permits the same regression against an earlier source checkout. This is a scoped correctness fix, not certification of the complete upstream Button family, every host, accessibility platform or physical touch device. The separate Button completion audit still records remaining API and evidence gaps. Worker validation on the frozen `6e36b5a` base: warning-enabled native build had no warnings; existing CTest passed 121/122, with only the expected generated distribution mismatch pending integrator regeneration. Both new standalone tests passed `-std=c11 -Wall -Wextra -Wpedantic -Werror`, and passed ASan/UBSan with leak detection. The existing Button behavior test also passed the sanitizer run. The independent strict WASM build and full Chromium 1208 suite passed after the fix. These results do not substitute for the integrator's generated distribution and platform CI checks. --- ## Button behavior Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BUTTON_BEHAVIOR.md # Button behavior This change audits the Button at pinned upstream component v0.7.1 commit `87d10ae5e1299d1be18670a37570c5402f952e34` (`button/button.rs`, `button/button_icon.rs`, `base/button.rs`). It covers the features below; custom shadows, ordered tab indexes, action-keybinding tooltip registries, and arbitrary tooltip builders remain outside this API. It does not certify whole-family parity or physical-device accessibility. `cui_button_ex` retains the original primary variant, four legacy sizes, zero-initialized options, boolean activation result, and replacement `content` callback. Design sizes continue to derive all fourteen metrics from the theme. Default, Text and Custom append to the existing variants. Outline remains orthogonal. Link and Text use a hand cursor and no horizontal padding; Link keeps its legacy control height, while Text fits its natural content. Default uses the theme's default button palette. Custom uses an explicitly resolved palette; it does not reproduce the source's Oklab color mixing or shadow. Positive finite `height`, `font_size`, and `icon_size` override derived metrics (up to 4096 logical pixels). Rounding selects theme, none, half-theme, double-theme, or a caller's nonnegative finite radius. Compact reduces padding and keeps known text/icon content at least as wide as the control height. Arbitrary callback content must supply a suitable `width` when it needs a minimum width. Positive width is an intentional clipping constraint; negative width retains Core's grow convention. Callers must allow enough height for arbitrary content. Named `icon`, `trailing_icon`, `loading_icon` and `dropdown_caret` use the real SVG icon renderer. The catalog always lists all names, but default builds embed 126 SVG assets; choose bundled names (such as `check`, `arrow-right`, `chevron-down`, `loader`) or supply a theme loader / `CUI_ICON_ALL_ASSETS` for other catalog assets. Loading suppresses activation, exposes busy metadata, and fades the normal/selected palette to 80% rather than using disabled colors. A named loading glyph rotates using frame time; reduced motion keeps it still. A `leading_content` callback takes precedence over generated loading/leading artwork, allowing a caller-owned Progress or Spinner composition. `trailing_content` replaces trailing artwork. `children` appends content after the label or existing replacement callback. Slot callbacks own their borrowed user data, geometry, colors, and nested semantics. `on_click` runs once per accepted activation. The boolean return still reports that same activation: use one action path, rather than handling both as separate actions. `on_hover` reports interactive hover edges when a caller-owned state is supplied. Disabled/loading controls ignore activation and hover callbacks. `selected` remains presentation-only, with stable semantic value zero; `toggle_semantics` plus `toggled` explicitly supplies checked/value metadata. Browser or accessibility adapters must map that metadata appropriately; this change does not add a generic browser `aria-pressed` mapping. Pointer focus defaults remain compatible. `prevent_pointer_focus` opts into pointer activation/capture without replacing current keyboard focus, using Core's `no_pointer_focus` policy. Tab, Enter, Space, programmatic focus and cancellation continue through Core. `skip_tab` removes the tab stop; `hide_focus_ring` affects paint only. Focus rings otherwise show only for focus-visible interaction. `custom_cursor` uses the cursor-only setter and preserves the control's other semantics. Optional state stores only hover lifecycle, tooltip state, an ellipsis buffer, and an absolute next-wake deadline. Zero-initialize it, keep one state per stable ID, and keep it alive across frames; an ID change resets it. No state heap allocation or cleanup is required. Existing icon resources remain owned by the context. Tooltips use the shared hover implementation and require a viewport in `tooltip_options`; Escape, disabled state and targeted cancellation close/suppress them. Hosts should honor invalidation and `state.next_wake_seconds` in the Core frame-time clock (zero means idle). A positive `label_width` makes the plain label unwrapped and clipped. With state, it also ellipsizes at a grapheme boundary while preserving the complete original accessible name (or explicit `accessibility_label`). The scratch buffer is 256 bytes: a truncated prefix is capped at 252 bytes plus U+2026 and NUL. A fully fitting label remains borrowed and has no 256-byte cap. If the ellipsis itself cannot fit, the visible label is empty. This is plain-label truncation, not a rich-text filter, shaping replacement, or callback-content truncation. ```c #include "cui/cui_components.h" static cui_button_state save_state; static void save(void *user) { ++*(unsigned *)user; } void save_control(cui_context *ui, const cui_theme *theme, unsigned *saves) { (void)cui_button_ex(ui, cui_id_from(ui, "save"), theme, cui_string("Save changes"), (cui_button_options){.icon = cui_string("check"), .on_click = save, .action_user = saves, .state = &save_state, .prevent_pointer_focus = true, .custom_cursor = true, .cursor = CUI_CURSOR_POINTER}); } ``` Validation is scoped to `test_button_behavior.c` and `test_button_behavior.py`: controlled activation/cancellation and pointer focus, keyboard activation, inert loading/disabled state, stable toggle metadata, 432 variant/size/density paint-containment cases, real SVG slot geometry, custom content, Unicode/buffer-boundary ellipsis and tooltip lifecycle. The browser slot test also requires the host preview height to include the expanded variant and custom-content rows, and fails if those drawings are clipped by the canvas. The browser uses Chromium CDP touch contacts and actual mouse/keyboard input, not direct reducer calls. Native headless tests do not constitute SDL window or physical touchscreen coverage. Constrained labels now use the current frame's laid-out label bounds. A positive Button width, a grow width, or a positive `label_width` produces one clipped, no-wrap label with a grapheme-boundary prefix and an ellipsis when it fits. The original full label remains the semantic name. Leading/trailing artwork, text, custom slots and the caret retain their own layout allocation; custom content callbacks remain responsible for their internal layout. The content clip also contains their paint. FIT buttons retain intrinsic sizing. For fixed/grow Buttons, `content` children receive the current frame's inner width, including space reserved for padding and leading/trailing slots. Ordinary wrapped text and `cui_text_paragraph_colored(..., wrap=true)` wrap there just as they do inside a normal box. A custom mail row can use a grow-width row containing a fixed-width avatar and a grow-width column for the sender, subject and preview. The callback runs once during submission; resizing needs no previous-frame bounds or callback replay. Explicit fixed-width children and unwrapped text still obey those choices, and the Button clips overflowing paint. Nested scroll/clipping boxes retain their ordinary Core layout behavior. `test_button_content_layout.c` compares wrapped line counts with normal boxes for plain and paragraph text, fixed/grow widths, first-frame layout and resizing, avatar/text columns and leading/trailing slots. It also checks text bounds, avatar allocation and one callback invocation per submission. `test_button_content_font.c` repeats these cases with a caller-opened native font. `allow_content_overflow` is an explicit compatibility opt-out for the former wrapping/overflow behavior. Automatic label paint copies the full original bytes into the context's bounded frame arena, using `cui_set_prepaint_parts`; it introduces no heap allocation or new label-length limit. Borrowed slot resources retain their existing lifetime. The optional caller-owned `cui_button_state.label` remains a 256-byte diagnostic and compatibility buffer, so its truncated prefix keeps the previous bound. Without that state, prefixes are limited by available width and frame capacity. Prefixes preserve graphemes, while ellipsis fitting uses separately measured prefix and ellipsis widths; this does not claim contextual shaping across the join. Font shaping and glyph fallback remain adapter responsibilities. Arena, command and registration capacity errors remain observable through Core's error API and empty failed frame. Accepted callbacks occur during submission, before later paint allocation failures; paint failure does not roll back an already accepted action. Layout-only ancestry emits no label paint. Inert ancestry paints and clips the same content without changing the optional state buffer. `test_button_label_layout.c` covers fixed/grow current-frame resizing, all 18 legacy/design sizes in both densities, full semantics, leading/trailing slots, caret, caller byte mutation, grapheme prefixes, malformed shapes, bounded arena failure/recovery, inert/layout-only behavior and the opt-out. The independent `test_button_label_font.c` repeats the matrix with a real caller-opened native FreeType/HarfBuzz font; the portable ZWJ case is separate from the native font's supported combining-mark case. `test_button_label_layout.py` compiles actual WASM, checks Canvas pixels, current-frame widths and ellipsis commands, and dispatches real Chromium mouse and CDP touch contacts. These tests close this label-layout slice; they do not certify the entire Button family or physical device behavior. Standalone Button composition under inherited inert or layout-only ancestry now uses a passive path selected by Core's ordinary-submission phase queries. Inert scopes retain content layout, artwork, clipping and presentation; layout-only scopes retain layout without paint. Neither path registers Button metadata, reduces tooltip state, invokes action/hover notifications, schedules a tooltip wake, or changes any bytes of the caller-owned Button state. Content callbacks still run to compose the visual children; they remain application code. The original state pointer remains borrowed through deferred label paint, so its existing 256-byte diagnostic-prefix cap stays consistent without a temporary stack-state lifetime. The synchronous legacy overflow/explicit-ellipsis branch uses a temporary paint copy whose visible bytes Core copies immediately; no temporary state pointer reaches deferred paint. Passive ID reuse preserves state; a later ordinary frame performs normal ID reconciliation. Explicit disabled/loading options in an ordinary frame retain their existing blockers, hover/tooltip cleanup and loading presentation. Calls outside ordinary submission, including font measurement and prepaint callbacks, perform no standalone Button work. This is a CUI passive composition correctness rule, not an upstream upstream inert-scope parity claim. The focused passive lifecycle fixture compares complete preloaded caller-state bytes across fixed/grow labels, same/changed IDs, direct/inherited ancestry, tooltip open/pending/suppressed states and zero/nonzero frame deltas. It retains strict no-draw assertions for layout-only composition and checks ordinary touch reuse, cancellation, disabled/loading behavior and guarded phases. The native font fixture and independent Chromium WASM fixture extend that evidence to real font measurement and actual hover-opened tooltips, Canvas paint and mouse/CDP touch/keyboard reuse; they do not claim physical touchscreen coverage. Visible inert loading artwork keeps its animation redraw requests. Layout-only loading composes the same-sized icon slot without calling the artwork painter or requesting invisible animation redraw. The existing Core paint-enabled query distinguishes these policies; caller state/deadlines remain unchanged in both. The fixture separately checks Core redraw state after each begin-frame reset and verifies normal loading resumes, rather than inferring wake behavior from pixels. ### Numeric sizing, open presentation, and caret `pixel_size` is an optional finite logical-pixel size in `(0, 4096]`; zero retains legacy/design sizing. Negative, nonfinite, or larger values reject the Button before layout, semantic registration, or callbacks. Numeric sizing follows the pinned source's numeric `Size` branch: horizontal padding is 20% of the size, leading/trailing artwork is 75%, normal text uses the theme's base font, and the content gap uses the medium gap. A normal button has intrinsic content height; an icon-only button defaults to a square of `pixel_size` except Link/Text. Compact mode does not change numeric padding. Link and Text still have no horizontal padding. Numeric sizing takes precedence over legacy/design metrics. Explicit `height`, `font_size`, and `icon_size` then override their respective metrics; `width` retains its existing FIT/grow/fixed behavior. Numeric dimensions are literal logical pixels, independent of density, while base text, medium gap, and medium caret follow theme density. Raster artwork reserves its rounded-up pixel extent; the existing Icon resource capacity and validity rules still apply. This bounded API does not promise successful artwork allocation for every large valid size. Joined ButtonGroup children retain their own numeric sizing and `open` options when group legacy/design/style inheritance is applied. `open` selects active presentation without changing checked/value semantics, selection, callbacks, focus, or managing a menu. It is independent of `selected` and `toggled`. The dropdown caret uses normal foreground at 75% alpha even when hover, press, open, disabled, or selected changes the label palette. Outline and custom normal foregrounds are respected; loading and ancestor opacity still compose over the whole control. Numeric sizing uses the medium caret size, independent of numeric or explicitly overridden leading artwork size. This slice implements those three documented contracts, not complete Button family or platform parity. Its focused tests cover numeric precedence and geometry across all 18 legacy/design sizes and two densities, normal/compact/icon-only layout, explicit dimensions, custom/outline caret tint, disabled/loading paint, and invalid numeric domains. A real Noto font fixture and Chromium WASM fixture exercise the same implementation; Chromium input evidence is not physical device validation. Existing constrained-label and passive lifecycle fixtures remain separate regression gates. The numeric formulas come from pinned `button/button.rs` lines 615–619 and 662–670, `sizing.rs` lines 337–343, and `select.rs` lines 59–67 at upstream commit `87d10ae5e1299d1be18670a37570c5402f952e34`. Numeric Link/Text normal and icon-only buttons use intrinsic height and width, matching the source no-padding branch; explicit caller dimensions still win. The zero numeric default preserves CUI's established legacy icon-only sizing. ### Event-aware click callbacks `on_click_event` receives one `cui_button_click_event` for every accepted activation, in frame input order. The legacy `on_click` runs first for each event when both are present, using the same `action_user`. Either callback can be used alone. `cui_button_ex` continues to return one boolean indicating that at least one activation was accepted; the callbacks preserve each individual event. The payload contains the stable target ID, successful frame sequence, event index and event type. Pointer activations include release coordinates in Core logical pixels, pointer type/button/contact/device, release modifiers, and click count (an unspecified zero normalizes to one). Keyboard activations carry the accepted key and modifier bits, without a fabricated pointer position. Accessibility activations have a distinct origin. Modifier bits for keyboard or touch are a CUI extension: the pinned source ClickEvent helper reports no such modifiers. This is an accepted-event snapshot, not a full source MouseClickEvent with down and up samples, keyboard hitbox, first-mouse or touch long-press data. The callback pointer is borrowed only until that callback returns. The structure contains no borrowed pointers, so copying the value retains it safely across frames or context destruction. `event_index` identifies that dispatched frame, not a future queue entry; `frame_sequence` is scoped to context lifetime and its existing wrap boundary. The callback must not end/reenter a frame or overwrite an active Group workspace. Callback registration and descriptor fields are snapshots; controlled model changes retain their existing semantics. Disabled, loading, cancelled and passive inert/layout-only submissions produce no callback. Repeated key events rejected by Core produce no callback. In a styled ButtonGroup, child legacy and event callbacks both dispatch when the group has no `on_change`. When `on_change` is present it overrides both child callbacks, including the existing pointer-only/default or ALL_ACTIVATIONS policy. The Base optional child event-index hook runs at that same dispatch point, after legacy, and `result.callbacks` counts each actual callback invocation. Cooperative `cui_consume_event` during the legacy notification cannot erase the new notification for the already accepted event. The event-aware callback returns `void`; it does not promise upstream capture/bubble propagation or restore a consumed event. The separate capture/propagation proposal records the remaining source contracts in `validation/button-click-capture-next33.md`. ```c struct button_model { unsigned clicks; cui_button_click_event last_click; }; static void button_clicked(void *user, const cui_button_click_event *event) { struct button_model *model = user; model->last_click = *event; model->clicks++; } bool draw_event_button(cui_context *ui, const cui_theme *theme, struct button_model *model) { return cui_button_ex(ui, 100, theme, cui_string("Open"), (cui_button_options){.on_click_event = button_clicked, .action_user = model}); } ``` The focused unit fixture verifies same-frame multiplicity and order, release metadata, repeat/cancel/current-disabled rejection, cross-frame touch identity, copy lifetime, accessibility, Group override and legacy-then-event order. The real Noto native fixture uses that same implementation. Chromium WASM uses actual mouse/keyboard/CDP touch input, modifiers, cancellation, passive rejection and joined Group behavior; it is not evidence of physical OS/device input. --- ## ButtonGroup Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BUTTON_GROUP.md # ButtonGroup ButtonGroup composes direct Button children into a joined horizontal or vertical collection. It is distinct from ToggleGroup. The Base API depends only on Core; `cui_button_group_ex` supplies styled Button paint, icons, slots, hover/focus states and inherited sizing. The caller owns a Boolean selection array, stable nonzero child IDs, and a zero-initialized workspace. Keep these alive through submission. Allocate the bounded workspace once, rather than on a small thread stack; it supports at most 256 direct children and performs no heap allocation. On the tested 64-bit build the Base workspace is 18,016 bytes and the styled workspace is 212,584 bytes; sizes vary with ABI. Labels, icons, content callbacks and optional Button states retain their existing borrowed lifetimes. Do not reuse a workspace, submit another frame, or mutate descriptors/theme/Button states from its callbacks. Selection callbacks may update the selection array. Descriptor and theme snapshots prevent descriptor changes from affecting later events in that submission. ```c #include #include #include typedef struct { bool selected[3]; cui_button_group_style_workspace *workspace; } app; static void select_requested(void *user, const cui_button_group_request *request) { app *a = user; memset(a->selected, 0, sizeof a->selected); for (size_t i = 0; i < request->selected_count; ++i) a->selected[request->selected_indices[i]] = true; } static bool compose_group(cui_context *ui, const cui_theme *theme, app *a) { cui_button_group_styled_item items[] = { {.id = 101, .label = {"Day", 3}}, {.id = 102, .label = {"Week", 4}}, {.id = 103, .label = {"Month", 5}}, }; return cui_button_group_ex(ui, 100, theme, items, a->selected, 3, a->workspace, (cui_button_group_style_options){ .behavior = {.on_change = select_requested, .change_user = a}, .override_variant = true, .variant = CUI_BUTTON_OUTLINE, }, NULL); } /* Initialize: a.workspace = calloc(1, sizeof *a.workspace); * Compose inside a successful begin_frame/end_frame; free at shutdown. */ ``` A callback is a controlled request. Ignoring it rejects the request. Single selection requests the clicked index, including a repeated click on the selected item. Multiple selection enumerates current selected indices in ascending order, then removes the clicked selected index or appends a newly selected index. Values are reread between accepted events, so two clicks in one frame produce two ordered callbacks and the second sees the first accepted change. Final checked/value semantics and styled selection paint reflect the final model immediately. The Boolean result of standalone Button remains “any accepted activation”; its callback now runs once per accepted event, rather than collapsing queued clicks. The default group callback policy matches the pinned source's pointer-only callback path: mouse and touch taps request selection; keyboard and accessibility activation do not invoke the group handler. `CUI_BUTTON_GROUP_ALL_ACTIVATIONS` explicitly extends this to accepted keyboard/accessibility activations. Key repeat rejection remains Core behavior. If no group handler is installed, each child's own callback remains active, including keyboard activation. With a group handler, child callbacks are replaced. A genuine collection-background pointer activation reports `item_index == SIZE_MAX` and unchanged selection; it never reuses a previous child index. Group disabled, child disabled and child loading states combine with OR. This intentionally avoids the pinned source's builder-order-dependent disabled propagation. Loading retains its busy description and blocks activation. Cancelled input and blocked releases do not dispatch callbacks. Pointer focus, custom cursors, slots, tooltips and Button state options remain per child. Group size/variant overrides take precedence; group compact/outline flags enable those child options. The group owns its direct child boxes, orientation, zero inter-child gap and segmented shape. First/last outer corners survive, internal corners are square, and later children omit the shared left/top border. A single child preserves its own shape. There is no invented roving-focus or mandatory-selection requirement; ordinary Core Tab behavior applies. Under explicit or ancestor inert/layout-only scope, the styled API participates in layout and permitted paint without registering semantics, dispatching selection/hover callbacks, updating tooltip state, focusing or mutating the model or caller Button state. Custom content remains an application layout callback and must avoid side effects, as with ordinary Core layout-only composition. The staged Base API instead rejects suppressed scopes. For Base composition, open the actual group box, call `cui_base_button_group_begin`, open each stable child box and call `cui_base_button_group_item` once, then call `cui_base_button_group_end` before closing the group. Missing/duplicate registration, stale frames, cross-context workspace reuse and reentrant dispatch reject without application callbacks. Partial Core registration is not rolled back; retain ordinary Core error handling. Reset abandoned workspaces before reuse, context recreation, or a complete 64-bit frame-sequence cycle. Core's read-only `cui_event_accepted_activation` reports only activation accepted during current widget registration, in original frame-event order. Raw `cui_event_activation` remains compatible. Current disabled/loading role/modal metadata can invalidate a record; the query does not consume it. `cui_frame_sequence` is nonzero only during ordinary interactive submission and increments on successful begin even with zero delta time. `cui_frame_is_submitting` also admits passive inert/layout-only submission. Both reject measurement, layout resolution, prepaint and outside-frame queries; neither is a clock or persistent context identity. Evidence: focused Core and Base tests cover multiple queued events, controlled accept/reject, source/all activation policies, cancellation, background identity, disabled/loading, snapshot and workspace lifecycle. Styled tests measure joins and text containment across four legacy sizes, fourteen design sizes, two density fonts, both axes and twelve variants, plus passive ancestry. Actual Chromium 1208 runs the WASM Core/components/software painter and genuine mouse/CDP touch events, checking joined pixels, shipped SVG pixels, custom cursor and callback behavior. The SDL Xvfb fixture pushes real SDL events through the adapter and renders native draw commands; it is queued-event evidence, not physical OS/device coverage. These tests do not establish complete Button-family parity, native font coverage at every size, or physical touch-device behavior. --- ## Chart appearance and hover Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CHART_APPEARANCE_HOVER.md # Chart appearance and hover `cui_chart` suppresses new hovered data while the marks appear. Default styled appearance lasts one second with quartic-out reveal; hover becomes eligible when **linear time** reaches completion. An eased float sample that rounds to1 early does not release the gate. Existing `appear_duration` overrides the duration. Manual `reveal_enabled` uses the rendered caller-supplied progress as its completion contract; render the requested progress before composing the chart. A pointer moved onto a valid datum during appearance is remembered in caller-owned state. It becomes eligible on completion without a second move event. Moving outside before completion or making the chart noninteractive cancels this pending hover. Restarting appearance supplies no live datum but preserves the previous tooltip/mark presentation through its existing exit fade; once that fade finishes it disappears completely. Disabled appearance and owner/Core reduced-motion completion permit hover immediately. Noninteractive charts still animate their marks. Keep `cui_chart_state` zero initialized with caller-owned pixel storage and `hovered=SIZE_MAX`, as in the existing API. The appended private `appear_hover_pending` field needs no application updates. Pure `cui_chart_hit_test`/`cui_chart_update_hover` remain geometry helpers; the styled widget applies the gate. Borrowed data, callbacks and pixel lifetimes retain their existing requirements. This fix follows pinned upstream kit/Base0.7.1 commit `87d10ae5e1299d1be18670a37570c5402f952e34`, `crates/base/src/plot/element.rs::prepaint`: appearance is resolved before live tooltip state; appearing plots supply no live datum to retained hover tracking. It does not add automatic current-frame layout/occlusion tracking. Chart pointer coordinates still use retained bounds, and no native screen-reader or OS long-press parity is claimed. The native regression uses actual pointer events and checks tooltip title draw commands. It covers incomplete/completed reveal, early float rounding, stationary resume, restart fade retention, move-out cancellation, settled redraw, noninteractive appearance, disabled appearance, owner/Core reduced motion and explicit progress. The browser test uses the real WASM gallery and Chromium mouse input: hover is absent during appearance, resumes with a stationary pointer after completion, settles on exit and works immediately with reduced motion. Browser touch/OS long-press behavior is outside this test. Validation on base `3f4e108`: baseline component linked against the current native test reports `hovered=0 tooltip_draw=1 reveal=0.937500` and fails the gate assertion. Fixed strict-warning native build succeeds; CTest106/107 passes, with the sole failure `distribution` reporting stale `dist/cui_chart.h` (integrator regeneration). Updated Chart regression passes ASAN/UBSAN with leak detection. Actual WASM Chromium headless-shell1208 browser test passes. Evidence logs are `/home/matteo/.cache/cui-validation/chart-hover-next23-baseline-proof.log` and `chart-hover-next23-ready-{build,ctest,asan,browser}.log` in that directory. --- ## Radar custom-label tooltip title Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CHART_RADAR_TOOLTIP_TITLE.md # Radar custom-label tooltip title Opt into `CUI_CHART_RADAR_TOOLTIP_TITLE_SOURCE_LABEL` through the appended `cui_chart_options.radar_tooltip_title_mode` field. This follows the pinned upstream component 0.7.1 `RadarLabel::Element` rule: paired custom dimension label measure/paint callbacks supply no automatic tooltip title. The series rows and hover marks still render. Plain text labels retain their datum-label fallback title. ```c options.kind = CUI_CHART_RADAR; options.radar_tooltip_title_mode = CUI_CHART_RADAR_TOOLTIP_TITLE_SOURCE_LABEL; options.radar_label_measure = measure_dimension; options.radar_label_paint = paint_dimension; ``` Zero is `CUI_CHART_RADAR_TOOLTIP_TITLE_LEGACY` and preserves the existing fallback. The source policy affects only Radar and only when both custom label callbacks are set. An explicit `tooltip_title` callback overrides the fallback, including an empty result that suppresses visible title text under the existing CUI callback contract. Legacy `tooltip_content` retains complete precedence and skips automatic title/row formatter construction. `CURRENT_FRAME` continues to reject legacy layout/measure tooltip callbacks; this option does not permit layout during prepaint. The component resolves the same fallback in legacy composition and current-frame deferred tooltip painting, including retained exit fade. Strings and callback users follow existing caller-owned lifetimes through the frame; no new title data is retained. Invalid enum values and a nonzero policy on another Chart kind are rejected before styled UI/state mutation or Base raster mutation. The option changes tooltip metadata, not raster geometry, and does not add cache-key terms. This is a bounded title fix. It does not provide typed arbitrary tooltip rows, reproduce popover Gaussian shadows, add a keyboard/legend contract, or certify native accessibility announcements. Source `Some(empty_title)` layout presence versus CUI's existing empty string suppression remains an independent typed-content contract. The native test covers legacy/current-frame paths, paired/partial/plain labels, explicit and empty overrides, legacy custom-content precedence/exact callback counts, exit retention/settling, copied options/state, invalid atomicity, and unchanged raster-cache keys. It runs through CTest and the portable WASI runner. The standalone browser check uses Zig 0.16.0 WASM, current-frame immutable pointer snapshots, and actual Chromium canvas text/raster pixels for stationary hover across legacy/source/explicit title toggles; it also runs in the website deployment workflow. --- ## Source point-axis layout Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CHART_SOURCE_POINT_AXIS.md # Source point-axis layout `CUI_CHART_LAYOUT_SOURCE_POINT` is an explicit Line/Area layout mode matching the point-axis geometry in upstream component 0.7.1, pinned at `87d10ae5e1299d1be18670a37570c5402f952e34` (`chart/mod.rs` point-count normalization and `AXIS_GAP`, `crates/base/src/plot/axis.rs` label offsets). Zero-initialized options retain `CUI_CHART_LAYOUT_LEGACY`. ```c cui_chart_options options = { .kind = CUI_CHART_LINE, .data = points, .count = point_count, .width = 320, .height = 180, .layout_mode = CUI_CHART_LAYOUT_SOURCE_POINT, .interaction_mode = CUI_PLOT_INTERACTION_CURRENT_FRAME, }; cui_chart(ui, chart_id, &chart_state, &options, cui_string("Revenue")); ``` Source mode reserves 18 raster pixels for the x axis, places the x-label top at the axis plus 6 pixels, and uses `max(point_count, count)` point slots. A zero point count therefore uses the data length; a smaller requested count also uses the data length. `hide_x_axis` removes the gutter. The independent legacy `hide_axes` switch still suppresses composition labels without changing raster geometry. The shared query `cui_chart_point_axis_layout` reports the effective slots and gutter without reading or retaining data arrays; it checks kind, enum, count (1–4096), and point-count capacity (at most 1,000,000), leaving both outputs untouched on failure. Output storage must be disjoint. Raster point positions, hit selection, grid/tick domain positions, measured y-axis gutter, hover crosshair endpoint, x-label placement, and source cache fingerprints consume this geometry. Raster pixels are scaled into `logical_width`/`logical_height` when supplied; label typography continues to use the existing 10-unit host font contract. Arbitrary custom label content is not introduced. Legacy mode keeps the 20-pixel gutter and existing label offsets. Render and point-coordinate APIs continue to reject a nonzero point count smaller than the data length. The historically permissive raw legacy hit-test geometry remains unchanged. Source mode is rejected for other chart kinds and invalid enums are rejected before styled UI/state changes. Base render validation continues to preserve raster/state on invalid options. Source cache keys use effective slot counts, so equivalent normalized requests reuse a frame; legacy zero-mode cache keys retain their existing structure. This slice does not certify complete Chart parity. Typed source tooltip composition, source popover styling/shadows, custom Radar-title suppression, and accepted mobile long-press phase/prevention remain separate gaps. Legend composition belongs to the source story rather than a Chart legend API; this mode adds no keyboard or legend API. Validation: `tests/unit/test_chart_source_point_axis.c` covers coordinates, normalized selection/cache reuse, source versus legacy labels/crosshair endpoints, invalid output atomicity, and raw legacy hit compatibility. `tests/web/test_chart_source_point_axis.py` builds pinned Zig 0.16.0 WASM and verifies actual Chromium canvas raster pixels for source/legacy and expanded slots. Register the new unit executable against `cui` in the integration CMake tree; this worker does not edit global registrations or regenerate distributions. Browser proof concerns raster geometry, not native accessibility certification. --- ## Opt-in Chart tooltip appearance Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CHART_TOOLTIP_APPEARANCE.md # Opt-in Chart tooltip appearance `cui_chart_options.tooltip_style` applies explicit typography, spacing, colors and boxed/bare placement to automatic and copied typed tooltip content. A NULL pointer preserves existing tooltip behavior, including the old border. Automatic opt-in content uses the same bounded copying row arena as typed content: 32 rows, 4096 aggregate bytes, 1024 bytes per string, valid UTF-8. The style is borrowed only during synchronous composition and copied by value into current-frame prepaint; the callback rebinds to its copied payload, so caller stack storage can disappear after `cui_chart` returns. Caller data, callback users and existing raster buffers retain their existing borrowed lifetimes. ```c cui_theme theme = cui_theme_light(); cui_chart_tooltip_style tooltip; float rem_pixels = 16; /* host's current rem projection */ /* upstream's default inherited relative line height, resolved for compact text. * Supply the actual resolved value when the host overrides line height. */ float inherited_line_pixels = roundf(.75f * rem_pixels * 1.618034f); if (cui_chart_tooltip_style_project(&theme, rem_pixels, inherited_line_pixels, &tooltip)) { options.tooltip_style = &tooltip; options.interaction_mode = CUI_PLOT_INTERACTION_CURRENT_FRAME; cui_chart(ui, chart_id, &state, &options, cui_string("Revenue")); } ``` The checked projection sets compact font .75rem, vertical gap .25rem, label/value gap .75rem, swatch gap .375rem, swatch size and padding .5rem. Minimum width stays 150px and Chart cursor gap 8px. Background/foreground use Theme.popover/popover_foreground; CUI Theme.muted supplies the muted foreground role. Surface radius uses Theme.radius; swatch radius is half. The sigma-zero ring shadow uses Theme.text (source foreground) RGB with alpha .1, quantized to 26/255; source projection replaces its inherited alpha. It is distinct from popover foreground. Transparent colors are intentional values. Font and line height must be positive; other dimensions may be zero. Enum and finite bounded dimensions, including minimum viable spacing, are validated before interaction/state mutation. Factory failure leaves output untouched. The source's `text_xs` sets font size without changing inherited line height. Pinned upstream-pre 0.3.8 defaults to a font-relative 1.618034 line height and rounds its resolved pixel value; Component Root sets rem size to Theme.font_size. The factory takes a resolved inherited line height explicitly instead of assuming glyph height equals font size. Measured glyph widths determine fitting; inherited line boxes determine vertical rhythm, with measured glyphs centered inside those boxes. A row reserves max(line height,swatch size) when any row has a swatch. Plain rows among swatched rows keep the empty slot; transparent swatches also keep it. Gaps appear only between existing title/rows, including an empty-present title. Values share the right edge. Existing per-value color overrides remain authoritative. BOXED (zero enum) uses the projected surface and midpoint cursor flips independently on both axes. BARE uses the full plot extent at its origin, removes padding/minimum/surface/cursor anchoring, stretches row value alignment to the plot edge, and preserves the tooltip's deferred fade. Crosshairs and marks stay local. BARE currently supports bounded single-line structured content: intrinsic width exceeding the plot width fails rather than inventing wrapping. Source arbitrary element wrapping remains a separate gap. Explicit CURRENT_FRAME follows immutable current bounds and pointer visibility under stationary scroll/resize. A style alone does not change AUTO's existing manual-pointer contract. Explicit LEGACY continues to use retained origin/manual pointer information; it does not gain current-frame geometry. Legacy custom `tooltip_content`/`tooltip_measure` remains supported, receives the projected content box, and must apply the host child font/line height itself. Custom measured sizes must be finite/nonnegative/bounded. Without a custom measurement the legacy content height remains a bounded 48px fallback. Arbitrary layout callbacks are still rejected by CURRENT_FRAME. Invalid style returns false before output or owner mutation. Legacy copied structured content and custom measurement are staged before layout/semantics. Oversized measured content fails without publishing owner state. Current-frame measurement/emission failure rolls back that owner's paint output and state, reporting Core layout error; layout clip commands can remain. Host callback/measurement side effects, motion frame requests, borrowed raster writes and later global end-frame failures remain outside the existing transaction scope. Clear a reported Core error before retrying corrected input. Source popovers have an outside translucent foreground ring and two Gaussian shadow layers. The consumed `ring_color` paints a filled rounded shadow before the surface in both boxed paths: bounds expanded 1px, ORIGINAL radius, sigma 0. Spread changes bounds, not corner radii, matching pinned Window.paint_drop_shadows. The source shadow also fills beneath the surface; transparent background or hover progress exposes that contribution. Legacy emits a separate bounded portal before the surface; current-frame emits the equivalent deferred filled rectangle, without Core input/layout mutation. BARE emits neither ring nor surface. Headless tests prove geometry, order, role distinction and alpha through ancestor opacity; the WASM probe proves outside/inside pixel compositing, including clipped half-opacity owners, translucent surfaces and controlled hover progress. A corner probe distinguishes the original radius from the former radius+1 geometry. This establishes source shadow geometry/compositing behavior, not exact native upstream shader/antialias pixel identity. Gaussian sigma 3/2 falloff remains a rendering gap; there are no shadow fields or approximations. Arbitrary current-frame interactive layout, source wrapping and accepted mobile long-press delivery/prevention also remain incomplete. This API does not establish full Chart or native accessibility parity. `tests/unit/test_chart_tooltip_appearance.c` checks source projection at three rem sizes, inherited line boxes independent of glyph height, all seven automatic Chart kinds, both consumers and appearances, empty-present titles, mixed/transparent/plain slots, larger swatches/zero gaps, placement flips, clipping/opacity, stationary current bounds, copied storage/relocated owners, malformed styles/oversized content rollback, ring geometry/order/theme alpha, custom legacy measurement and finite exit. `tests/web/test_chart_tooltip_appearance.py` compiles a standalone pinned Zig 0.16 WASM probe and checks actual Chromium canvas pixels for all eight automatic/typed × boxed/bare × consumer combinations plus stationary owner move/resize and outside/inside ring pixels with clipping/opacity. Its custom proof renderer does not certify all adapter styling or native platform behavior. Worker validation: strict warning build and scoped native test passed; GCC ASAN/UBSAN/leaks with runtime use-after-return detection passed; real Chromium 1208 WASM probe passed. Full CTest on isolated f8b7f43 completed 125/126, only stale generated distribution failed. Integrator registers the new native/browser tests and regenerates distributions; worker changes no global registrations. A focused correction replaces the former outline/border approximation: the pre-fix native regression against093e927 fails because the source requires filled-under-surface shadow geometry with unchanged radii. Full baseline CTest still reports125/126, only stale distribution. Gaussian layers are separate remaining work. In the website Chart preview, choose Classic tooltip, Popover tooltip or Bare tooltip. Combine the choice with Custom tooltip rows to compare automatic and callback content. The gallery resolves rem from the current theme font size and supplies the inherited compact line height; other applications can supply their own resolved metrics. --- ## Copied Chart tooltip content Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CHART_TYPED_TOOLTIP.md # Copied Chart tooltip content Append `tooltip_build` and `tooltip_build_user` to opt into structured tooltip content. The builder copies title, label, and value bytes synchronously; local formatting buffers can be changed or leave scope immediately after a setter returns. No builder or string pointers escape into owner state. ```c #include "cui/cui_chart.h" #include static bool tooltip(const cui_chart_tooltip_info *info, cui_chart_tooltip_builder *builder, void *user) { (void)user; char value[48]; int written = snprintf(value, sizeof value, "%.0f", info->values[0]); if (written < 0 || (size_t)written >= sizeof value) return false; if (info->has_fallback_title && !cui_chart_tooltip_set_title(builder, info->fallback_title)) return false; cui_chart_tooltip_row row = { .has_swatch = true, .swatch = info->series_colors[0], .label = info->series_labels[0], .value = {value, (size_t)written}, }; if (!cui_chart_tooltip_add_row(builder, &row)) return false; return cui_chart_tooltip_add_row(builder, &(cui_chart_tooltip_row){ .label = {"Total", 5}, .value = {value, (size_t)written}, }); } /* options.tooltip_build = tooltip; */ ``` Choose **Custom tooltip rows** in the Chart gallery to see a swatched series row and a plain reporting-period row. The application callback receives real values and fills its rows with these copying helpers. Configure `options.tooltip_build` before submitting the Chart; retain any `tooltip_build_user` data through frame completion. This callback describes paint content and should not perform application actions or change the UI during prepaint. The immutable callback info contains Chart kind, retained visual datum/index, at most eight raw values (four Open/High/Low/Close values for candles), default series labels/colors, and optional fallback title. Sankey supplies current retained throughput. Pie supplies raw values rather than formatted share percentages; callers wanting ratios have their caller-owned data/user context. Automatic title/value/label/value-color/pie formatter callbacks are skipped when the builder is selected. The builder supplies the complete title/row content. `tooltip_content` or `tooltip_measure` together with a builder is rejected before mutation; existing custom layout callbacks retain their original behavior when no builder is supplied. `AUTO` plus the new builder selects current-frame pointer/snapshot painting. Existing zero/no-builder AUTO behavior stays unchanged. Explicit `LEGACY` preserves the legacy manual/event pointer path and stages a local next-state, the copied builder, and the shared measured row layout before layout/semantic output. Bounds tracking targets the persistent original owner state. Current-frame builds once during prepaint and uses immutable current bounds, hover/occlusion state, and fade progress. Legacy builds once during composition. Both rebuild while retained exit content is visible and stop when the hover channel settles. A row's `has_swatch` is presence, including an alpha-zero color. If any row has a swatch, all labels reserve the same 14-unit slot (8 swatch plus 6 gap); a plain row leaves that slot empty. With only plain rows, labels start at the tooltip padding. Values align to one shared right edge; `has_value_color` selects an explicit color, including transparent, otherwise foreground. Calling `set_title` with an empty string creates a present title row and retains its space. Without a setter, there is no title row. An empty builder renders the existing empty padded box. Limits are 32 rows, 4096 aggregate copied bytes, and 1024 bytes per string. Replacing a title still consumes copied byte capacity. Strings must be valid UTF-8; NULL data is allowed only for length zero. NULL rows, malformed UTF-8, over-capacity strings/rows, or a failed setter/add-row latch a failure. Ignoring a returned false cannot publish partial content. Callback false also rejects the whole builder. Legacy builder failure leaves caller state and component layout/semantic output unchanged. A failed current-frame callback rolls back the complete owner paint output and does not commit next-state. Core reports a current-frame callback failure as `CUI_ERROR_LAYOUT`; clear the reported error before retrying corrected input. Writer command-budget and copied-text limits remain bounded. Legacy commits after successful synchronous emissions. Frame requests already generated while stepping appearance/hover, borrowed pixel-buffer writes, callback/measurement host side effects, and later global `end_frame` capacity/layout failures are outside the component's transactional scope; they cannot be restored by this API. Data, callbacks, and user remain caller-owned and must be live through composition/prepaint and renderer completion as required by existing Chart contracts. Callback info/builder are synchronous-only; callbacks must not retain them or perform layout/input/semantic work during prepaint. This slice uses the existing tooltip box styling: font 11, radius 4, minimum width 150, padding/cursor gap 8, row height 16, title step 18, label/value gap 12, background/foreground/grid border, and muted labels at .7 foreground alpha. It adds no speculative theme/style API and does not claim source popover style parity. Pinned 0.7.1 source uses popover colors/radius, compact rem typography, optional structured/freeform content, unboxed appearance, and an outside ring with Gaussian shadows; those contracts remain separate. Arbitrary custom layout/content in current-frame painting and accepted mobile long-press phase/prevention also remain gaps. This is no full Chart-family or native accessibility certification. Native coverage checks raw callback values/labels/colors for all seven Chart kinds, copied overwritten stack buffers, plain/mixed/transparent slots, value alignment/color, title-only/empty-present/empty content, exact row/byte limits, invalid UTF-8 and latched failures, formatter precedence, both consumers, owner relocation and persistent bounds, unknown pointer, deferred clipping/ancestor opacity/modal exclusion, and finite retained exit. The standalone Zig 0.16.0 WASM test checks actual Chromium canvas text/raster pixels for both consumers, copied rows, failed-owner rollback, and stationary pointer under controlled owner move/resize. It is a custom proof renderer, not adapter-wide styling certification. GCC ASAN/UBSAN/leaks with the runtime use-after-return option passed; a separate Clang always-use-after-return attempt was unavailable because no Clang executable was installed. The headless test runs through CTest and the portable WASI runner; the standalone pixel check also runs in the website deployment workflow. --- ## Checkbox source contracts Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CHECKBOX_BEHAVIOR.md # Checkbox source contracts This audit uses upstream kit v0.7.1, commit `87d10ae5e1299d1be18670a37570c5402f952e34`, from the frozen checkout described in [upstream-baseline.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/upstream-baseline.md). It reads actual Base and Styled implementations and their tests, not just the existing parity ledger. | Frozen source | SHA-256 | | --- | --- | | `crates/base/src/checkbox.rs` | `faa48acd7e1243ff661b542d753a6aa1327f76058837edb4cc00b3f469409883` | | `crates/component/src/checkbox.rs` | `45cb50dac2d8194cc958d1776fcc2003cc03af132e3fde94289ff66e7c054e1e` | The source distinguishes an unstyled Base primitive from the Styled facade. Base owns controlled checked/unchecked/indeterminate requests, pointer focus, keyboard activation, roles, tab traversal and accessibility metadata. Its separate indicator part projects checked/mixed/disabled styles over an instance style and renders arbitrary children. Styled composes that primitive with an indicator, label/custom content, sizes, spring mark, tooltip and focus ring; pointer presses explicitly preserve focus. Disabled activation is inert and can reach its parent. ## Shipped C mapping | Contract | C API and evidence | | --- | --- | | Controlled state requests with activation metadata | `cui_base_check_ex`, `cui_check_options.on_change`, copied `cui_activation_snapshot` | | Mixed activation becomes checked | `cui_base_check_ex`; semantic numeric value retains `CUI_CHECK_MIXED` | | Base pointer focus; Styled pointer-focus suppression | Base default versus `cui_checkbox_source` | | Signed focus order and traversal omission | `tab_index`, `skip_tab`; keyboard/programmatic focus remains available | | Role override and accessible label | `custom_role`/`role`; Styled `accessibility_label` replaces only semantic name | | Unstyled indicator and state refinement | `cui_base_check_indicator`, `cui_check_box_style`, `cui_check_box_styles` | | Styled root/indicator/text refinement | `cui_checkbox_styles`, refining initialized `cui_checkbox_paint` | | Arbitrary icon/indicator presentation | `indicator` callback receives size, state, disabled flag and spring progress | | Label and application children | Existing `content` callback; bounded source content clips and uses 1.25-line-height labels | | Check/mixed mark, spring and tooltip | Existing caller-owned `cui_checkbox_state`; reduced-motion and wake contracts retained | | Sizes | Four frozen control metrics plus existing fourteen CUI design sizes, at logical densities 1 and 1.5 | The additive source facade is the recommended entry point for the frozen controlled/pointer-focus behavior. Existing `cui_checkbox`, `cui_checkbox_ex`, `cui_base_checkbox` and `cui_base_check` keep their legacy direct-mutation and pointer-focus defaults. `cui_checkbox_ex` can also use the new callback, style and indicator seams. Radio aliases ignore Checkbox-only fields. ## Controlled example ```c #include "cui/cui_components.h" typedef struct { cui_check_state value; cui_checkbox_state motion; bool permit_change; } preferences; static void requested(void *user, cui_check_state value, const cui_activation_snapshot *event) { preferences *app = user; /* event contains copied keyboard/pointer/modifier evidence for this request. */ (void)event; if (app->permit_change) app->value = value; /* Reject by leaving the owner unchanged. */ } static void scene(cui_context *ui, const cui_theme *theme, preferences *app) { cui_checkbox_source(ui, 100, theme, cui_string("Receive updates"), &app->value, (cui_checkbox_options){.on_change = requested, .change_user = app, .state = &app->motion, .width = 220, .tab_index = 2}); } ``` Call inside an active frame. Keep one motion state per stable ID. Every accepted activation emits a request; multiple accepted events in one frame each receive the next value computed from that submission's original value. Callback presence means the helper never writes the owner. The owner can accept synchronously so this frame's paint and semantic state reflect its committed value. A source facade without a callback is read-only. Base callers can select the same behavior with `controlled=true`; the zero-default Base extended options retain direct mutation when no callback is supplied. The callback's event pointer is valid only during the call. Copy the snapshot if it must outlive the callback. Frame/event indices identify events within the originating context; they are not global IDs. No host event data is fabricated. Disabled, inert and layout-only submissions do not dispatch accepted callbacks. The Base helper draws nothing: put it inside your own same-ID box and compose children yourself. ## Styles and indicator slots Styled style callbacks refine initialized defaults in this order: `instance`, `checked` **or** `mixed`, then `disabled`. Each receives the current committed state. Modify `paint.root`, `paint.indicator`, glyph/text colors, label font size, line height or `label_style`. Keep style callbacks confined to refinement; use existing hover/focus queries for state-dependent adjustments, and put UI content in `content`/`indicator` callbacks. Those content callbacks run during submission and must obey the ordinary inert/layout-only contract; do not perform application side effects there. A custom `indicator` replaces built-in check/dash painting, while preserving the indicator box and semantics on the root. Its info includes checked/mixed spring progress for animated custom icons. Use caller-owned immutable icon resources through renderer completion. Without an override, the existing built-in marks remain in use. Base applications use `cui_check_box_style` to project styles onto their own root box, and `cui_base_check_indicator` for the noninteractive child part; it creates no redundant accessibility control. CUI box/text fields are the supported style vocabulary. These seams do not claim byte-for-byte equivalence to upstream's entire inherited `StyleRefinement` language. Platform-specific focus handles map to stable CUI IDs and explicit focus scopes; there is no Rust/OS focus-handle object in the portable API. Native accessibility transport depends on the host adapter and is not proved by semantic snapshots. ## Existing motion, labels and tooltip contracts A zero-initialized `cui_checkbox_state` snaps to the initial value. Keep one state per stable Checkbox ID through `cui_end_frame`; it allocates nothing and needs no cleanup. Reusing it for a different ID resets motion and tooltip. Checked and mixed channels crossfade and reverse from current progress/velocity using `theme.spring_control` response, damping, epsilon and travel settings. Painted alpha clamps underdamped overshoot. Response zero, travel false, Core reduced motion or `options.reduced_motion` snaps immediately; logical selection never waits for paint. A NULL state retains immediate marks. `state.next_wake_seconds` is an absolute Core frame deadline while spring motion or a delayed tooltip is active; zero is quiescent. The component also invalidates Core. Honor deadlines alongside input redraws. Nonfinite or exceptionally large Core clocks do not produce invalid deadlines. Positive `width` bounds the fit-height label column while reserving indicator and gap space. Text wraps; custom `content` follows the label. Give children intrinsic height or an intentional constraint. Oversized words need enough width or an appropriate scroll/clipping ancestor; no ellipsis or arbitrary word-breaking is introduced. Tooltip text requires motion state and a valid `tooltip_options.viewport`. The component supplies trigger, frame delta and disabled state and delegates placement, delay, keyboard focus and Escape behavior to the existing Tooltip. Targeted capture cancellation suppresses it until hover/focus leaves. Removing text clears tooltip state. Legacy touch activation can focus and reveal help; the source facade preserves focus on touch/pointer activation, so use hover or keyboard focus for its tooltip. Choose dimensions for the supplied tooltip text; its existing clipping contract remains in force. ```c static cui_checkbox_state motion; static cui_check_state checked; void preferences(cui_context *ui, const cui_theme *theme, cui_rect viewport) { bool changed = cui_checkbox_ex(ui, 42, theme, cui_string("Receive updates"), &checked, (cui_checkbox_options){.state = &motion, .width = 240, .tooltip = {"Email notification preferences", 30}, .tooltip_options = {.viewport = viewport, .open_delay = .2f, .close_delay = .1f}}); if (changed) { /* Persist the legacy directly mutated value. */ } } ``` The existing motion fixture also has a real WASM/browser contact proof: `uv run tests/web/test_checkbox_motion.py --chromium /path/to/chrome-headless-shell`. That fixture exercises marks, tooltip/keyboard behavior, sizes and wrapped labels; it is not physical-device or new source-callback verification. ## Tests and current limits `tests/unit/test_checkbox_source.c` checks owner accept/reject/read-only behavior, per-event keyboard requests, mixed state, mouse/touch metadata, touch cancellation, current-frame inert/layout-only suppression, disabled parent activation, Base vs Styled pointer focus, signed tab ordering/omission, role/name/required/invalid semantics, style precedence, actual slot/indicator/root geometry and text sizing. It also exercises all fourteen design sizes at two logical densities. Existing `test_checkbox_motion`, `test_components` and `test_base` continue to check legacy controls and springs/tooltips. Headless evidence uses strict portable C11 warnings and the isolated CTest wrapper. It does not establish full family verification, native accessibility delivery, screenshot equality across renderers, or new current-frame hit-routing guarantees beyond Core's documented previous-region event model. Final manifest status belongs to the integrator after the frozen-source audit and complete acceptance proof. No dependency or upstream runtime is introduced. For AI consumers, use `cui_base.h` and `cui_components.h` as signature authority, this guide as the Base/Styled behavioral distinction, and the generated API index for exact exports. Do not infer controlled callbacks or pointer-focus suppression from the older boolean convenience functions. --- ## Combobox selection notifications Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMBOBOX_EVENTS.md # Combobox selection notifications `cui_base_combobox_events` and `cui_combobox_events` add synchronous selection CHANGE observers to single-selection Combobox. Legacy APIs, query editing, Select, List/Menu and multi-selection retain their behavior. Shared pointer-free payloads come from [selection events](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SELECTION_EVENTS.md); this does not enable bridge typed-selection tags or uniform family coverage. ```c #include static void selected_changed(void *user, const cui_selection_change *change) { cui_id *last_seen = user; *last_seen = change->value; } /* During active composition; query, scratch, selection and popup belong to app. */ static cui_combobox_event_result search(cui_context *ui, const cui_theme *theme, cui_edit *query, const cui_choice_item *items, size_t count, cui_choice_item *scratch, size_t capacity, cui_id *selected, cui_choice_popup *popup, cui_id *last_seen) { return cui_combobox_events(ui, 2, theme, cui_string("Find account"), query, items, count, scratch, capacity, selected, popup, (cui_choice_popup_options){.viewport = {0, 0, 640, 480}}, (cui_selection_handler){selected_changed, last_seen}); } ``` Initialize popup once with `cui_choice_popup_init` and a stable nonzero popup ID. The Base entry point matches `cui_base_combobox` arguments followed by a handler; the Styled entry point likewise appends a handler to `cui_combobox`. Base still draws nothing and handles query/Enter reduction; Styled adds query/option rendering and popup-list selection. The caller supplies a single-line editor and filtered scratch capacity at least equal to item count. Existing matching is ASCII case-insensitive substring search, byte-exact otherwise. Committed IDs remain stable under filtering and are not replaced by array indices. `cui_combobox_event_result.legacy` preserves the complete old `changed/query_changed/scrolled/matching_count/error` result. `.events` contains preflight `valid`, active `submitted`, actual observer invocation `change_count`, and `count_overflow`. Counts saturate at `SIZE_MAX` while dispatch continues. Missing observer preserves ordinary editing/selection and reports zero callbacks. Disabled controls can submit but emit no selection notifications; inert/layout-only ancestry emits none. Scratch/argument errors remain explicit and do not report observer calls; a valid preflight is not a promise against later editing/render errors. The callback reports an applied selection transition, not an owner-rejectable request. `cui_selection_change` copies actual `previous/value`, attempted `item`, common metadata and ACTIVATION reason. Here ACTIVATION describes semantic option confirmation, including Enter. Metadata kind is **CHANGE**, not ACTIVATE, and the reason does not imply a Core activation snapshot. Query-only edits, cursor navigation, external owner assignments, unmatched Enter, and confirming the existing value emit no selection CHANGE. Query edits have their own `.legacy.query_changed`; no query/SUBMIT event is inferred from selection. Base first reduces query editing/filtering and Enter confirmation; Styled then reduces popup-list option input if still open. Observers run synchronously at the existing selection-write points, without sorting, replay or deferred delivery. Event indices can decrease across those phases: a later-index Enter transition can precede an earlier-index captured pointer release. Use indices as truthful input identity, not a promise of globally sorted callback delivery. Preserve existing text-before-Enter versus Enter-before-text behavior and the complete list pass before popup close. Legacy `.changed` may collapse/overwrite transitions in its existing paths; it is not a callback count or proof of final owner acceptance. An observer may update the external selection; later events and final painting/results see that owner state according to the existing pointer-owned contract. Such writes do not recursively synthesize another notification. Each payload is frozen before the observer runs. Consuming later input changes later eligibility; no prequeued callback batch overrides consumption. Do not repeat the same side effect from both the callback and aggregate result. `event.target` is the public input ID. Enter's direct key path copies real KEYBOARD/frame/index metadata with **no HAS_ACTIVATION**. The option-list seam copies a genuine accepted snapshot only if Core already makes it available, retaining the actual child `activation.target`; it normally registers option semantics after reduction, so snapshots are absent there too. The fallback records only source proven by the actual event type plus its frame/index. No pointer coordinates, touch snapshot or accessibility activation evidence is fabricated from source alone. See [metadata presence/lifetime conventions](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMPONENT_EVENTS.md). Current Core excludes OPTION from accessibility ACTIVATE support. FOCUS is supported, but focus alone does not synchronize the retained list cursor. This slice preserves those limits and tests explicit focus/navigation rather than claiming successful accessibility option activation. Enabling that capability needs a separate Core review. Handler/user/payload are borrowed through synchronous submission. Pointer-free payload copies survive later frames and context destruction. Keep active item arrays, editor/scratch/popup/selection, callback users and render resources alive through their existing boundaries. Copied handler/options changes affect later calls. Schedule removal/teardown for after submission/frame completion: active context destruction, freeing active state and recursive same-frame submission remain unsupported. No runtime destruction guard, queue, scheduler or request binding is introduced. `tests/unit/test_combobox_events.c` exercises real Base/Styled query and Enter paths, both text/Enter orders, filtered-out committed IDs, same-value confirmation, missing handler, scratch errors, disabled/inert/omitted calls, real pointer/touch input, owner writes/later consumption, existing accessibility boundaries, phase-order evidence and copied lifetime. The mixed-phase case uses a genuine cross-frame option pointer capture, restores input focus and the caller-owned active cursor, then queues release/Enter/text; it checks callback indices1 then0 without fabricated snapshots. Legacy choice and Select suites remain compatibility checks. Run native tests only through the invisible wrapper: ```sh python scripts/test_local.py --build-dir build -- -R '^(combobox_events|select_events|choice)$' ``` [Private plumbing checkpoint](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMBOBOX_EVENTS_SLICE.md) records the implementation boundary. Controlled selection rejection, query/edit events, confirmation/lifecycle events, multi-selection, foreign request hooks and parity promotion remain deferred. --- ## Command observers Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMMAND_EVENTS.md # Command observers Include `cui/cui_command_events.h`. The additive `cui_command_rebuild_events`, `cui_command_select_events`, `cui_command_move_events` and `cui_command_confirm_events` accept the existing arguments, an explicit nonzero metadata target after state, and a `cui_command_event_handler`. Existing functions and public layouts remain unchanged. Base and Styled submission are available; foreign bindings remain separate work. ```c static void confirmed(void *user, const cui_command_activation *event) { cui_command_index *saved = user; *saved = event->value; /* Copy the confirmed path, not later selected state. */ } /* state/options/selected_path are application-owned. */ /* cui_command_confirm_events(state, 90, options, * (cui_command_event_handler){.on_activate=confirmed,.user=&selected_path}); */ ``` `result.control` is the exact legacy bool result: false can mean no change or invalid input, and does not imply rollback. Zero target rejects before any reducer work. Counts record actual synchronous observer calls, saturating with `count_overflow`; absent callbacks ignore user and preserve reducer behavior. Base metadata is PROGRAMMATIC with the supplied target, without invented context, frame, index or activation evidence, even when the application calls it in a UI frame. Section/row indices are operation-time paths, not stable item IDs. Selection CHANGE follows each successful select/move transition or changed-query rebuild that installs a different eligible path. `has_previous` establishes whether `previous` exists. Rebuilds with `query_changed=false` remain silent even if model replacement removes/changes selection. Selection loss emits no new event. Explicit Base `query_changed=true` can notify on initialization, unlike Styled's initial false flag; it need not mean different query bytes. Direct select/move retain the legacy policy of ignoring options.disabled/loading. Confirm respects options/item disabled, but loading and missing action/hooks do not suppress it. Rebuild installs state and freezes all selected-path snapshots, then invokes the new query observer **before either legacy hook**. When all are eligible the order is new query → old select → new selection → old query. The old hooks retain their relative order and timing. Query observation requires changed && searchable and borrows the original untrimmed raw query view only during callback. This explicit ordering exception lets old select/query hooks replace/reallocate query storage without adding a dangling-view read afterward. The old select hook retains only its pre-existing obligation to preserve the view for old on_query when installed. No allocation, workspace or hidden query snapshot is added. To retain text use `cui_component_event_copy_utf8` with explicit bound/storage and check its status; a struct copy does not own text. Other new observers follow the old hook. Select freezes paths before legacy code can redirect state. Confirm snapshots actual selected row and legacy confirm/user, then runs action → captured old confirm → new activation. Action-induced selection changes do not rewrite the confirmed path. Same-item/repeated confirmations remain separate ACTIVATE calls. No callback rejects an operation, changes consumption or introduces commit/submit semantics. Handlers/user borrow through the outer call. Selection/activation payloads are pointer-free copies, safe to retain beyond resource teardown. New handlers may copy facts or set unrelated application flags; they must not mutate/rebind active state/editor/model/resources, recurse into the same operation, destroy resources or unwind across C. Legacy mutations retain their existing timing. Defer removal and teardown until the outer operation and any renderer consumption complete. Missing callbacks do not make controls read-only. Clearing selection remains the existing silent helper. Styled behavior is specified below; Base always remains contextless. ## Styled submission and causes `cui_command_events(ui, id, theme, state, entries, count, options, handler)` returns the same typed result with the legacy Styled bool in `control` and counts across all operations actually observed during that call. No final-state replay, extra model interaction or allocation is added. A later false return retains successful earlier query/selection notifications, including before invalid custom geometry. The same early-query exception and callback lifetime rules apply. The leading rebuild detects an externally edited query by the existing hash. It is PROGRAMMATIC with no invented frame/input evidence, including under disabled, inert/layout-only ancestry or loading. Initial/unchanged rebuild remains silent. An aggregate query-input change reports UNKNOWN with the proven active frame, without picking a text event/index; Escape query-clear has its actual keyboard frame/index/source. Hover selection is aggregate and may be stationary: it reports UNKNOWN/frame-only, not a fabricated pointer event. No per-edit query claim. A row's activation evidence is captured after its current semantic interaction, before hover-selection or custom content/binding/old callbacks can consume input or redirect state. One genuine accepted activation supplies its exact snapshot; multiple/missing evidence reports frame-only UNKNOWN. Shared event target is the Command root; the snapshot keeps its actual row target. Confirm snapshots the actual selected path at confirm entry, including legacy redirects. If it differs from the clicked row, the copied clicked-row activation snapshot is omitted; known causal input index/source remains. Action changes after confirm entry do not rewrite that identity. Keyboard loop observations have actual frame/index/ KEYBOARD evidence, without inventing accepted activation for a query-editor target. `on_cancel(user, const cui_command_cancel_request *)` reports REQUEST to dismiss the host, not completed dismissal. It runs after legacy on_cancel, or independently when only the new observer is installed, on the same eligible empty-query Escape branch. `cancel_request_count` counts actual observer calls. No additional consume, invalidation, overlay close or veto is introduced. Nonempty searchable Escape still clears/rebuilds query rather than requesting cancellation. UI observations require a nonzero ordinary active frame; inert/layout-only, measurement and out-of-frame work emit no new UI callbacks. Legacy callback and mutation rules remain unchanged. Disabled suppresses UI interaction; loading is busy presentation and does not suppress existing nonempty-row confirmation. No submission emits nothing and registers no callback. Command rows retain OPTION with the existing pointer_activatable detail; actual accessibility FOCUS and ACTIVATE are supported without a role remap. This does not claim broader foreign/platform accessibility parity. Custom content, matching and binding callbacks remain separate APIs. Native synchronous observers do not add bridge or Python/Node/Go/Rust event categories. --- ## Authoring a custom design system Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMPONENT_AUTHORING.md # Authoring a custom design system Call base behavior inside your own Clay-backed box, then draw with your tokens. Base functions do not import colors, fonts or styled components. ```c cui_id id = cui_id_from(ui, "notify"); cui_begin_box(ui, id, (cui_box){.width=240, .height=40, .padding=8}); bool changed = cui_base_switch(ui, id, cui_string("Notifications"), &settings.notifications, false); cui_text(ui, cui_string(settings.notifications ? "Enabled" : "Disabled"), 16, my_foreground); cui_end_box(ui); ``` The box and semantic behavior use the same ID. Use a different scoped key for each child. Domain values belong to the caller; base functions request changes synchronously through controlled values and return change status. Draw from updated state and inspect `cui_interaction` for focus, hover and press. Current styled controls deliberately reuse this seam. `examples/unstyled` compiles independently of theme/style APIs, and the terminal theme uses the same behavior with square corners and amber/ink tokens. Compound components must use explicit behavioral models and focus scopes. Do not duplicate keyboard rules in their painters. Add behavioral tests, semantic assertions, a real story and limitation docs before raising manifest status. Full verified status requires every acceptance criterion in initial-prompt.md. --- ## Shared component event metadata Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMPONENT_EVENTS.md # Shared component event metadata The additive `cui_component_events.h` utility supplies common metadata and a bounded text-copy helper. It does **not** change any existing component callback, result, state owner or dispatch timing. The [78-family coverage](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_COVERAGE.md), [binding audit](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_BINDINGS.md) and [design contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_CONTRACT.md) describe the wider work. The first [Button and Check facades](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CONTROL_EVENTS.md) are implemented; [Switch/Toggle facades](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BOOLEAN_EVENTS.md) are also implemented; implemented family guides below describe their precise scope. The [current coverage audit](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_REMAINING.md) records remaining gaps and justified exceptions. This utility is not full component parity. ## Names and meanings `cui_component_event_metadata` is a pointer-free value containing a kind, nonzero stable target ID, presence flags, optional context-local frame/index, source, and an optional copied `cui_activation_snapshot`. Component values and reasons stay in separate typed payloads: a requested boolean, tri-state, date, double or selection is not a `void *value`. | Kind | Meaning supplied by the component that uses it | | --- | --- | | `CUI_COMPONENT_EVENT_ACTIVATE` | Accepted attempt to invoke an action; no implied value change. | | `CUI_COMPONENT_EVENT_REQUEST` | Proposed typed value; the owner may reject it. | | `CUI_COMPONENT_EVENT_CHANGE` | A transition that actually applied. | | `CUI_COMPONENT_EVENT_COMMIT` | Gesture/transaction completion, possibly with no net change. | | `CUI_COMPONENT_EVENT_SUBMIT` | Explicit submission, distinct from typing or blur. | | `CUI_COMPONENT_EVENT_LIFECYCLE` | Component-specific open/close/begin/end reason, kept separately. | `cui_component_event_init(&metadata, kind, target, source)` validates the enums and target and clears unavailable fields. `SOURCE_UNKNOWN` omits `HAS_SOURCE`; `SOURCE_PROGRAMMATIC` explicitly records a known application origin without inventing an input event. Pointer, keyboard and accessibility sources may also be explicitly supplied when known. Source alone does not imply activation evidence. An all-zero struct is not a valid target-bearing event. Presence flags are authoritative. `HAS_FRAME`, `HAS_INDEX`, `HAS_SOURCE` and `HAS_ACTIVATION` describe optional information; index zero is a valid first event, not an absence sentinel. `cui_component_event_set_frame_index(&metadata, frame_sequence, event_index)` records a known pair and rejects frame zero, index `SIZE_MAX`, or replacement of copied activation identity. The utility does not infer a position for programmatic work. Frame/index identities are local to the originating context and cannot be compared across recreated contexts. No timestamp, global ordering, physical device or pointer position is manufactured. ## Copy accepted evidence before mutable callbacks This complete helper can be used by a component adapter at its existing accepted-activation point. Calling it does not route, consume, accept or redispatch an input event: ```c #include static bool activation_metadata(cui_context *ui, size_t event_index, cui_component_event_metadata *out) { cui_activation_snapshot snapshot; if (!cui_event_activation_snapshot(ui, event_index, &snapshot)) return false; return cui_component_event_from_activation(out, CUI_COMPONENT_EVENT_ACTIVATE, &snapshot); } ``` Use a real snapshot or its unchanged copy. `from_activation` checks nonzero identity and supported accepted event types, derives the source, and copies existing evidence; it cannot authenticate a fabricated struct. Pointer release, key down/up and accessibility activation are supported. The utility preserves the snapshot exactly, including optional press/release/key-bounds flags. Key and accessibility events gain no fake pointer sample. Snapshot acquisition must precede mutable callbacks that could consume input. Failed helpers leave outputs unchanged. The resulting metadata may be copied by value and kept after callback, later frames or context destruction. This guarantee covers this pointer-free metadata and Core's snapshot, not arbitrary typed component payloads. In particular, copying `cui_event` does **not** deep-copy its borrowed text pointer. ## Copy borrowed text into caller storage `cui_component_event_copy_utf8(source, maximum_bytes, storage, capacity, &copied)` returns a `cui_component_event_copy_status`. Argument order deliberately places the source and payload byte limit before destination storage and its capacity. The source length and maximum are UTF-8 **bytes**, not glyphs. Capacity includes the trailing NUL; the returned `cui_str.length` excludes it. ```c static cui_component_event_copy_status keep_text(cui_str borrowed, char storage[257], cui_str *saved) { return cui_component_event_copy_utf8(borrowed, 256, storage, 257, saved); } ``` The caller owns both storage and descriptor. Keep storage alive for every use of the copied view. The helper allocates nothing, truncates nothing and never retains a handler or pointer. It checks the maximum and capacity before reading bytes, reuses Base's existing UTF-8 validation, rejects embedded NUL, and uses `memmove` so source and destination text may overlap. The output descriptor itself must be disjoint from both text regions. `{NULL,0}` is valid empty input but still requires one writable destination byte for NUL. Callers must provide the declared readable/writable extents; no C function can discover arbitrary allocation sizes from a pointer. `COPY_INVALID_ARGUMENT`, `COPY_LIMIT`, `COPY_CAPACITY` and `COPY_INVALID_UTF8` leave **both destination bytes and output descriptor unchanged**. A source length of `SIZE_MAX` fails as a limit error before adding NUL or reading bytes. No partial output or required-size side channel is published on failure. Caller-selected limits make the memory/time budget explicit; this utility does not choose a hidden global payload limit. ## Integration and lifetime boundary These are portable C11 header-only helpers. Include `cui/cui_component_events.h`; the text-copy helper calls existing `cui_edit_valid_utf8` and therefore requires the existing portable `cui` library. Metadata-only use needs no extra runtime or allocation. No platform/Clay types, callback registration, scheduler or networking are introduced. Direct C components still retain their existing behavior: Button legacy callback precedes its typed callback; controlled requests are distinct from owner acceptance; frame-result reads do not replay callbacks. Speech explicit pump, bridge queued language delivery, retained Surface/Notification/Dock registrations and current-frame Plot/Chart deferred callbacks keep their own documented timing and lifetimes. This utility neither permits recursive frame/component submission nor context destruction during callbacks. No binding event facade or automatic callback export is supplied by this slice. Future facades and bindings require their own typed-value, lifetime, multiplicity, reentrancy and compatibility tests. Applications must choose one side-effect path per action rather than performing it from both callback and frame result. The focused `tests/unit/test_component_events.c` exercises actual accepted pointer, keyboard and accessibility snapshots, evidence retention after consumption/context destruction, absent/programmatic metadata, identity overwrite rejection, atomic UTF-8 failure, exact byte/capacity limits, empty text, malformed encodings, overflow-sized input and overlapping copies. Native test runs use the invisible wrapper: ```sh python scripts/test_local.py --build-dir build -- -R component_events ``` The helper is registered in native and WASI tests and included in generated distributions, the Go/Rust source SDKs and the agent resource index. Inclusion of a C header in a source SDK does not expose a language wrapper. Binding event facades remain documented omissions. ## Nonblocking application work The separate [async HTTPS fetch example](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/async_fetch/README.md) builds an actual native UI using the existing synchronous Button callback. It copies requests to a worker, shows loading, prevents duplicate requests, delivers completions through a bounded mailbox and wakes the idle UI. Its guide covers failure, retry, stale responses, cancellation and joined shutdown, with deterministic offline tests. Networking and worker code belong to the optional Linux host example; they are not Core APIs or a replacement event-dispatch architecture. The bridge separately supports [versioned typed manual notification polling](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_NOTIFICATIONS.md). These queued post-mutation views preserve legacy dispatch timing and do not provide synchronous value rejection through language bindings. The controlled [Slider phase facade](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SLIDER_EVENTS.md) preserves double values and distinguishes BEGIN/UPDATE/COMMIT/CANCEL, including cancellation without fabricated input evidence. The [Styled Slider facade](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/STYLED_SLIDER_EVENTS.md) adds themed rendering with the same controlled double phases. Those older scalar request facades remain unbound. The separate [typed Base Slider model](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BASE_SLIDER_MODEL.md) adds direct C Single/Range proposals with frozen confirmed values, ordered evolving intent and explicit value-acceptance ownership; it preserves older Slider entry points. The unreleased [Python bridge-owned controlled subset](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PYTHON_SLIDER_MODEL.md) supplies copied Single/Range requests and explicit receipt acceptance after stepping, rather than exporting direct C state/style/result structs. The [Rust bridge subset](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/RUST_SLIDER_MODEL.md) supplies copied requests through a restricted context; Linux dynamic and matching bundled-static checks passed on1.99.1, with MSRV1.85.1 pending. The [Base Input observer](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TEXT_INPUT_EVENTS.md) and [Styled Input facade](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TEXT_INPUT_STYLED_EVENTS.md) report committed text changes and eligible submissions synchronously. These input facades do not add rejectable edit requests; [multiline observers](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MULTILINE_EVENTS.md) are available separately. [Go and Rust manual notification views](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_NOTIFICATIONS_GO_RUST.md) preserve typed queue values with owning payloads; their callbacks retain existing timing. [RadioGroup observers](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SELECTION_EVENTS.md) report actual owner selection transitions after the existing request callback. Select/Combobox and general selection requests remain outside that slice; RadioGroup activation snapshots are unavailable at its preserved reducer step. [Textarea observers](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MULTILINE_EVENTS.md) deliberately aggregate committed revision changes into at most one notification per submission. They do not claim a single input cause, per-event delivery or submission intent; Editor observers use the same aggregation, after its entire completion/multicursor/painting pass. [Select observers](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SELECT_EVENTS.md) report each actual selection transition, preserving the full list pass and popup-close timing. [Combobox observers](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMBOBOX_EVENTS.md) preserve Base/query and popup-list phase ordering; option accessibility limitations are explicit in both guides. [Surface completed-close observers](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SURFACE_EVENTS.md) use caller-owned retained registration, unlike render-call-only handlers. Existing close decisions and result consumption stay separate from lifecycle notification. [MenuTree observers](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MENU_EVENTS.md) report each applied command synchronously, including repeated commands. ContextMenu and Simple Menu forwarding are implemented separately; Dropdown forwarding is also implemented separately; this is not complete menu-family coverage. [NumberInput observers](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NUMBER_EVENTS.md) report an aggregate committed double change after the legacy reducer, independently of draft revisions or submission. They preserve step-policy callbacks and do not provide rejectable numeric requests. Additional implemented observers cover [Tabs selection](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TABS_EVENTS.md), [ContextMenu commands](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CONTEXT_MENU_EVENTS.md), [Pagination, Stepper and Rating](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NUMERIC_SELECTION_EVENTS.md), and [Calendar/DatePicker selected dates and ColorPicker RGBA](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PICKER_EVENTS.md). [Simple Menu commands](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SIMPLE_MENU_EVENTS.md) preserve repeated activations. Their guides specify aggregation and timing. These additions do not automatically extend binding allowlists. [DropdownButton](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DROPDOWN_EVENTS.md) exposes separate action and menu handlers while preserving their phase order. [OTP](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/OTP_EVENTS.md) provides aggregate accepted-operation and completion counts on CHANGE; completion is not submission. These C additions do not extend the foreign notification allowlist automatically. [Collapsible transitions](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DISCLOSURE_EVENTS.md) report every applied expanded bool write before final semantics and paint. [Single List selection](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/LIST_EVENTS.md) reuses the ordered selection seam after legacy activation/confirmation callbacks. Accordion, multi-list and ToggleGroup also report each applied transition; see [disclosure events](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DISCLOSURE_EVENTS.md) and [List events](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/LIST_EVENTS.md). The [opt-in bridge value API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_VALUE_NOTIFICATIONS.md) currently supports scalar, plain-text and selection notifications; existing polling retains its contract, and Python, JS/TypeScript, Go and Rust expose separate owning value polls. [Tree events](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TREE_EVENTS.md) observe each applied selection and expansion transition and every row invocation without replaying reduction; callbacks precede later semantics and paint. [DataTable events](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TABLE_EVENTS.md) cover sort, single selection, exact multi-selection sets and column width/move transitions; [Settings events](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SETTINGS_EVENTS.md) cover navigation and built-in boolean, number and choice fields plus committed text revisions. Explicit programmatic and UI resets report RESET separately from normal EDIT changes. [TimeField events](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TIME_FIELD_EVENTS.md) report zero or one final typed time change after the complete Base/Styled operation; draft/focus changes are separate. [Sidebar events](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SIDEBAR_EVENTS.md) report each row invocation and distinguish controlled expansion REQUEST from actual uncontrolled CHANGE after legacy callbacks. Collapse and header/footer actions remain separate slices; no generic TREEITEM accessibility activation support is implied. [Attachment actions](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/ATTACHMENT_EVENTS.md) observe OPEN/REMOVE/RETRY at the original category callback seams, with aggregate zero/one counts per category. They report requested host actions, not completed deletion/upload work. [Scrollable final-offset observers](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SCROLL_EVENTS.md) pair Base reduction or Styled composition with one final notification after children. They preserve legacy input consumption and report aggregate offsets, including normalization, without inventing an input cause. VirtualList and MessageScroller retain their separate typed result contracts. [HoverCard and Tooltip model observers](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/HOVER_EVENTS.md) distinguish the applied open-state transition from composition admission and actual visibility. Pure Base policy has no invented input evidence; Styled aggregation carries only a genuine frame. Pending timers and omitted components retain no handler. The separate [Node/TypeScript bridge-owned controlled subset](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NODE_SLIDER_MODEL.md) also supplies copied requests and explicit full-pair receipt acceptance; it does not bind direct C custom Styled style or motion records. --- ## Component composition, state and interaction Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMPONENT_USAGE.md # Component composition, state and interaction CUI composes visible UI each frame between `cui_begin_frame` and `cui_end_frame`. The context retains focus, prior hit regions, resources and transient routing. Application-owned values and explicit models persist between frames. A persistent model is not a retained application widget tree. Model-only families require application composition; this guide does not claim complete upstream parity. See the [implementation manifest](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/gpui-parity.json) for per-family limitations. This guide mirrors [component-usage.json](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/component-usage.json), the website metadata. “Immediate frame submission” means values/descriptors suffice; “application model + frame composition” highlights explicit persistent model, behavior or resource storage. Both use the same frame engine. Keep stable IDs for the same logical controls. Retain borrowed strings, arrays, buffers and callback user data for the lifetime documented by each header, including through `cui_end_frame` when deferred layout/painting uses them. Model-bound arrays may need to survive until the next successful bind/rebuild; notification and host registrations outlive a submission. Never retain callback-borrowed URLs without copying. See [frames and callbacks](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/IMMEDIATE_AND_STATE.md) and [core lifecycle](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CORE.md). Component action/change callbacks run synchronously at the API's event-reduction point; model operations may also emit events. Speech recognizer/input callbacks may originate outside frame submission; queue reports and pump on the owning thread. User pointers must be valid for that call and for any longer registered-model lifetime. Rendering another frame alone must not replay application side effects. Content/render/paint/measure callbacks are for composition and may run during measurement; never put saving, network requests, deletion or other application actions in paint-only callbacks. For example, inside an active frame, save only on activation: ```c if (cui_button(ui, save_id, theme, cui_string("Save"), false)) save_document(app); if (cui_checkbox(ui, notify_id, theme, cui_string("Notifications"), &app->notifications, false)) persist_preferences(app); ``` The checkbox updates the application's bool. Controlled Switch/Toggle `on_change` receives the requested bool; accept by updating the authoritative value or reject by leaving it unchanged. See the complete [controlled callback example](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/IMMEDIATE_AND_STATE.md#use-a-controlled-callback). Initialize models once, retain them across frames, and destroy/dispose allocated models explicitly. External model changes should invalidate the context; honor animation deadlines and reduced motion. ## Component index - [Accordion](#accordion) - [AlertDialog](#alertdialog) - [Alert](#alert) - [Attachment](#attachment) - [Avatar](#avatar) - [Badge](#badge) - [Bubble](#bubble) - [Button](#button) - [Checkbox](#checkbox) - [Clipboard](#clipboard) - [Collapsible](#collapsible) - [DropdownButton](#dropdownbutton) - [Empty](#empty) - [Focus Trap](#focus-trap) - [GroupBox](#groupbox) - [HoverCard](#hovercard) - [Icon](#icon) - [Image](#image) - [Kbd](#kbd) - [Label](#label) - [Marker](#marker) - [Message](#message) - [MessageScroller](#messagescroller) - [Notification](#notification) - [Pagination](#pagination) - [Progress](#progress) - [Radio](#radio) - [Rating](#rating) - [Shimmer](#shimmer) - [Skeleton](#skeleton) - [Spinner](#spinner) - [Stepper](#stepper) - [Switch](#switch) - [Tag](#tag) - [Toggle](#toggle) - [Tooltip](#tooltip) - [Calendar](#calendar) - [ColorPicker](#colorpicker) - [Combobox](#combobox) - [DatePicker](#datepicker) - [Editor](#editor) - [Form](#form) - [Input](#input) - [Input Group](#input-group) - [NumberInput](#numberinput) - [OtpInput](#otpinput) - [Questionnaire](#questionnaire) - [Select](#select) - [Slider](#slider) - [Speech](#speech) - [Textarea](#textarea) - [TimeField](#timefield) - [Carousel](#carousel) - [DescriptionList](#descriptionlist) - [Dialog](#dialog) - [Dock](#dock) - [List](#list) - [Menu](#menu) - [Popover](#popover) - [Resizable](#resizable) - [Root View](#root-view) - [Scrollable](#scrollable) - [Settings](#settings) - [Sheet](#sheet) - [Sidebar](#sidebar) - [StatusBar](#statusbar) - [Tabs](#tabs) - [Theme](#theme) - [TitleBar](#titlebar) - [Toolbar](#toolbar) - [Tree](#tree) - [VirtualList](#virtuallist) - [Chart](#chart) - [Command](#command) - [DataTable](#datatable) - [Plot](#plot) - [Table](#table) - [TextView](#textview) ## Accordion **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains bool expansion values and optional per-panel cui_disclosure_motion arrays. **Interaction:** Returns whether expansion changed; cui_disclosure_panel_fn composes panel children and cui_disclosure_header_fn custom headers. **Usage:** Submit stable item IDs and current expansion each frame; keep motion and style arrays alive through end_frame. API: `cui_accordion`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_disclosure.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DISCLOSURE.md). Additional event includes: `cui/cui_disclosure_events.h`. ## AlertDialog **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains cui_surface_state, cui_dialog_layout_v1 and child data through end_frame; callback tokens are borrowed only during the active callback. **Interaction:** cui_surface_decision_fn may veto close; cui_surface_closed_fn observes close; take_result consumes the decision. **Usage:** For intrinsic first-frame sizing, retain surface plus dialog layout, open with cui_dialog_open_v1, resolve current sizing, and submit six independent slots with cui_dialog_compose_v1 or its Base counterpart. Keep storage through end_frame; old surface/alert helpers remain unchanged. Held-input reset, Root/host and foreign slot builders remain separate limitations. API: `cui_surface_init`, `cui_alert_dialog`, `cui_surface_take_result`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_surface.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SURFACES.md). Additional event includes: `cui/cui_surface_events.h`. Additive C six-slot Base/Styled route: `cui/cui_dialog_composition.h` and `cui/cui_dialog_composition_styled.h`; [composition guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DIALOG_COMPOSITION.md). ## Alert **Composition:** immediate frame submission. **Scope:** styled frame component. **State:** Caller optionally retains a bool visible flag referenced by cui_alert_options.visible. **Interaction:** Returns dismissal; writes supplied visibility. **Usage:** Submit the current title/message and visibility; handle dismissal in the returned event branch. API: `cui_alert`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CONTENT.md). Direct C `cui_alert_events` and `cui_alert_dismiss_fn` observe the completed built-in dismissal after the legacy visibility write. See [dismissal timing and ownership](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/ALERT_EVENTS.md). ## Attachment **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains cui_attachment_state and owns attachment model, metadata and resource lifetime. **Interaction:** cui_attachment_result reports actions; cui_attachment_action_fn receives remove/retry activation. **Usage:** Submit transfer status and progress; perform removal/retry in action callbacks, not render callbacks. API: `cui_attachment`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_media.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MEDIA.md). Additional event includes: `cui/cui_media_events.h`. ## Avatar **Composition:** immediate frame submission. **Scope:** styled frame component. **State:** Caller retains name, borrowed RGBA pixels, bounded circular cache and destination storage through rendering. Optional typed placeholder state and mask versions also survive draw completion; named SVG uses the context cache. Metrics and palettes are copied values. **Interaction:** Interactive avatars return activation; interactive stacks return the selected index or SIZE_MAX. Application opens the selected profile. **Usage:** Initialize a circular image cache once; submit borrowed image pixels with a revision. Missing/invalid images fall back to initials; stacks use stable application keys. Opt into shared design sizes, deterministic identity palettes or anonymous SVG placeholders without changing legacy defaults. API: `cui_avatar`, `cui_avatar_ex`, `cui_avatar_stack`, `cui_avatar_image_init`, `cui_avatar_image_prepare`, `cui_avatar_measure`, `cui_avatar_identity`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h); [content guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CONTENT.md); [profile images and conversations](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/AVATAR_MESSAGE_EXAMPLES.md); [Avatar styling from Python, JS/TS, Go and Rust](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/AVATAR_STYLE_BINDINGS.md). Direct C observers: `cui_avatar_events`, `cui_avatar_stack_events`; callbacks `cui_component_activation_fn`, `cui_avatar_stack_activation_fn`. See [activation guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/AVATAR_EVENTS.md). ## Badge **Composition:** immediate frame submission. **Scope:** styled frame component. **State:** Caller owns counts, options, child state and configured Icon state. Content is synchronous; Icon masks outlive rendering. Style/constraints are borrowed during submission. **Interaction:** Child controls return their own actions; corner indicators provide nonfocusable status semantics. **Usage:** Use cui_badge_ex for count/dot/named-icon composition; use cui_badge_with_icon with caller-owned Icon state/options for configured artwork. Handle icon_error independently from composition admission and Core frame success. API: `cui_badge_defaults`, `cui_badge_ex`, `cui_badge_with_icon`, `cui_badge_icon_content`, `cui_badge_result`, `cui_badge`. Callback: `cui_button_content_fn`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BADGE.md), [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMPONENTS.md). ## Bubble **Composition:** immediate frame submission. **Scope:** styled frame component. **State:** Caller owns child data; no separate bubble model. **Interaction:** Child controls handle their own events. **Usage:** Begin the surface, compose child controls, then end it in the same frame. API: `cui_begin_bubble`, `cui_end_bubble`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CONTENT.md). ## Button **Composition:** immediate frame submission. **Scope:** styled frame component. **State:** Caller owns application data and options. Button style callbacks/user are borrowed through submission; surface shadow arrays are copied by value, bounded to eight layers; no callback/list persists across frames. **Interaction:** Returns true on activation; invoke the application action in that branch. **Usage:** For Save, call save_document only when cui_button returns true. content is a composition callback, not an action handler. API: `cui_button`, `cui_button_ex`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BUTTON.md). Opt-in styling: `cui_button_styled_ex`, `cui_button_styled_paint`, `cui_button_surface_ex`, `cui_button_surface_paint_only`. Include [`cui/cui_button_styles.h`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_button_styles.h) explicitly; see [style phases, ownership and rejection](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BUTTON_STYLES.md). These additive surface APIs are post-alpha.3 development APIs; published alpha.3 packages lack them. ## Checkbox **Composition:** immediate frame submission. **Scope:** styled frame component. **State:** Caller retains bool or cui_check_state value; context owns focus. **Interaction:** Returns true when the caller-owned value changes. **Usage:** Pass the current value by pointer and persist preferences in the change branch. API: `cui_checkbox`, `cui_checkbox_ex`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CONTROLS.md). ## Clipboard **Composition:** application model + frame composition. **Scope:** host adapter facility; no standalone styled clipboard widget. **State:** Host retains backend and application owns clipboard buffers; cui_platform carries portable callbacks. **Interaction:** Clipboard reads/writes are host interface calls, not a rendered widget action callback. **Usage:** Obtain the host clipboard interface and supply it to editing/copy controls; compose a Copy button to trigger application copying. API: `cui_sdl3_clipboard_interface`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_sdl3.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/INTERFACES.md). ## Collapsible **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains bool expansion values and optional per-panel cui_disclosure_motion arrays. **Interaction:** Returns whether expansion changed; cui_disclosure_panel_fn composes panel children and cui_disclosure_header_fn custom headers. **Usage:** Submit stable item IDs and current expansion each frame; keep motion and style arrays alive through end_frame. API: `cui_collapsible`, `cui_collapsible_ex`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_disclosure.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DISCLOSURE.md). Additional event includes: `cui/cui_disclosure_events.h`. ## DropdownButton **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains menu tree state and menu entries; style descriptors copy at entry, while pure style callbacks and userdata are synchronously borrowed. Metadata descriptors copy at entry; custom name bytes remain borrowed and immutable through submission, then Core retains frame copies. **Interaction:** cui_dropdown_button_result separates main activation from menu interaction; styled entries preserve the same Base/events reduction and legacy callback mutations. Metadata names/order apply before existing callbacks; skip-tab does not suppress pointer/AT eligibility. **Usage:** Use independent optional metadata for UTF-8 accessible names, signed tab ordering and skip-tab. NULL/zero preserves legacy behavior. Checked/value matches the existing Button convention; optional toggled presence and language-builder facades remain gaps. API: `cui_dropdown_button`, `cui_dropdown_button_events`, `cui_dropdown_button_styled_ex`, `cui_dropdown_button_styled_events`, `cui_dropdown_button_with_metadata_ex`, `cui_dropdown_button_with_metadata_events`. [Legacy header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h); [paint header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_dropdown_button_styles.h); [paint guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DROPDOWN_BUTTON_STYLES.md). ## Empty **Composition:** immediate frame submission. **Scope:** styled frame component. **State:** Caller owns title and description. **Interaction:** Borrowed content callbacks can submit buttons and handle their activation events. **Usage:** Compose optional media/title/description header, content and appended children. Child callbacks submit ordinary native controls. API: `cui_empty`, `cui_empty_ex`, `cui_empty_default_style`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CONTENT.md); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/EMPTY.md). ## Focus Trap **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains cui_overlay with modal=true; context retains focus routing/restoration. **Interaction:** Overlay update handles dismissal/focus; child controls return their own events. **Usage:** Open a modal overlay, submit children inside its active scope and close via application actions. API: `cui_overlay_init`, `cui_overlay_begin`, `cui_overlay_end`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_overlay.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/OVERLAYS.md). ## GroupBox **Composition:** immediate frame submission. **Scope:** styled frame component. **State:** Caller owns title and child data; no group model. **Interaction:** Child controls handle their own events. **Usage:** Pair begin/end around application-composed children. API: `cui_begin_group_box`, `cui_end_group_box`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CONTENT.md). ## HoverCard **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains cui_hover_state for delay/open lifecycle. **Interaction:** Hover, focus and escape update the open model. Optional synchronous observers report aggregate open-state transitions, independently of composition admission or actual visibility. **Usage:** Submit the trigger first. With event facades, inspect changed separately from control_result; end HoverCard only when control_result is true. Handlers are borrowed for the call and are not retained across delay or omission. Explicit TAP_TOGGLE accepts the submitted trigger result. LEGACY uses conservative outside taps and a retained contact workspace; RAW_PRIMARY uses unconsumed primary releases outside previous valid content bounds, with no matching down or movement threshold. Raw mode needs no contact. Accepted activation uses entry-open after release; disabled/Escape/placement retain precedence. API: `cui_begin_hover_card`, `cui_end_hover_card`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CONTENT.md); [event header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_hover_events.h); [event guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/HOVER_EVENTS.md). Event API: `cui_hover_update_events`, `cui_begin_hover_card_events`. ## Icon **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains cui_icon_state for custom SVG/resource preparation; named helper uses context resources. **Interaction:** cui_icon_loader_fn resolves SVG resources; no click callback. **Usage:** Initialize custom icon state, load data/name/path, submit each frame and destroy prepared resources after use. API: `cui_icon`, `cui_icon_named`, `cui_icon_state_init`, `cui_icon_state_destroy`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_icon.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/ICON.md). ## Image **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains cui_image_state and owns loader/resource backing storage. **Interaction:** cui_image_loader_fn resolves resources; cui_image_result reports load status, not a click event. **Usage:** Submit a source and loader each frame; retain loaded frame resources for their documented paint lifetime. API: `cui_image`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_media.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MEDIA.md). ## Kbd **Composition:** immediate frame submission. **Scope:** styled frame component. **State:** Caller owns shortcut text and optional formatting buffer. **Interaction:** Presentation only; shortcut dispatch belongs to the application. **Usage:** Submit typed single-stroke hints; compose several as ordinary row children. Host shortcut registration remains separate. API: `cui_kbd`, `cui_kbd_format`, `cui_kbd_ex`, `cui_kbd_format_stroke`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h); [typed hints](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_kbd.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/KBD.md). ## Label **Composition:** immediate frame submission. **Scope:** styled frame component. **State:** Caller owns label text. **Interaction:** Optional semantic control association; presentation has no action callback. **Usage:** Compose secondary text, Unicode highlights and private scalar masking with cui_label_options; the plain wrapper remains available. API: `cui_label`, `cui_label_source`, `cui_label_prepare`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMPONENTS.md); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TYPOGRAPHY.md); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/LABEL.md). ## Marker **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains cui_marker_state and child descriptors; owns animation time. **Interaction:** cui_status_render_fn paints rich content; no action callback. **Usage:** Supply elapsed time/loading status and compose children using resolved style and opacity. API: `cui_marker`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_status.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/STATUS_COMPONENTS.md). ## Message **Composition:** immediate frame submission. **Scope:** styled frame component. **State:** Caller owns message data and slot content. **Interaction:** cui_message_render_fn composes slots; action controls inside slots supply events. **Usage:** Submit body and slot options each frame; compose application actions in designated slots. API: `cui_message`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_message.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MESSAGE.md). ## MessageScroller **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains allocated cui_message_scroller_state and message data; destroy model after use. **Interaction:** Row render callbacks compose visible messages; optional cui_message_scroller_handler observes final double offsets and following-tail policy, offset before tail, after legacy composition. **Usage:** Retain state and records through frame completion. Use cui_message_scroller_events for aggregate applied notifications; explicit mutators stay result-only and returned change flags do not replay callbacks. API: `cui_message_scroller_create`, `cui_message_scroller_destroy`, `cui_message_scroller`, `cui_base_message_scroller_events`, `cui_message_scroller_events`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_message.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MESSAGE.md). Additional event includes: `cui/cui_message_events.h`; [observer guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MESSAGE_EVENTS.md). ## Notification **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains cui_notification_state, entry storage, notification content/user pointers and host binding. **Interaction:** cui_notification_callback handles click/close/action; cui_notification_send_fn delegates system delivery to host. **Usage:** Push on an application event, render the stack once after content each frame, and honor returned scheduling deadlines. API: `cui_notification_init`, `cui_notification_push`, `cui_notifications`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_status.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/STATUS_COMPONENTS.md). ## Pagination **Composition:** immediate frame submission. **Scope:** styled frame component. **State:** Caller retains size_t page. **Interaction:** Returns true when page changes. **Usage:** On a page change, load or select application data for the new page. API: `cui_pagination`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_numeric.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NUMERIC.md). Additional event includes: `cui/cui_numeric_selection_events.h`. ## Progress **Composition:** immediate frame submission. **Scope:** styled frame component. **State:** Caller owns the target fraction, host clock and optional zero-initialized cui_progress_motion. **Interaction:** Presentation only; the extended return reports whether another animation frame is needed. **Usage:** Submit the controlled fraction each frame; use cui_progress_defaults for the source loading cycle and retain motion state for smooth value changes. Circles need caller-owned pixel storage retained through rendering. API: `cui_progress_defaults`, `cui_progress`, `cui_progress_ex`, `cui_progress_circle_defaults`, `cui_progress_circle`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PROGRESS.md). ## Radio **Composition:** immediate frame submission. **Scope:** styled frame component. **State:** For grouped choices, retain one selected cui_id and cui_radio_group_state per collection; standalone radios retain one shared integer. **Interaction:** cui_radio_group resolves controlled callback requests before painting and provides arrow/Home/End navigation with one Tab stop; standalone functions return true when selection changes. **Usage:** Submit stable unique item IDs to cui_radio_group; synchronously accept or reject on_change requests in your application model. Keep selected and navigation between frames. API: `cui_radio`, `cui_radio_ex`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h); [group guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/RADIO_GROUP.md); [standalone guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CONTROLS.md). ## Rating **Composition:** immediate frame submission. **Scope:** styled frame component. **State:** Caller retains float rating. **Interaction:** Returns true when rating changes. **Usage:** Pass the current rating by pointer and save it in the change branch. API: `cui_rating`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_numeric.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NUMERIC.md). Additional event includes: `cui/cui_numeric_selection_events.h`. ## Shimmer **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains cui_shimmer_state through end_frame and supplies elapsed time. **Interaction:** Presentation only; no action callback. **Usage:** Submit text, timing and reduced-motion preference; honor animation wake deadlines. API: `cui_shimmer_text`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_status.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/STATUS_COMPONENTS.md). ## Skeleton **Composition:** immediate frame submission. **Scope:** styled frame component. **State:** Caller owns phase for the legacy route, or persistent loading motion and an owned palette for modern fixed-size painting. Easing userdata is borrowed synchronously; omission does not reset motion. **Interaction:** Decorative presentation adds no action, focus or busy semantics. Optional easing runs synchronously during sampling; application loading semantics remain separate. **Usage:** Use cui_skeleton_ex or cui_skeleton_with_palette for fixed-size painting, or cui_skeleton_present for own-root full/fraction/flex sizing and style refinement. Retain motion and schedule absolute wakes. Explicit palettes preserve custom RGBA including alpha0; legacy routes retain their behavior. API: `cui_skeleton`, `cui_loading_phase`, `cui_skeleton_options_default`, `cui_skeleton_ex`, `cui_loading_motion_sample`, `cui_skeleton_palette_from_theme`, `cui_skeleton_palette_preset_get`, `cui_skeleton_with_palette`, `cui_skeleton_presentation_default`, `cui_skeleton_present`. Callback: `cui_loading_ease_fn`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_skeleton_presentation.h); [legacy header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h); [palette header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_skeleton_palette.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SKELETON_PALETTE.md). ## Spinner **Composition:** immediate frame submission. **Scope:** styled frame component. **State:** Caller owns persistent motion state, the monotonic host clock and reduced-motion preference. Optional size descriptors and callback userdata are borrowed through submission. **Interaction:** Decorative presentation; paint/ease callbacks customize appearance and phase, with no action callback or implicit busy semantics. **Usage:** Submit cui_spinner_ex each frame while loading and schedule result.next_wake_seconds; zero deadline means idle. Use a custom paint callback for another SVG icon. Optional cui_spinner_sizing preserves named rem versus custom pixels; finite eased turns may exceed [0,1], reduced motion evaluates ease(0), and nonfinite easing rejects atomically. API: `cui_spinner_ex`, `cui_spinner_options_default`, `cui_spinner`, `cui_loading_phase`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SPINNER.md). ## Stepper **Composition:** immediate frame submission. **Scope:** styled frame component. **State:** Caller owns step descriptors and size_t active step. **Interaction:** Legacy reducer updates the active index; additive navigation requests let the application validate and choose the next submitted index. **Usage:** Submit step descriptors and the current step; validate application data before progressing elsewhere. API: `cui_stepper`, `cui_stepper_events`, `cui_stepper_navigation`, `cui_base_stepper_navigation`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_numeric.h); [controlled requests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_stepper_navigation.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/STEPPER_NAVIGATION.md). Foreign visual authoring: [binding builders](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BINDING_BUILDERS.md). Additional event includes: `cui/cui_numeric_selection_events.h`. ## Switch **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains bool value and optional cui_switch_state motion. **Interaction:** Returns activation/change; cui_boolean_change_fn receives requested value when on_change is set, leaving acceptance to the caller. **Usage:** Accept or reject requested changes in a synchronous on_change callback; resubmit the accepted value next frame. API: `cui_switch`, `cui_switch_ex`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CONTROLS.md). ## Tag **Composition:** immediate frame submission. **Scope:** styled frame component. **State:** Caller owns tag text/content; no tag model. **Interaction:** Presentation only; child controls provide actions. **Usage:** Use the text helper or pair successful begin/end and apply returned foreground/font style to children. API: `cui_tag`, `cui_begin_tag`, `cui_end_tag`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_status.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/STATUS_COMPONENTS.md). ## Toggle **Composition:** immediate frame submission. **Scope:** styled frame component. **State:** Caller retains bool pressed value. **Interaction:** Returns activation/change; optional cui_boolean_change_fn receives the requested value. **Usage:** Keep the authoritative bool in application state; on_change may validate before accepting. API: `cui_toggle`, `cui_toggle_ex`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CONTROLS.md). Additional event includes: `cui/cui_list_events.h`. ## Tooltip **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains cui_hover_state for delay/open lifecycle. **Interaction:** Hover, focus and escape update the open model. Optional synchronous observers report aggregate open-state transitions, independently of composition admission or actual visibility. **Usage:** Submit the trigger first. With event facades, inspect changed separately from control_result; end HoverCard only when control_result is true. Handlers are borrowed for the call and are not retained across delay or omission. API: `cui_tooltip`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CONTENT.md); [event header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_hover_events.h); [event guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/HOVER_EVENTS.md). Event API: `cui_hover_update_events`, `cui_tooltip_events`. ## Calendar **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains cui_calendar_state and cui_date_selection. **Interaction:** cui_calendar_result reports aggregate selection/navigation; live cui_date_disabled_fn excludes dates. Presentation and behavior extensions have no typed observer bridge or binding options; legacy CHANGE remains selection-only. **Usage:** Initialize caller state and submit each frame. Optional cui_calendar_ex enables month access, host-supplied today and neighboring cells; cui_calendar_with_behavior adds independent range transition, endpoint validation, year destination and recenter policies. Zero options preserve exact legacy behavior. Rebuild with matching headers/library. API: `cui_calendar_init`, `cui_calendar`, `cui_calendar_events`, `cui_calendar_ex`, `cui_base_calendar_ex`, `cui_calendar_reduce_ex`, `cui_calendar_submit_ex`, `cui_calendar_cell_resolve`, `cui_calendar_month_toggle_id`, `cui_calendar_with_behavior`, `cui_base_calendar_with_behavior`, `cui_calendar_reduce_with_behavior`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_picker.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PICKERS.md). Additional event includes: `cui/cui_picker_events.h`. Presentation extension: `cui/cui_calendar_presentation.h`; [opt-in month, today and neighboring dates](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CALENDAR_PRESENTATION.md). Behavior extension: `cui/cui_calendar_behavior.h`; [independent selection and navigation policies](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CALENDAR_BEHAVIOR.md). ## ColorPicker **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains cui_color_state and cui_color value. ColorEntry owns an address-stable, noncopyable bounded draft/editor; destroy after render consumption. Float-HSLA entry separately retains normalized full-precision selection/preview and an address-stable owned editor. **Interaction:** Returns true when color changes. Additive ColorEntry separates draft/preview/commit and summarizes accepted Enter commits after submission; owner sync is silent and conflict-aware. Float-HSLA entry preserves owner floats until explicit hex parsing; SELECT requests close without owning a popup. **Usage:** Submit persistent channel/editor state; use the accepted color in the next frame theme or preview. API: `cui_color_picker`, `cui_color_picker_events`; additive `cui_color_entry`, `cui_base_color_entry` and the ColorEntry model operations. [Picker public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_picker.h); [ColorEntry public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_color_entry.h); [picker guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PICKERS.md); [entry guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COLOR_ENTRY.md). Additional includes: `cui/cui_picker_events.h`, `cui/cui_color_entry.h`. ColorEntry keeps optional committed and preview values separate from its bounded draft. Float-HSLA primitives and entry: `cui_color_hsla_entry`, `cui_base_color_hsla_entry` and model/conversion operations. [Primitive header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_color_hsla.h); [entry header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_color_hsla_entry.h); [float entry guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COLOR_HSLA_ENTRY.md). Float owner precision is preserved across display; explicit hex commit quantizes by source truncation/parsing. Popup focus/actions, tabs and handwritten foreign builders remain outside this slice. ## Combobox **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains cui_edit query/buffer, popup state, items, selection and filtered scratch array with capacity at least the item count. **Interaction:** cui_combobox_result distinguishes query and selection behavior. **Usage:** Retain the query editor and popup; filter application choices using the query and process returned changes. API: `cui_combobox`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CHOICE.md). ## DatePicker **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains cui_date_picker_state and cui_date_selection. DateTime uses separately initialized cui_date_time_picker_state plus cui_date_time_value; both are owner-thread/context local. **Interaction:** Returns final selection changes; live cui_date_disabled_fn restricts dates. The extended API forwards Calendar presentation/behavior and preserves final-queue completion close/focus; legacy CHANGE wrappers do not accept the extension or observe lifecycle. **Usage:** Initialize stable popup identity once; submit caller state and selection each frame. Optional cui_date_picker_ex forwards month/today/neighbor presentation and independent range/year/recenter policies. Zero extension preserves legacy behavior, including late-error bool; rebuild matching headers/library. The separate date-only actions facade adds bounded presets, an optional clear button and explicit Delete scope with retained child selection; language builders omit it. Optional cui_date_time_picker is a separate single civil date/time model with retained time, explicit assignment, bounded presets/clear and one-reduction Styled composition; Base helpers submit semantics inside caller-owned popup. No timezone/range/chrono parser, typed callback stream or binding facade is provided. The DatePicker gallery has an explicit single-date Date + time mode with desktop/touch segment editing, presets/clear and copyable C11 snippet; turning it off retains the date in legacy/actions modes. API: `cui_date_picker_init`, `cui_date_picker`, `cui_date_picker_events`, `cui_base_date_picker`, `cui_date_picker_ex`, `cui_base_date_picker_ex`, `cui_date_picker_calendar_id`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_picker.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PICKERS.md). Additional event includes: `cui/cui_picker_events.h`. Calendar forwarding: `cui/cui_date_picker_calendar.h`; [presentation and behavior guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DATE_PICKER_CALENDAR.md). Optional civil date/time: [DateTime picker guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DATE_TIME_PICKER.md); `cui/cui_date_time_picker.h`. ## Editor **Composition:** application model + frame composition. **Scope:** styled frame adapter + retained base model. **State:** Application retains the multiline edit, visual-row workspace, editor/search state, matcher ranges, query/replacement edit models and optional replacement scratch. Multicursor editing also borrows live selections, history snapshots and cursor anchors; adapters borrow this storage. **Interaction:** cui_editor returns edit, selection and scroll results; retained search supports ASCII-insensitive navigation and atomic replacement. Optional multicursor interaction supports adding cursors, measured navigation, selection painting, atomic typing and undo/redo; cui_editor_highlight_fn supplies syntax colors. **Usage:** Initialize editor and optional search resources once, call cui_editor_find_bar every frame, and pass the same matcher in cui_editor_options.search for visible match highlights. Attach selection storage with cui_edit_attach_selections and initialize borrowed anchors with cui_editor_multicursor_init to enable multicursor interaction. Keep replacement scratch disjoint from model storage. API: `cui_editor_state_init`, `cui_editor_multicursor_init`, `cui_editor_matcher_init`, `cui_editor_search_enable_replace`, `cui_editor_find_bar`, `cui_editor_search_open`, `cui_editor`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_editor.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/EDITOR.md). Event API includes: `cui/cui_editor_events.h`. ## Form **Composition:** immediate frame submission. **Scope:** styled frame component. **State:** Caller owns field descriptors, labels, validation messages and each control value/model. **Interaction:** cui_form_content_fn composes field controls; those controls supply action/change events. **Usage:** Describe associations and validation in fields; submit controls in content callbacks and handle their events there. API: `cui_form`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_form.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/FORMS.md). ## Input **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains cui_edit and its backing buffer; cui_input_ex additionally uses caller-owned cui_input_state. **Interaction:** cui_input_result reports changed, submitted, rejected and errors. Optional whole-value validate callback decides whether a proposed edit is accepted. Checked pattern and number formatting use caller-owned workspace and commit as one Undo step. **Usage:** Create an editor once; submit it each frame and perform application submission only on the result event. API: `cui_input`, `cui_input_ex`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/INPUT.md). ## Input Group **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains cui_edit, cui_input_group_state, and addon descriptors. **Interaction:** cui_input_group_result reports edit behavior; cui_input_group_content_fn composes addons. **Usage:** Keep the editor and state across frames and compose prefix/suffix addon controls. API: `cui_input_group`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_form.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/FORMS.md). cui_input_group_result reports edit behavior; cui_input_group_content_fn composes addons. Opt-in observers report accepted addon activations and per-event nested text changes/submissions; results never replay callbacks. Additional event includes: `cui/cui_form_events.h`. ## NumberInput **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains double value, cui_number_state and its borrowed cui_edit editor/buffer. **Interaction:** cui_number_result reports changed/submitted/invalid; cui_number_step_fn customizes stepping. **Usage:** Retain editor draft across frames; consume submitted/changed separately from invalid input. API: `cui_number_input`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_numeric.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NUMERIC.md). Additional event includes: `cui/cui_number_events.h`. ## OtpInput **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains cui_otp_state and initialized character buffer. **Interaction:** cui_otp_result distinguishes changed and completion events. **Usage:** Initialize bounded storage once, submit cells each frame and consume the returned completion event. API: `cui_otp_init`, `cui_otp`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_otp.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/OTP.md). Additional event includes: `cui/cui_otp_events.h`. ## Questionnaire **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains question definitions, state and all workspace buffers. An attached observer, handler/userdata and disjoint frame arenas remain alive through detach and all in-flight callbacks; rebuild matching headers/library after the state pointer ABI extension. **Interaction:** cui_questionnaire_event_fn emits live legacy model events; cui_questionnaire_validate_fn validates answers. The optional persistent typed observer runs synchronously before each legacy callback with frozen bounded copied payloads; handlers are observational and input metadata is UNKNOWN. **Usage:** Initialize definitions/workspace once; compose current controls each frame and handle answer/submit events. Optional masked slot styles refine boxes; six localized labels override defaults. Rebuild consumers after changing the by-value options ABI. Additive keyboard policies offer OFF/letters/numbers, item-only answer entry and host-selected Control/Meta submission; zero preserves legacy routing. Language builders omit these policies. Pure answer/submission snapshots copy effective values into caller-owned bounded storage without callbacks or model mutation; query_copy reports scalar state. Language builders omit snapshot APIs. Optional typed observation freezes Completed/Submit as one pair, preserves legacy callback replacement and nested mutations, and reports capacity/depth failures without suppressing legacy events. Detach can return BUSY while an outer callback pins resources. Language builders omit observer attachment, typed payloads and arenas. Additive progress presentation supports masked localized accessible/visible labels, borrowed decorative child composition and explicit bounded text size/linebox/style/color; zero preserves legacy paint and enabled-position numeric semantics. No implicit typography cascade or language-builder progress facade is provided. Additive named Title/Description/ChoiceDescription and decorative Error content use independent LEGACY/TOKENS text policies and masked text refinements. Zero extracts legacy text metrics and preserves Error paint; separate text wrappers do not recreate heading gap automatically. Four-size token tiers are source-derived; shared design-size proportional tiers are CUI extensions. Schema parts need an Item container for active/disabled gating; Error keeps one localized Alert. Callbacks are borrowed, pure and C-only; no family style cascade or model events are added. Additive independent geometry exposes five masked container/card patches, checked full numeric metrics and borrowed extended choice renderers. NULL/zero retains the exact legacy path; numeric values never implicitly cascade. Shared design size wins over custom scalar, then explicit masks win. Minimum blank area shares the real card hit/focus/semantic ID; fixed overflow and ancestor clipping remain ordinary Core behavior. Default choice text refinements stay inside the existing reducer. Input asymmetric padding/editor style, Button/trailing actions, Form role, arbitrary Styled and language-builder geometry remain required followups. API: `cui_questionnaire_init`, `cui_questionnaire_begin`, `cui_questionnaire_end`, `cui_questionnaire_begin_with_keyboard`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_questionnaire.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/QUESTIONNAIRE.md); [keyboard policies](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/QUESTIONNAIRE_KEYBOARD.md); [retained snapshots](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/QUESTIONNAIRE_SNAPSHOTS.md). Typed observation: `cui/cui_questionnaire_observer.h`; [lifetime and copied-payload guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/QUESTIONNAIRE_OBSERVER.md). Named text presentation: `cui/cui_questionnaire_presentation.h`; [policies, composition and lifetimes](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/QUESTIONNAIRE_PRESENTATION.md). Geometry: `cui/cui_questionnaire_geometry.h`; [metrics, precedence and minimum bounds](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/QUESTIONNAIRE_GEOMETRY.md). ## Select **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains cui_choice_popup, selected cui_id and item array. **Interaction:** Returns selection change; choice content/render callbacks customize presentation. **Usage:** Initialize popup once; submit trigger and selected value each frame. API: `cui_select`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CHOICE.md). ## Slider **Composition:** immediate frame submission. **Scope:** styled frame component. **State:** Caller retains float value and supplies min/max/step. Optional palette values own all colors and two gradient stops; no borrowed storage. Optional typed model values/domain/state own pointer-free doubles. Optional style plans own source metrics and background brush values; the pure resolver does not render or submit a Styled widget. The C-only Base route borrows callback/user/strings synchronously, keeps confirmed entry immutable and evolves requested intent; acceptance explicitly updates external owner storage. The unreleased C Styled facade owns separate ring motion and rejects visible V1 gradient thumbs before reduction; actual V2 adapters and native numeric host delivery remain pending. The unreleased C bridge kind81 owns reducer/presentation state and a copied request FIFO; explicit receipt acceptance updates a full double Single/Range pair after step without legacy CHANGE. The unreleased Python and Node/TypeScript controlled builders own frozen copied requests and receipt tokens; callbacks run after legacy dispatch, with explicit full-pair acceptance. Go controlled builders return owned value copies with private receipt authority; all controlled bridge callbacks require explicit full-pair acceptance. Rust controlled builders own copied typed requests and local receipt tokens; restricted HRTB callbacks receive a borrowed request context after legacy dispatch and accept full pairs explicitly. Rust App remains !Send/!Sync; close requests shutdown and Drop destroys. **Interaction:** Legacy scalar route returns true when the value changes; the C-only typed Base route emits ordered proposals and returns passive counts without accepting owner values. Python, Node/TypeScript, Go and Rust use independent after-step FIFOs and never autoaccept. **Usage:** Pass a volume value by pointer; apply audio settings only in the change branch. The browser gallery uses the controlled Single/Range facade with explicit accept/reject, both axes, reverse/log and passive deadlines; its complete callback/init/compose copy code is in web/modules/slider_usage.js. Native typed delivery and V2 gradient adapters remain pending. Python and Node/TypeScript controlled authoring and complete callback/compose examples are documented in docs/PYTHON_SLIDER_MODEL.md and docs/NODE_SLIDER_MODEL.md; Go owned-value authoring is documented in docs/GO_SLIDER_MODEL.md. Rust owned-value authoring and the restricted callback context are documented in docs/RUST_SLIDER_MODEL.md. API: `cui_slider`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CONTROLS.md). Additional event includes: `cui/cui_styled_slider_events.h`. The unreleased C-only palette value API is declared in [`cui_slider_palette.h`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_slider_palette.h); include `` and follow the [palette usage guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SLIDER_PALETTE.md). `cui_slider_palette_preset_get` copies an owned value for inspection; it does not apply a palette to Slider rendering. There is no presenter setter, sampler or language builder API in this slice. Disabled/theme presentation remains partial. The unreleased independent typed value/math API is declared in [`cui_slider_model.h`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_slider_model.h); include `` and follow the [owned value/math guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SLIDER_MODEL_VALUES.md). It validates and constrains double Single/Range values, maps linear/log fractions and initializes owned state. It does not submit UI, emit requests, bind an owner, render typed Sliders or add language builder APIs. The unreleased C-only typed Base Slider route is in ``; follow [Base Slider usage](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BASE_SLIDER_MODEL.md). It owns explicit-size Single/Range geometry and emits synchronous proposals; The separate [C Styled facade](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/STYLED_SLIDER_MODEL.md) adds source presentation and motion. Native numeric host delivery remains pending. Legacy scalar APIs retain their existing behavior. The unreleased controlled C bridge route is in ``; follow [typed bridge Slider usage](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_SLIDER_MODEL.md). It owns copied requests and accepts explicit full pairs after step. The [Python controlled builder](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PYTHON_SLIDER_MODEL.md) and [Node/TypeScript builders](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NODE_SLIDER_MODEL.md) wrap this route; the [Rust subset](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/RUST_SLIDER_MODEL.md) adds owned requests and a restricted callback context. Native numeric delivery and V2 adapters remain pending. ## Speech **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains speech state/workspace and recognizer/input implementations. **Interaction:** cui_speech_event_fn reports recognition events; host reports queue messages and application pumps them. **Usage:** Initialize provider bindings, pump recognition on the owning thread and compose button/waveform each frame; dispose after use. API: `cui_speech_init`, `cui_speech_pump`, `cui_speech_button`, `cui_speech_dispose`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_speech.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SPEECH.md). ## Textarea **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains cui_edit, buffer, cui_textarea_state and line workspace. **Interaction:** cui_textarea_result reports edit events and layout errors. **Usage:** Initialize line storage once and submit the multiline editor each frame. API: `cui_textarea`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_textarea.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TEXTAREA.md). Additional event includes: `cui/cui_multiline_events.h`. ## TimeField **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains cui_time_state and cui_time value; additive localized route retains cui_time_field_state_v1 and immutable borrowed locale/options. **Interaction:** Legacy plain functions return bool after applying edits. V1 returns cui_time_field_result_v1: changed is net value mutation, status is operation outcome and validation is edit validation; optional cui_time_change_fn observes one copied aggregate after Base semantics or Styled submission. **Usage:** Choose one side-effect path: observe via cui_time_handler or branch on changed after submission, rather than applying the same side effect twice. Value mutates through its pointer; do not reapply the callback payload. Retain state/options and immutable locale resources, check status/validation, and compose during ordinary frames. API: `cui_time_field`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_picker.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PICKERS.md). Additional event includes: `cui/cui_picker_events.h`. Pure locale/domain text helpers use `cui/cui_time_text.h`; the unchanged `cui_time` value is declared in `cui/cui_time_types.h`. See [TimeField text values](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TIME_FIELD_TEXT.md). These unreleased C-only helpers do not localize the existing widget. The additive `cui/cui_time_field_v1.h` route uses caller-owned `cui_time_field_state_v1` and explicit locale/domain options; see [localized widget](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TIME_FIELD_LOCALIZED.md). Legacy options and state stay unchanged. The additive [localized bridge source checkpoint](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_TIME_FIELD_LOCALIZED.md) is unvalidated; existing foreign builders still expose only the scalar subset. Its owned records are declared in `cui/cui_bridge.h`, independently of direct C borrowed widget state. No new bridge/binding support is advertised yet. The [Python localized source checkpoint](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PYTHON_TIME_FIELD_LOCALIZED.md) prepares owned configuration/observations and a complete authored UI, but has not passed Python runtime or package checks. Other four localized builders remain pending. ## Carousel **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains state, geometry workspace and slide data. **Interaction:** cui_carousel_change_fn observes selection; cui_carousel_render_fn composes slides. **Usage:** Initialize capacity once, submit slides each frame and handle selected-index changes separately from slide rendering. API: `cui_carousel_state_init`, `cui_carousel`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_carousel.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CAROUSEL.md). ## DescriptionList **Composition:** immediate frame submission. **Scope:** styled frame component. **State:** Caller owns item descriptors/content; no separate list model. **Interaction:** cui_description_render_fn composes custom values; child controls provide actions. **Usage:** Submit label/value descriptors each frame; respect the resolved layout width in custom content. API: `cui_description_list`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_description.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DESCRIPTION_LIST.md). ## Dialog **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains cui_surface_state, cui_dialog_layout_v1 and child data through end_frame; callback tokens are borrowed only during the active callback. **Interaction:** cui_surface_decision_fn may veto close; cui_surface_closed_fn observes close; take_result consumes the decision. **Usage:** For intrinsic first-frame sizing, retain surface plus dialog layout, open with cui_dialog_open_v1, resolve current sizing, and submit six independent slots with cui_dialog_compose_v1 or its Base counterpart. Keep storage through end_frame; old surface/alert helpers remain unchanged. Held-input reset, Root/host and foreign slot builders remain separate limitations. API: `cui_surface_init`, `cui_surface_begin`, `cui_surface_end`, `cui_surface_take_result`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_surface.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SURFACES.md). Additional event includes: `cui/cui_surface_events.h`. Additive C six-slot Base/Styled route: `cui/cui_dialog_composition.h` and `cui/cui_dialog_composition_styled.h`; [composition guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DIALOG_COMPOSITION.md). ## Dock **Composition:** application model + frame composition. **Scope:** styled frame adapter + retained base model. **State:** Application retains cui_dock, cui_dock_view and the panel registry; keep callback data alive through renderer completion. **Interaction:** Panel render callbacks compose active content; on_event reports select, close, reorder, move, split and resize; allow_operation may veto structural actions. **Usage:** Create the model and view once, register stable panel keys, submit cui_dock_view_render each frame and serialize the model between frames. API: `cui_dock_view_create`, `cui_dock_view_render`, `cui_dock_view_destroy`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_dock.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DOCK.md), [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DOCK_MODEL.md). ## List **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains cui_list_state, selected cui_id and item array. **Interaction:** Returns changes; cui_choice_activation_fn / cui_choice_confirm_fn / cui_choice_cancel_fn handle list interaction. **Usage:** Keep keys stable; submit current items and selection, then handle activation/confirmation callbacks synchronously. API: `cui_list`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CHOICE.md). Additional event includes: `cui/cui_list_events.h`. ## Menu **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains menu entries and popup/menu-tree state. **Interaction:** Returns activation and writes the activated cui_id through the action pointer; check/radio entries update caller values. cui_menu_render_fn composes custom content. **Usage:** Initialize menu-tree state once and submit stable entry IDs each frame; invoke application actions from the returned activation and action key. API: `cui_menu_tree`, `cui_menu`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CHOICE.md). ## Popover **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains cui_surface_state and child form/application data. **Interaction:** cui_surface_decision_fn may veto close; cui_surface_closed_fn observes close; take_result consumes the decision. **Usage:** Initialize the appropriate surface kind, open from an action, and pair end only when begin succeeds. Consume result once. Use cui_popover_begin for explicit anchor/offset/arrow positioning, paired with surface_end; legacy surface_begin keeps its original placement. Arrow rendering requires a mesh-capable adapter; SDL3 and browser adapters support bounded analytic meshes with documented limits. The gallery starts in legacy mode; explicitly select source anchors to explore all eight popup anchors, signed custom gap, arrow toggle, app/host reference rem and edge clamping. Open the card before the inert/modal demonstrations. The copyable complete C11 snippet follows the current mode. API: `cui_surface_init`, `cui_surface_begin`, `cui_surface_end`, `cui_surface_take_result`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_surface.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SURFACES.md). Additional event includes: `cui/cui_surface_events.h`. ## Resizable **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains state, slots and panel descriptors. **Interaction:** cui_resizable_resize_fn observes size changes; panel content composes controls. **Usage:** Initialize slot storage, submit panel descriptors each frame and save sizes after resize events. API: `cui_resizable_state_init`, `cui_resizable`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_resizable.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/RESIZABLE.md). ## Root View **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains cui_root, plugin instance storage, registry and bound surface/notification storage. **Interaction:** cui_root_content_fn composes application content; cui_root_copy_fn handles copy; plugins have explicit lifecycle hooks. **Usage:** Initialize root/plugin storage, render content and facilities each frame, then dispose after use. API: `cui_root_init`, `cui_root_render`, `cui_root_dispose`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_root.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/ROOT.md). ## Scrollable **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains cui_scroll_state offsets and supplies content/viewport dimensions. **Interaction:** Legacy begin/end reduce scroll input. Optional paired observers report one applied final offset after children and finish; normalization is not evidence of user input. **Usage:** Preserve caller offsets. Base observer begin may return false for a valid no-change pair and must still be finished. Styled observer begin returns admission: end only after true. Handlers are borrowed by finish/end; do not mix pairing layers. API: `cui_scrollable_begin`, `cui_scrollable_end_ex`, `cui_base_scrollable_events`, `cui_base_scrollable_finish_events`, `cui_scrollable_begin_events`, `cui_scrollable_end_events`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_scroll.h); [event header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_scroll_events.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SCROLL.md); [event guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SCROLL_EVENTS.md). ## Settings **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains page state/workspace, descriptors and actual setting values. **Interaction:** cui_setting_render_fn composes controls; cui_setting_dirty_fn and cui_setting_reset_fn implement application dirty/reset behavior. **Usage:** Initialize page/query storage; submit descriptors and implement each setting through its render/dirty/reset functions. API: `cui_settings_state_init`, `cui_settings`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_settings.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SETTINGS.md). Additional event includes: `cui/cui_settings_events.h`. ## Sheet **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains cui_surface_state and child form/application data. **Interaction:** cui_surface_decision_fn may veto close; cui_surface_closed_fn observes close; take_result consumes the decision. **Usage:** Initialize the appropriate surface kind, open from an action, and pair end only when begin succeeds. Consume result once. API: `cui_surface_init`, `cui_surface_begin`, `cui_surface_end`, `cui_surface_take_result`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_surface.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SURFACES.md). Additional event includes: `cui/cui_surface_events.h`. ## Sidebar **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains sidebar state/cache, entry descriptors and selected application route. **Interaction:** cui_sidebar_content_fn composes regions; menu-item results expose selection/activation. **Usage:** Initialize measurement cache, submit current entries, and update routing from menu-item events. API: `cui_sidebar_state_init`, `cui_sidebar`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_sidebar.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SIDEBAR.md). ## StatusBar **Composition:** immediate frame submission. **Scope:** styled frame component. **State:** Caller owns left/center/right descriptors and displayed data. **Interaction:** cui_chrome_render_fn composes regions; child controls handle actions. **Usage:** Submit region content each frame; preserve application data outside the bar. API: `cui_status_bar`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_chrome.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CHROME.md). ## Tabs **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains selected cui_id, item array and optional motion/scroll state. **Interaction:** Returns selection changes; cui_tab_panel_fn composes selected panel content. **Usage:** Submit tab descriptors and current selected key; keep optional animation state across frames. API: `cui_tabs`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CHOICE.md). Event API includes: `cui/cui_tabs_events.h`. ## Theme **Composition:** application model + frame composition. **Scope:** application style data; passed during frame submission. **State:** Caller retains cui_theme value and any icon-loader user/backing storage. **Interaction:** cui_theme_icon_loader_fn resolves icon SVG; theme selection is an application event. **Usage:** Choose/copy a preset and pass its address to styled controls; invalidate after changing it. Unreleased cui_background values/sample helpers are pure C-only math. For actual opt-in rendering, use cui_software_query_v2 before Core V2 composition and cui_software_render_v2 afterwards; V1 routes remain unchanged. The other four renderer paths, foreign authoring and all78 part coverage remain pending. API: `cui_theme_light`, `cui_theme_preset_get`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_theme.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/THEME_GUIDE.md). Pure background values: explicitly include [`cui/cui_background.h`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_background.h) and read [background sampling and ownership](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BACKGROUND_VALUES.md). These development APIs sample colors. Explicit [`cui/cui_draw_v2.h`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_draw_v2.h) adds [Core V2 background transport](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CORE_DRAW_V2.md); renderer paths and foreign authoring remain pending. Maintainer-only [CPU preparation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BACKGROUND_PREPARATION.md) is an allocation-free building block, not a renderer. ## TitleBar **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains cui_title_bar_state and window interface binding. **Interaction:** on_close callback handles application close; window host functions implement native window behavior. **Usage:** Submit current window information each frame; keep host/user pointers valid during calls. API: `cui_title_bar`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_chrome.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CHROME.md). ## Toolbar **Composition:** immediate frame submission. **Scope:** styled frame component. **State:** Caller owns item/command descriptors and command user data. **Interaction:** cui_toolbar_render_fn composes items; cui_toolbar_command.on_activate handles command activation. **Usage:** Submit command descriptors each frame and perform application actions in on_activate. API: `cui_toolbar`, `cui_toolbar_command_render`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_toolbar.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TOOLBAR.md). Additional event includes: `cui/cui_toolbar_events.h`. ## Tree **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains model/state, selected cui_id and borrowed node/expansion arrays until next successful rebuild. **Interaction:** cui_tree_result separates selection_changed, expansion_changed and activated key. **Usage:** Rebuild preorder data when it changes; submit visible rows each frame and open the activated application item from the result. API: `cui_tree_create`, `cui_tree_rebuild`, `cui_tree`, `cui_tree_destroy`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_tree.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TREE.md). Event API includes: `cui/cui_tree_events.h`. ## VirtualList **Composition:** application model + frame composition. **Scope:** styled frame adapter + retained base model. **State:** Application retains cui_virtual_list and cui_virtual_widget_state; keyed extents live in the model and row controls remain application-owned. **Interaction:** cui_virtual_render_item_fn composes the visible window; cui_virtual_measure_item_fn supplies intrinsic measurement; optional cui_scroll_handler observes aggregate final offsets after composition, with UNKNOWN source. **Usage:** Rebuild keyed extents between frames and keep keys stable during row callbacks. Use cui_virtual_list_draw_events for final-offset observation; inspect changed separately from delivered change_count and the unchanged deferred control_result. API: `cui_virtual_list_draw`, `cui_base_virtual_list`, `cui_virtual_list_draw_events`, `cui_base_virtual_list_events`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_virtual_scroll.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/VIRTUAL_LIST.md), [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/VIRTUALIZATION.md), [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/VIRTUAL_EVENTS.md). Additional event includes: `cui/cui_virtual_events.h`. ## Chart **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains cui_chart_state, its RGBA pixel buffer/byte capacity, data arrays and resources used by options. **Interaction:** Hit testing identifies data; tooltip/format/paint callbacks customize output and are not application action callbacks. **Usage:** Submit data/options each frame; route application actions from explicit hit testing or child controls. API: `cui_chart`, `cui_chart_hit_test`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_chart.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CHART.md). The gallery custom tooltip toggle uses `cui_chart_tooltip_build_fn` with copied row strings. See [the callback example](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CHART_TYPED_TOOLTIP.md), [point-axis layout](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CHART_SOURCE_POINT_AXIS.md), [Radar title policy](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CHART_RADAR_TOOLTIP_TITLE.md) and [current-frame painting](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PLOT_CHART_CURRENT_FRAME.md). ## Command **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains command state, row workspace, cui_edit query and command descriptors. **Interaction:** on_select/on_query/on_confirm/on_cancel observe synchronous interaction; command item action invokes application work. **Usage:** Initialize bounded query/row storage, submit entries each frame, and execute actions only from confirmation/action events. API: `cui_command_init`, `cui_command`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_command.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMMAND.md). Event API includes: `cui/cui_command_events.h`. ## DataTable **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains allocated model/state, data rows/columns and any borrowed label storage. **Interaction:** cui_table_result reports interaction; cui_table_label_fn provides accessibility text and cui_table_cell_fn composes visible cells. **Usage:** Bind data when changed, submit virtual cells each frame, and handle selection/sort actions from the result. Enabled movable headers own touch reorder; body/nonmovable headers retain pan, and touch drops use indexed clipped-region admission. API: `cui_table_create`, `cui_data_table`, `cui_table_destroy`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_table.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TABLE.md). Additional event includes: `cui/cui_table_events.h`. ## Plot **Composition:** application model + frame composition. **Scope:** styled frame adapter + standalone numeric model; bounded software rasterizer. **State:** Caller retains scales, samples, path commands, RGBA pixels, tick labels and callback state; no retained widget tree. **Interaction:** cui_plot_activate_fn receives validated pointer positions; pure numeric operations return cui_plot_result and the application routes pan/zoom. **Usage:** Build paths and render into caller-owned pixels, then submit a themed bitmap and axes each frame; keep labels and pixels alive through renderer completion. API: `cui_plot_view`, `cui_plot_axis`, `cui_plot_raster`, `cui_plot_path`, `cui_plot_map`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_plot_view.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PLOT.md); [numeric model](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PLOT_MODEL.md). ## Table **Composition:** immediate frame submission. **Scope:** styled frame component. **State:** Caller owns row/cell hierarchy and data; no retained table model is required. **Interaction:** Composition only; child controls handle actions. **Usage:** Submit sections, rows and cells using balanced begin/end nesting each frame. API: `cui_table_begin`, `cui_table_begin_row`, `cui_table_begin_cell`, `cui_table_end`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_table.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TABLE.md). ## TextView **Composition:** application model + frame composition. **Scope:** styled frame component. **State:** Caller retains state and all source/rendered/layout workspace buffers. **Interaction:** on_link/open_url handle link interaction; image resolves resources; other content/measurement hooks compose or paint. **Usage:** Initialize bounded workspace, set text on changes, then submit each frame. Decoded link URLs are borrowed only during callbacks: copy for deferred use. API: `cui_text_view_init`, `cui_text_view_set_text`, `cui_text_view`. [Public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_text_view.h); [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TEXT_VIEW.md). ## Core layout constraints **Scope:** Opt-in C Core only: current intrinsic Y body allocation, standalone Y clamping and fixed real overlay track/thumb boxes with independent visibility/interactivity and current final paint/hit geometry. Widths remain independent of allocated Y. Existing Scrollable/Base/Dialog composition APIs and all five foreign builders remain unchanged; this is not full slot composition or general constraint closure. **Capacity:** 32 body links, 64 total clamps (two per body) and 64 optional tracks, one per clamp; copied 80/32/48-byte records and distinct application offset destinations borrowed through end_frame. LP64 lazy payload 12856 bytes, bounded by 16 KiB; zero-opt-in legacy frames allocate none. Read [SCROLL_LAYOUT.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SCROLL_LAYOUT.md) and the exact declarations in [Core public header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui.h); these APIs do not change the 78-component manifest. --- ## Northstar: a composed native CUI application Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMPOSED_APPS.md # Northstar: a composed native CUI application Northstar is a complete, editable workspace demo assembled from real CUI controls. Its overview, pricing and settings pages share a responsive navigation shell and an account menu. It demonstrates application composition rather than individual controls in isolation. ![Northstar desktop overview](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/composed_apps/screenshots/overview-desktop.png) ## Build and run From the repository root: ```sh cmake -S examples/composed_apps -B examples/composed_apps/build -G Ninja cmake --build examples/composed_apps/build ctest --test-dir examples/composed_apps/build --output-on-failure ``` The standalone project includes the checkout's CUI library, native adapters and full repository test suite, then builds the `northstar` host and the additional `composed_app_interactions` test. C11 sources compile with the repository's warnings-as-errors settings. Requirements are CMake 3.20+, Ninja and a C/C++ compiler; the existing optional adapters use installed SDL3 3.2+, FreeType and HarfBuzz. No new dependencies or downloads are introduced. The repository's pinned optional SDL3 fetch remains available via `-DCUI_FETCH_SDL=ON`. Choose an existing font file and launch the native application: ```sh FONT=/usr/share/fonts/noto/NotoSans-Regular.ttf examples/composed_apps/build/northstar --font "$FONT" examples/composed_apps/build/northstar --font "$FONT" --page pricing examples/composed_apps/build/northstar --font "$FONT" --page settings --width 390 --height 844 ``` The font shown above was available on the Linux validation machine. Substitute a real TrueType/OpenType file on your system. Native mode returns an error if the adapter or font is unavailable; it does not silently become a headless demo. For the portable core without native dependencies: ```sh cmake -S examples/composed_apps -B examples/composed_apps/build-headless -G Ninja -DCUI_BUILD_NATIVE=OFF cmake --build examples/composed_apps/build-headless --target northstar test_composed_app examples/composed_apps/build-headless/test_composed_app examples/composed_apps/build-headless/northstar --headless --page overview examples/composed_apps/build-headless/northstar --headless --page pricing --width 390 --height 844 ``` Headless mode builds actual CUI layout/render commands. The separate interaction test drives actual pointer, keyboard, text and scroll events and asserts application state. Headless execution does not open or validate a native window. ## What works - **Navigation:** a real CUI sidebar menu switches Overview, Plans & billing and Settings. The hamburger hides/restores the desktop sidebar. Below 760 logical pixels, navigation starts hidden and the hamburger reveals it below the header; selecting a page closes it. It is an inline panel, not an overlay drawer. - **Account:** the real account popup offers workspace settings and a local demo sign-in/sign-out command. Its desktop label reflects the saved display name; narrow layouts use a compact Account label. Popup dismissal and keyboard navigation come from CUI. - **Overview:** a hero CTA opens pricing, metric cards stack on narrow content, and Personalize workspace opens settings. Metrics are explicitly sample data. - **Pricing:** three cards show Starter, Team and Studio. Selecting a plan changes state, updates the selected CTA, displays confirmation and dispatches a callback. Re-selecting the current plan does not dispatch another change. Cards stack when content width is below 720 logical pixels. - **Settings:** a CUI form associates the required name with a real text editor; checkbox and switch retain preferences. Save rejects an empty or ASCII whitespace-only name, stores the accepted name in session state and dispatches a save callback. Invalid saves leave the previous saved name intact. - **Scrolling:** CUI scrollable content keeps stacked cards and forms reachable. Tracks hide when the authored page extent fits the current viewport. ![Northstar desktop pricing](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/composed_apps/screenshots/pricing-desktop.png) ## Copy the scene into your own host The [scene header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/composed_apps/app.h) contains only public CUI and standard C types. SDL and font adapters live in [main.c](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/composed_apps/main.c). [app.c](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/composed_apps/app.c) owns the application state and composition: ```c #include "app.h" static void changed(void *user, app_event event, app_snapshot state) { (void)user; if (event == APP_PLAN_CHANGED) { /* Dispatch your application's plan workflow using state.plan. */ } if (event == APP_SETTINGS_SAVED) { /* Persist state.saved_name, state.notifications and state.sync. */ } } composed_app *app = composed_app_create(changed, NULL); /* Check app and your cui_context allocation before continuing. */ cui_begin_frame(ui, width, height, dt); composed_app_scene(ui, app, width, height); cui_draw_list commands = cui_end_frame(ui); /* Render commands now, before another frame or app destruction. */ ``` `composed_app_frame` combines begin, scene submission and end for a standalone host. Use `composed_app_scene` when embedding into your own frame or gallery. It builds a full-window shell using the width/height supplied by the host; provide a context viewport matching that shell. Stable `APP_*` control IDs in the header support testing and automation. Use one instance per context: the IDs are intentionally fixed rather than namespaced for multiple side-by-side instances in the same context. Callbacks run synchronously during control submission on the UI thread. They receive a read-only snapshot; its strings borrow application storage and can change on the next interaction. Copy strings before retaining them. Do not recursively submit a frame or destroy the app/context from a callback. Destroy the app with `composed_app_destroy` after the renderer has consumed its last draw list. The host owns CUI context, font and backend destruction separately. To follow a host application's selected theme, copy its theme into the scene before submitting the frame: ```c cui_theme selected = cui_theme_dark(); composed_app_set_theme(app, &selected); /* selected may now go out of scope: color/metric values were copied. */ composed_app_scene(ui, app, width, height); ``` Call the setter between frames on the UI thread. Calling it every frame is supported; it preserves the selected plan, editor/preferences, session and keyboard focus. `composed_app_set_theme(app, NULL)` restores Northstar's default native palette. Pointer-valued icon hooks and their user storage remain owned by the host and must retain the lifetimes required by CUI; copying the theme does not copy data behind those pointers. Cards and the header use `theme.surface`, the document uses `theme.background`, and scene ink, borders and controls follow the supplied theme. The hero and feedback panels derive subtle tints from its palette. The navy navigation rail intentionally keeps its own readable light ink across themes. Light, dark, high-contrast and terminal themes run through the complete interaction test; representative header/hero/card ink contrast, keyboard focus paint, copied-theme storage and live theme switching are also checked. These are targeted checks, not a claim of a comprehensive accessibility audit. ![Northstar with a dark host theme](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/composed_apps/screenshots/overview-dark.png) To restyle the demo further, edit the `sidebar` composition and page render functions. To connect it to production data, replace the sample metrics and implement authentication, billing and persistence in your application layer. The sample callback is the integration boundary. ## Native captures and interaction validation Linux/X11 native captures were inspected for all three pages at 1200×900 and 390×844. The screenshots in this folder were produced by the actual SDL3 host, not a browser recreation. A bounded native capture is reproducible: ```sh FONT=/usr/share/fonts/noto/NotoSans-Regular.ttf TMPDIR=/your/writable/cache timeout 15 xvfb-run -a -s '-screen 0 1600x1200x24' \ examples/composed_apps/build/northstar --font "$FONT" --page pricing \ --frames 3 --capture examples/composed_apps/build/pricing.bmp ``` Set `TMPDIR` to an existing writable directory when `/tmp` space is constrained. Omit `TMPDIR=...` when your default temporary directory has sufficient space. Capture requires a positive `--frames` count and a native backend. It writes the last bounded frame to BMP; zero frames runs interactively until window close. The native interaction check uses xdotool to choose Team, sign in through the account menu, navigate to Settings, type Grace Hopper, change both preferences, save and sign out. It asserts the resulting callback log and saves the final native frame: ```sh TMPDIR=/your/writable/cache timeout 20 xvfb-run -a -s '-screen 0 1600x1200x24' \ examples/composed_apps/native-check.sh "$FONT" ``` The explicit Xvfb screen size matters: the default 1024×768 display would clamp pointer coordinates for a 1200×900 application window. The check rejects a display smaller than the window. Its fixed coordinates are specific to this scene and the validated font; adapt them if changing layout/font metrics. Artifacts appear in `build/native-interactions.log` and `build/native-interactions.bmp`. ![Native settings after editing and saving](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/composed_apps/screenshots/settings-saved-desktop.png) ### Scrolling in an embedding or browser host Narrow pricing cards stack vertically. Team (`APP_PLAN_TEAM`, 131) and Studio (132) may start below the viewport; this is expected. CUI retains their raw semantic bounds, but hit geometry is clipped to the document viewport. A host that exports only visible controls may omit those IDs until you scroll. Do not click stale offscreen centers or assume all three CTAs are immediately visible. Route scroll input to a point inside `APP_CONTENT` (150), rather than the header, sidebar or an open account menu. For a pixel-based host such as DOM wheel input: ```c cui_rect content = cui_bounds(ui, APP_CONTENT); cui_queue_event(ui, (cui_event){ .type = CUI_EVENT_SCROLL, .x = content.x + content.w / 2, .y = content.y + content.h / 2, .dy = -192, /* Negative moves the document downward. */ .scroll_precise = true /* Logical pixels, not wheel ticks. */ }); composed_app_frame(ui, app, width, height); /* Re-read current bounds/visible semantics; repeat until the CTA is visible. */ ``` For DOM `deltaMode == DOM_DELTA_PIXEL`, map positive `deltaY` to negative CUI `dy` and account for CSS-to-logical-pixel scaling in coordinates/deltas. With `scroll_precise == false`, deltas are wheel units: `dy = -1` moves this scene 48 logical pixels downward. Feeding pixel deltas as nonprecise units multiplies them by 48 and usually jumps straight to the end. Re-read bounds after rendering the scrolled frame before dispatching pointer down/up. The real vertical scrollbar is `cui_scrollbar_id(APP_CONTENT, true)` from `cui/cui_scroll.h`. It exposes current value/minimum/maximum in its semantic record, supports pointer dragging, and supports Home/End/PageUp/PageDown when focused. Its End key reveals the last Studio CTA. Tests exercise precise wheel reveal/click of Team, scrollbar-keyboard reveal/click of Studio, reverse pixel scroll and exact wheel-unit movement for all four themes at both 390×844 and 360×420. No scene-specific browser scrolling API is required. ### Reproduce native host-theme validation The optional native audit driver lives in `test_app.c` behind `APP_THEME_NATIVE`; ordinary CTest stays portable. Build it explicitly after the native example build above: ```sh EXAMPLES=examples/composed_apps cc -std=c11 -Wall -Wextra -Wpedantic -Werror -DAPP_THEME_NATIVE \ -Iinclude -I"$EXAMPLES" "$EXAMPLES/app.c" "$EXAMPLES/test_app.c" \ "$EXAMPLES/build/cui-build/libcui_sdl3.a" \ "$EXAMPLES/build/cui-build/libcui_text.a" "$EXAMPLES/build/cui-build/libcui.a" \ $(pkg-config --cflags --libs sdl3 freetype2 harfbuzz) -lm \ -o "$EXAMPLES/build/test_theme_native" ``` The driver accepts `--native FONT light|dark|contrast|terminal OUTPUT_DIRECTORY`. It runs a bounded 1200-frame window that closes after the verified workflow settles, captures each visited page and its final frame, prints measured control centers for automation, and returns success only if the native interactions produced Team selection, sign-in/out and one saved Grace Hopper profile with notifications off and sync on. The following helper uses the measured centers rather than fixed per-theme coordinates: ```sh cat > "$EXAMPLES/build/theme-check.sh" <<'SH' #!/bin/sh set -eu font=$1 theme=$2 example_dir=$(pwd)/examples/composed_apps "$example_dir/build/test_theme_native" --native "$font" "$theme" "$example_dir/build" \ >"$example_dir/build/$theme-theme.log" 2>&1 & client=$! sleep 0.8 window=$(xdotool search --name '^Northstar / theme audit$') xdotool windowfocus "$window" click() { line=$(rg "^bound id=$1 " "$example_dir/build/$theme-theme.log" | tail -1) x=$(printf '%s\n' "$line" | awk '{sub("x=","",$3); print $3}') y=$(printf '%s\n' "$line" | awk '{sub("y=","",$4); print $4}') xdotool mousemove --window "$window" "$x" "$y" click 1 sleep 0.6 } click 120 # Overview CTA opens pricing. click 131 # Choose Team. click 101 xdotool key --window "$window" End Return # Sign in. sleep 0.6 click 112 # Settings navigation. click 140 xdotool key --window "$window" ctrl+a xdotool type --window "$window" --clearmodifiers --delay 5 'Grace Hopper' sleep 0.6 click 141 click 142 click 143 click 101 xdotool key --window "$window" End Return # Sign out. wait "$client" rg '^native event=' "$example_dir/build/$theme-theme.log" SH for theme in light dark contrast terminal; do timeout 30 xvfb-run -a -s '-screen 0 1600x1200x24' \ sh "$EXAMPLES/build/theme-check.sh" "$FONT" "$theme" || break done ``` Run from the repository root and set `TMPDIR` if needed as described above. The helper assumes the validated font and Linux tools. It waits briefly for window creation and bounded frame progress; slower machines may need longer waits/timeouts. Each theme writes `-overview.bmp`, `-pricing.bmp`, `-settings.bmp`, `-settings-saved.bmp` and `-theme.log` in the build directory. Actual native workflows passed for all four themes; committed light/dark PNGs show the captured SDL frames. ## Scope and limits The scene's state is local and in memory. Demo sign-in does not authenticate, plan selection creates no subscription or payment, and save does not write a file or server. Notification/sync toggles record preferences without performing those services. Closing the app resets its state. Prices and activity metrics are illustrative, not an external product offer or telemetry feed. Native operation and actual interaction were validated on Linux with SDL3 3.4.18, FreeType/HarfBuzz and Noto Sans under Xvfb. Physical displays, Wayland, Windows and macOS have not been validated by this example. It uses CUI controls painted into an SDL desktop window, not operating-system-native widgets. Regular font shaping works; additional bold/italic font faces can be registered by an embedding host for stronger typography. No claim of complete component or platform parity is implied. Page scroll extents are explicit scene estimates, chosen for this sample's content and responsive breakpoints. Update those estimates alongside page content or font changes; they are not an automatic document measurement system. Name validation only rejects empty/ASCII-whitespace-only names and the editor limits storage to 79 UTF-8 bytes; it is not a full identity validation policy. --- ## Semantic alerts, bubbles and table rows Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CONTENT_STYLING.md # Semantic alerts, bubbles and table rows Alerts select Info, Success, Warning or Error using `cui_alert_options.kind`. The theme provides independent `info`, `success`, `warning` and `danger` colors; the border and default SVG icon follow that color. Set `icon_name` to another named SVG or supply the legacy `icon` text override. The gallery demonstrates all four kinds, with a controlled, dismissible success alert. Composable bubbles support `CUI_BUBBLE_INFO`, `CUI_BUBBLE_SUCCESS`, `CUI_BUBBLE_WARNING` and `CUI_BUBBLE_ERROR`. Each uses a tinted theme color. Compose arbitrary children between `cui_begin_bubble` and `cui_end_bubble`. Static Table rows can provide their own background independently of header semantics. This example alternates application-owned row colors: ```c cui_table_begin(ui, table_id, &theme, 480); for (unsigned row = 0; row < 4; row++) { cui_table_begin_row_ex(ui, table_id + row + 1, &theme, (cui_table_row_options){ .height = 40, .header = row == 0, .custom_background = true, .background = row == 0 ? theme.accent : row % 2 ? theme.surface : theme.background}); /* Compose your cells with cui_table_begin_cell / cui_table_end_cell. */ cui_table_end_row(ui); } cui_table_end(ui); ``` Choose foreground colors appropriate to a custom background. The existing `cui_table_begin_row` retains its previous default behavior. A DataTable has its own options and row callback contract; this API applies to the composable Table. The headless tests verify distinct semantic colors and actual row drawing in both light and dark themes. These options do not imply complete component parity. --- ## Contextual native text Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CONTEXTUAL_NATIVE_TEXT.md # Contextual native text Core text commands retain the original paragraph and a half-open UTF-8 byte range for the selected visual line. Native software, SDL3, SDL GPU and Sokol renderers use that context for bidi analysis. A wrapped line beginning with numbers or punctuation therefore keeps the direction of its original paragraph. This change preserves Clay's existing wrap choices; it does not implement UAX14 line breaking or visual arrow navigation. ## Portable interfaces `cui_text_line_source` contains `paragraph`, `byte_start` and `byte_end`. Endpoints are paragraph-relative UTF-8 scalar boundaries. Hard paragraph separators are excluded. U+2028 remains inside the paragraph: native drawing splits its physical lines while retaining the shared bidi context. A geometry factory request selects one physical line and cannot include U+2028 in its range. `cui_text_context_line` copies a paragraph and submits a selected line. `cui_text_context_line_colored` additionally copies sorted, nonoverlapping color spans, also in paragraph-relative bytes. Colored submission selects one physical line and rejects a range containing U+2028. There are at most `CUI_TEXT_COLOR_SPAN_MAX` (4096) spans. A shaped cluster takes the color at its first original byte; a color boundary inside a ligature or combining cluster does not split shaping. Both submission functions return false on invalid input or capacity failure. Capacity reports `CUI_ERROR_CAPACITY`; failure does not consume frame bytes or submit an element. Ordinary `cui_text` wrapping also retains provenance. Core records submissions in an array bounded by `max_elements`, resolves Clay's exact `baseChars` pointers, and copies text into `frame_bytes`. It does not search for matching substrings. Contextual lines share paragraph storage but have unique slice storage, so repeated text and equal-start/different-end ranges remain distinct. CRLF suffixes retained by Clay are removed from the visible line without changing the original paragraph boundaries. Draw descriptors and color spans have the same lifetime as the draw list: consume them before the next frame or context destruction. Any renderer retaining commands must deep-copy their paragraphs and spans. ## Native host setup Add the range factory to a native font configuration: ```c cui_config config = { .measure_user = font, .measure = cui_font_measure, .measure_styled = cui_font_measure_styled, .font_metrics = cui_font_get_metrics, .text_geometry = cui_font_text_geometry, .text_geometry_line = cui_font_text_geometry_line, }; ``` A measurement wrapper needs matching geometry wrappers sharing `measure_user`. `cui_get_text_geometry_line` preserves output on failure, checks the session metadata, and releases a partial failed session. Successful sessions are owned and immutable; release them once with `cui_release_text_geometry`. `byte_length` is the full paragraph length. Caret, hit and selection offsets are original paragraph-relative bytes, including when the selected line starts later. The native adapter translates validated byte endpoints to the existing scalar line-layout API. It retains shaped arrays and font faces, not the source buffer. The old factory contract is unchanged. When a range selects the entire paragraph, the helper can use the old `text_geometry` factory. Other ranges require `text_geometry_line`; unavailable geometry uses the legacy measured editing path. BIDI-off native factories return UNAVAILABLE. Ordinary contextual drawing retains legacy BIDI-off drawing; colored contextual drawing requires the optional native bidi implementation. Editor selects its established fragment path when visual geometry is unavailable. Browser renderers do not consume these native contextual/color descriptors in this batch. ## Multiline consumers and ownership Textarea row records include original paragraph boundaries and hard-line indices. Textarea and Editor share visual geometry for hits, caret x, preferred vertical columns, reveal, selection spans and composition underlines. Primary pointer-selected bidi affinity survives idle frames. The final IME rectangle comes from the actual painted caret child's bounds after layout, including when its blink is invisible. Logical editing offsets and keyboard motion keep their existing policies; secondary Editor cursors do not gain persistent dual bidi affinity or visual navigation. One context resource caches at most 64 requested line sessions and 1 MiB of unique paragraph bytes per frame. Visible rows and requested navigation rows are created lazily; identical paragraph/range/style requests share a session. Queries outside a frame use a temporary owned session. Beginning a new frame releases cached sessions/source copies, observing host font registrations and metrics changes. Source changes within a frame create a new immutable session. Capacity, allocation, unavailable and unsupported-boundary failures retain the measured fallback. Styled `cui_textarea_result.visual_error` reports the first visible-line factory failure separately from edit/layout errors. For a configured visual host, an active composition also retains one exact preedit snapshot per state in a context resource, bounded to 65,535 bytes. Unchanged composition reuses row layout across idle frames. Its resource owns and frees the snapshot; caller state receives no allocation handle or cleanup duty. Omitted resources and context destruction clean up ownership. Model identity is compared without dereferencing a previous model. Rebinding to a different model invalidates cached rows. Reinitialize state before destroying and replacing a model at the same address; Editor's borrowed model must outlive its state. Caller row arrays must remain alive and must not be shared by widgets. Editor shapes each highlighted contextual line once, then supplies at most 64 color spans. Excessive spans report `CUI_TEXTAREA_CAPACITY` and paint a plain contextual line. Gutter line indices are cached during row layout; gutter paint visits visible rows, and digit-width counting refreshes on model revision. Long individual paragraphs still require paragraph analysis for each selected native line; this is not an incremental native paragraph-analysis cache. Host measurement, geometry and raster calls are UI-thread confined. Keep host font/style registrations consistent through draw-list consumption. After an external metrics change, call `cui_text_metrics_changed` before the next frame. No GDEF interior-ligature caret, cross-run grapheme, OS font discovery, bidi visual arrow, or complete international editing parity is claimed. Prefix fallback is not claimed visually correct for unsupported interior-cluster boundaries. ## Validation and integration `tests/unit/test_contextual_text.c` exercises malformed UTF-8/ranges, duplicates, CRLF provenance, frame ownership, copied colors, atomic capacity failures, immutable cached sessions, exact cleanup and the 64-session bound with a 200 KB paragraph. `tests/integration/test_contextual_text.c` uses actual Noto Sans plus explicit Hebrew/Arabic fallbacks. It checks RTL caret/hit/selection geometry, rendered selection pixels, wrapped punctuation raster hashes, U+2028 context, Editor cluster colors and software-rendered pixels, pointer affinity through idle frames, IME update/cancel/commit/Undo, retained sessions after source/font changes, and a document over 200 KB with bounded idle viewport/composition work. Missing font/bidi fixtures return 77; missing-glyph raster never counts as success. The portable unit target links `cui`. The native integration target links `cui`, `cui_text`, and `cui_software` (with native text enabled), and should use CTest's skip-return-code 77. Root CMake registration and distribution regeneration are integrator-owned. The older audit's standalone `cui_font_draw_styled` call intentionally bypasses descriptors; use the new contextual test for the actual renderer path rather than treating that legacy call as contextual rendering. --- ## ContextMenu command notifications Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CONTEXT_MENU_EVENTS.md # ContextMenu command notifications `cui_base_context_menu_events` and `cui_context_menu_events` add synchronous per-command observation to the existing Base and Styled ContextMenu. They use the unchanged `cui_menu_command_handler`, payload and result from [MenuTree events](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MENU_EVENTS.md). Legacy ContextMenu entry points retain their behavior. Simple Menu and DropdownButton forwarding are separate, pending slices; this does not establish uniform component or binding coverage. ```c static void selected(void *user, const cui_menu_command *event) { cui_id *last_command = user; *last_command = event->command; } /* During the existing frame, after submitting the receiving target: */ cui_menu_command_result result = cui_context_menu_events( ui, receiving_target, &theme, cui_string("Actions"), entries, entry_count, &action, &menu, options, (cui_menu_command_handler){selected, &last_command}); ``` The Base form takes the legacy Base arguments followed by the handler: `ui, target, entries, count, action, state, disabled, dt, keep_open_checks, handler`. It reduces without drawing; Styled retains the existing popup layout and painting. Call either facade once for a given submission, rather than calling the legacy reducer as well. Right-click opening, reanchoring and programmatic `cui_context_menu_open` emit no command notification. The original receiving bounds, popup-scope checks, anchor, focus restoration and opening order remain intact. `event.target` is the public receiving target, even if `state.overlay.trigger` restores focus to another control. `command` is the activated leaf ID, including nested leaves. Each actual MenuTree command forwards exactly once at its existing commit seam, after action output, check/radio writes and close policy. Repeated keep-open commands remain separate notifications, including a return to the initial checked value. Closing-command exit policy is frozen before observation. `legacy_activated` preserves the aggregate bool; `command_count` counts actual handler invocations, so a missing handler yields zero while normal mutations still occur. `valid`, `submitted` and overflow semantics are those of MenuTree, including inert/layout-only suppression. Metadata kind is ACTIVATE. Genuine pointer/touch, keyboard and supported menu accessibility events retain their source/frame/index evidence. MenuTree's reducer precedes current semantic registration, so the normal path has no copied activation snapshot; no opening event, focused target or programmatic action is converted into invented activation evidence. Copied pointer-free payloads survive the callback, frame and context lifetime. Handlers may update caller-owned values or consume later input under the existing reducer rules. Payload/handler arguments are borrowed synchronously; active descriptors, child arrays, state, values and user storage must remain alive through submission. Direct mutation of in-flight menu navigation, freeing active storage, recursive submission and context destruction inside dispatch remain unsupported. Schedule removal or shutdown after submission/frame completion. Notifications cannot veto applied mutations and do not introduce open/close callbacks, queues or callback retiming. [test_context_menu_events.c](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_context_menu_events.c) exercises Base and Styled with distinct receiver/restore-focus identities, real right-click opening/reanchoring, repeated accessibility check commands, nested keyboard activation, mouse/touch, missing observers, owner updates, later-input consumption, disabled/inert/omitted calls, modal rejection and copied lifetimes. Existing `test_choice` remains the legacy behavior regression suite. Native tests run only through the invisible-display wrapper: ```sh python scripts/test_local.py --build-dir build -- -R '^(context_menu_events|choice)$' ``` The integrator registers the new fixture in CMake and distribution/documentation exports. No binding facade or parity promotion is included. --- ## Controlled sibling audit Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CONTROLLED_SIBLING_AUDIT.md # Controlled sibling audit This audit began at base `513883e` (integration/next17). It exercises real frame/event routing, caller-owned values, completed-frame semantics, and actual draw commands. The follow-up fixes ListMulti callback forwarding in the base reducer. The default audit now passes; `--radio` separately preserves the known Radio regression. CMake registration remains the integrator's responsibility. ## Confirmed defects 1. **Fixed: ListMulti confirmation/cancel callback user pointer.** Previously, `cui_base_list_multi` replaced `options.activation_user` with its private stack reducer to intercept `on_activate`, while forwarding the caller's `on_confirm` and `on_cancel` callbacks unchanged. Both received the private reducer pointer instead of the caller's user object. All three callbacks now use trampolines that preserve the original user pointer. The original defect was at `src/base/cui_choice.c:1006` in the audited base. A callback which writes through its expected owner pointer could corrupt the reducer or adjacent stack memory. The regression safely compares pointers without dereferencing the unexpected pointer. It covers accept and restore/reject policies, confirmation order/count, Escape, and idle frames. The registered Choice suite additionally writes final selection through the actual owner object from confirmation and cancellation callbacks and verifies final completed-frame semantics. Disabled paths emit no notifications. 2. **Remaining: Radio publishes stale earlier-sibling semantics.** Render radio option0 followed by option1 sharing one `int *`, initially 0; click option1. The owner value becomes 1, but the completed frame reports both radios as checked. Only the newly activated radio's semantic is refreshed by `cui_base_radio` (`src/base/cui_base.c:156`). Accessibility consumers can observe mutually exclusive controls simultaneously selected. The source explicitly schedules a repaint for earlier siblings; that next event-free frame correctly reports only option1. The draw list also contains both selected indicators in the activation frame and only one after that natural corrective redraw. The regression fails on stale completed-frame semantics; it records existing delayed-paint behavior without claiming paint can be retroactively rebuilt by the per-radio API. The original audit reported five failing observations across these two defects. The default executable covers the fixed ListMulti behavior and other passing controls; `--radio` still reports one failure. No Radio production change is included in this follow-up. ## Covered behavior and API limits | API | Actual external-owner scenario | Observation | | --- | --- | --- | | List | `on_activate` replaces selection or restores the original selection | Final same-frame semantics and subsequent render callback see the final owner value; callback runs once. | | ListMulti | `on_activate` replaces the full boolean array, including the earlier sibling, or restores it | Final same-frame semantics and actual checkmark location follow the owner array; callback runs once. Confirmation/cancel preserve the caller user pointer after the fix. | | Radio | Later option changes the shared integer | Earlier semantic stays checked until scheduled redraw, as above; disabled option does not change the value. | | Checkbox | Individually caller-owned booleans | Completed-frame semantics match both independent values; disabled item is inert. There is no dedicated CheckboxGroup or change-request callback API in this snapshot. | | Tabs | Later tab changes the shared stable ID | Earlier and later semantics reflect final selection in the activation frame. | | Tree | Later row changes the shared node ID | Final semantics are correct in the activation frame and repaint is scheduled. | | Stepper | Later item changes the shared index | Final semantics are correct; one actual `Current` label is painted; repaint is scheduled. | | MenuTree radio entries | Later entry changes the shared integer while popup stays open | Both sibling semantics reflect final selection in the activation frame; disabled entry is inert. | List callbacks are synchronous notifications after the reducer writes selection, not dedicated cancellable requests. An owner can restore selection inside the notification, which this suite tests. Radio, Checkbox, Tabs, Menu, Tree and Stepper do not expose selection-request callbacks; the suite does not invent a rejection contract for them. Custom content/render callbacks are not treated as controlled change callbacks. No cross-widget retroactive repaint or arbitrary owner-state tracking is claimed. List, ListMulti, Tabs and MenuTree complete their same-group state/paint in the activation frame and do not request another corrective frame in these fixtures. The audit records this rather than requiring unnecessary redraws. An event-free host repaint is also exercised to verify stable state and no duplicate callbacks. Radio's explicit corrective redraw is checked before that event-free frame. All fixtures use public APIs; disabled controls and disabled list items are exercised through actual routed pointer events. ## Reproduction From the isolated checkout: ```sh cmake -S . -B build -G Ninja cmake --build build cc -std=c11 -Wall -Wextra -Wpedantic -Werror -Iinclude \ tests/unit/test_controlled_siblings.c build/libcui.a -lm \ -o /tmp/cui-controlled-siblings /tmp/cui-controlled-siblings /tmp/cui-controlled-siblings --radio # intentionally fails for the known Radio gap ctest --test-dir build --output-on-failure ``` The default audit returns 0; the separate Radio diagnostic returns 1. The existing CTest suite does not yet register this new audit. The Choice suite's notification regression is registered through its existing target. A sanitizer build of `cui` and both audit selections exercises all cases. Validation: warnings-as-errors compilation passes. The existing CTest suite passes 90/91; its only failure is `distribution`, because `dist/cui_choice.h` needs regeneration after the base reducer fix. Distribution output belongs to the integrator. The audit passes by default, and `--radio` preserves its one expected failure. ASan/UBSan pass the default audit and registered Choice suite without runtime errors. --- ## Button and Check event facades Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CONTROL_EVENTS.md # Button and Check event facades `cui_control_events.h` and the Styled declarations in `cui_components.h` add typed synchronous event facades for Button and Checkbox/Check. Existing entry points keep their behavior. [Switch/Toggle facades](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BOOLEAN_EVENTS.md) are also implemented; group controls and language request bindings remain deferred; this is not uniform coverage of all 78 families. See the [design checkpoint](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_CONTRACT.md), [coverage inventory](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_COVERAGE.md) and [binding limitations](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_BINDINGS.md). ## Controlled Checkbox requests The value is an immutable entry snapshot. The application accepts by assigning its own value, or rejects by leaving it unchanged. Subsequent events, painting and semantics in this invocation still use the entry snapshot; the next submission observes accepted owner state. No notification of an external assignment is synthesized. ```c #include typedef struct { cui_check_state checked; bool allow_changes; } account_state; static void request_check(void *user, const cui_component_check_request *request) { account_state *account = user; if (account->allow_changes) account->checked = request->requested; } static cui_component_action_result account_checkbox(cui_context *ui, cui_id id, const cui_theme *theme, account_state *account) { return cui_checkbox_events(ui, id, theme, cui_string("Receive updates"), account->checked, (cui_checkbox_options){0}, (cui_component_check_handler){request_check, account}); } ``` `cui_component_check_request` contains typed `current` and `requested` states plus `event` metadata with kind `REQUEST`. Unchecked or mixed requests checked; checked requests unchecked. Every accepted activation produces a separate request from the same entry value. Two activations in one submission therefore propose the same next value, even if the first is accepted. Missing handler is read-only: no value write and zero requests, although accepted activation attempts are still counted. `cui_base_check_events(ui, id, name, value, options, handler)` supplies drawing-free behavior inside a caller box with the same ID. Base preserves `cui_check_options.no_pointer_focus`; Styled `cui_checkbox_events` selects source Checkbox behavior, preserving existing focus on pointer activation. Keyboard tab/focus policies, role overrides, required/invalid metadata, indicator/style slots and motion remain the existing Checkbox policies. Omitted options default as before except that these new by-value entry points are always controlled. Old `on_change` and `change_user` must both be NULL; conflicting handler configuration fails preflight rather than being ignored or dispatched twice. ## Button activation `cui_button_events(ui, id, theme, name, options, handler)` uses `cui_component_activation_handler` with a callback `(void *user, const cui_component_event_metadata *event)`. Its event kind is `ACTIVATE`, not value change. A missing new handler still reports accepted activation counts. Legacy options remain usable for migration. Existing hover processing precedes click dispatch. Per accepted event the order is legacy `on_click`, old `on_click_event`, then the new handler, followed by existing paint/tooltip work after iteration. Existing click evidence is frozen before the legacy callback; a callback consuming accessibility input does not erase evidence delivered to the new handler. Original `options.action_user`, including hover, stays separate from the new handler's user. Prefer one callback or frame-result path for each side effect; performing the same action from both dispatch and result duplicates it. ## Results and lifecycle `cui_component_action_result` contains: | Field | Meaning | | --- | --- | | `valid` | Arguments/options passed preflight; later Core/paint errors remain possible. | | `submitted` | Ordinary active submission reached, including disabled controls; false outside submission or in inert/layout-only ancestry. Passive visuals may still compose. | | `activation_count` | Accepted activations observed by this invocation. | | `request_count` | Check request callback invocations; zero for Button. | | `count_overflow` | A count saturated at `SIZE_MAX`; dispatch continues in event order. | Results aggregate one invocation; copying/reading a result never dispatches or mutates a value. Counts do not report owner acceptance. Disabled/inert controls emit no user callbacks. Button loading also suppresses activation; Checkbox gains no loading state. Missing/omitted immediate calls emit nothing. No COMMIT, SUBMIT, CHANGE, propagation control or default-prevention promise is added to these discrete APIs. Payload/handler/user are borrowed through synchronous submission only. Metadata and Check request structs are pointer-free and copyable by value, including beyond frame/context lifetime. Appearance strings, icon resources and caller state retain their existing boundaries; some paint resources must live through renderer completion. [Shared metadata](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMPONENT_EVENTS.md) explains real input evidence, absent fields, context-local identities and safe copying of other borrowed UTF-8 payloads. Copying an arbitrary `cui_event` is not a text deep copy. Callbacks may update unrelated application state and the external value owner. Changing a caller descriptor affects a later invocation, not the copied descriptor in flight. Consuming later input can change its later eligibility; callbacks are not prequeued. Request view removal or application shutdown in application state, then perform removal/freeing/teardown after the active submission and frame finish. Do not recursively submit the same component/frame, destroy the active context, or free active users/state/resources during dispatch. **There is no runtime context-destruction guard** in this slice. Bridge runner deferred destruction does not imply such a Core guarantee. The header's `cui_control_events_private_*` identifiers are forwarding implementation details, not application entry points. No allocation, registration, worker, scheduler, Core event routing or backend changes are introduced. New source APIs are not automatically exposed by existing SDK/binding event queues. The integrator owns module registration, generated distributions/API indexes and consumer human/LLM resources. The focused `tests/unit/test_control_events.c` covers per-event legacy/new order and users, pointer/touch/key/accessibility evidence, rejected and accepted owners, immutable multi-request snapshots, next-submission semantics, read-only/missing handlers, Base versus Styled focus, disabled/loading/passive suppression, invalid handler conflicts, outside-frame calls and saturation bookkeeping. Existing Button and Checkbox suites remain compatibility checks. Run registered tests without desktop windows: ```sh python scripts/test_local.py --build-dir build -- -R 'control_events|button_click|button_callback|checkbox_source' ``` ## Run a complete native example The [settings example](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/control_events/README.md) builds a real SDL window with an owner-controlled Checkbox, an Apply button and deferred panel removal. It demonstrates acceptance and rejection, passive result inspection without duplicate side effects, and the next-submission snapshot boundary. Its README includes exact dependency, compiler, font, build and invisible-test commands. The separate [async fetch example](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/async_fetch/README.md) demonstrates returning promptly from a synchronous handler and applying worker completions on the UI thread. --- ## Core contract and limits Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CORE.md # Core contract and limits The core uses the pinned Clay implementation for sizing and draw generation. Public APIs contain C11 types only. Calls run on one UI thread; contexts may be interleaved, including open frames, because each layout operation selects its owning Clay context. Concurrent calls are unsupported. Queue input before `cui_begin_frame`. Events resolve in order against enabled interactive regions from the preceding completed frame, intersected with ancestor clips. The first frame has no input targets. Pointer down captures and focuses the topmost submitted hit region; release activates only inside that same region. Cancel and Escape clear pointer and space captures. Tab and Shift+Tab follow previous submission order. Enter activates on non-repeated key down; Space activates on key up when its captured focus remains current. Repeated key downs do not activate. Disabled controls suppress pending activation; disabled and omitted controls lose focus and capture by frame end. `cui_event_target` reports the target at dispatch time, allowing controls to process multiple down/move/up or focus/text events in a single frame. Key events target the focus before that event; pointer move and up target capture. `cui_interact` reports final held state and consumes pending activation once. Multiple queued activations for one control are coalesced to its boolean activation. `cui_update_semantic` updates a submitted controlled value after a same-frame change. Text and semantic names are copied to the fixed frame string arena; draw lists and semantic names survive until the next begin. The default text measure uses approximate width `length * font_size * 0.6` and height `font_size * 1.3`; applications needing font metrics supply the callback. Draw conversion supports rectangles, per-edge borders, text, RGBA bitmaps, and clip push/pop. Unsupported Clay draw types are not exposed by the public composition API. The configuration defaults to 4096 elements, 8192 commands, and 262144 string bytes. There are at most 256 queued events, ID scopes, and nested boxes. Capacity failures set a sticky error. String exhaustion produces empty strings. Command exhaustion returns an empty list to avoid exposing unbalanced clip commands. Skipped elements remain safely balanced by matching end calls. Errors can be explicitly cleared after inspection; frame lifecycle errors reject invalid transitions. IDs use scoped 64-bit FNV hashing. Nonzero element IDs and semantic IDs must be unique within a frame. Clay internally receives a domain-mixed 32-bit ID; consecutive raw public IDs are avalanched before Clay derives its automatic text IDs. Distinct public IDs with equal internal IDs are reported as duplicates rather than silently aliased. ID zero creates an anonymous box and is not an interactive control ID. Semantic controls should be submitted inside their matching element box so clipped hit regions can be established. Bounds returned during submission refer to the previous completed frame; completed semantic bounds reflect the current layout. Headless tests cover input ordering, first-frame input, reordered IDs, capture and cancellation, focus traversal, keyboard activation, disabled and omitted controls, string ownership, draw conversion, clipped hit testing, context interleaving, duplicate/scoped IDs, lifecycle errors, and capacity recovery. This is the core interaction and composition contract, not a claim of complete shadcn component parity. Focus scopes are explicit, independently nested declarations. A successful `cui_begin_focus_scope` must be paired with `cui_end_focus_scope`; failed begins must not be ended. At most 256 scopes can be declared per frame. The last declared modal scope is active, including nested scopes; enabled descendants receive initial focus by frame end. On the next input dispatch, Tab traversal and pointer hit testing are restricted to its descendants. Pointer down outside an active modal targets the scope ID without activating the underlying control. Escape targets the focused control's innermost scope, or the last declared scope when focus is outside all scopes; this also supports nonmodal popup dismissal. Nonmodal scopes alone do not restrict traversal or pointer routing. Omitted scopes stop trapping after the frame completes. `cui_focus_restore` checks that a trigger appeared as an enabled interactive semantic in the previous completed frame. It permits restoring a trigger while its former modal scope is being omitted. The completed frame clears focus if that trigger is now disabled or omitted, and an active current modal still enforces its own descendants. Scope IDs should be distinct from interactive control IDs when their dismissal events must be distinguished. These APIs provide routing and focus state; overlays own visibility, panel bounds, outside-dismiss policy, placement, and rendering. ## Floating layers and compound controls `cui_begin_portal` opens a viewport-positioned box outside ancestor clipping and normal layout flow. Positive layers sort painting and interactive hit regions by layer, with later submitted regions winning ties. Close it with `cui_end_box`. Portals can clip their own content. Bounds must be finite and nonnegative; a malformed portal suppresses its subtree while preserving paired begin/end calls, even at the nesting budget. A portal does not itself trap focus: use a modal focus scope where appropriate. Passive portal content lets pointer events pass through; an active modal scope blocks underlying interactive controls. `cui_set_semantic_details` records expanded/selected/read-only/required/invalid state, numeric ranges, descriptions and relationships independently of painting. Description strings are frame-copied. Group, tab-list/panel, list/menu, status, alert, image and other roles distinguish container/content from focusable controls. `cui_set_tab_stop(false)` removes an item from Tab traversal while preserving pointer/programmatic focus, so composite controls can use roving focus. `cui_event_activation` preserves each validated pointer-release, Enter or released-Space activation even after `cui_interact` consumes the aggregate flag. Compound reducers process this alongside events in input order, so ArrowDown then Enter selects the newly navigated item within one frame. Core target IDs still refer to dispatch-time previous-frame focus; reducers apply their local cursor. Call `cui_dismiss_focus_scope` after reducing closing popup behavior and before painting it. It withdraws current semantic descendants, deactivates nested traps, and restores an enabled previous-frame trigger. Paired scope begin/end calls remain required. This avoids briefly forcing focus back into a closing popup. Boxes expose portable `align_x`/`align_y` start, center and end values. They align children inside the available content area after sizing/padding; default start alignment preserves existing layout behavior. These are physical axes: `align_x` always means horizontal and `align_y` vertical, regardless of `row`. For a fixed or growing row, `.align_x = CUI_ALIGN_CENTER` centers the whole child group horizontally; `.align_y` aligns children vertically. For a column, `.align_y = CUI_ALIGN_CENTER` centers the group vertically and `.align_x` aligns children horizontally. Centering needs spare space on that axis: a FIT box or children that consume all available grow space leave none to distribute. `padding` is the uniform shorthand. Set `custom_padding` to replace it with `padding_edges` (left, right, top, bottom), preserving explicit zero edges. Negative/nonfinite edges normalize to zero and use integer layout units. Likewise, `custom_corners` replaces `radius` with `corner_radii`, and `custom_border_edges` replaces `border_width` with `border_edges`; custom zeros win over nonzero uniform values. `CUI_STR("literal")` is a brace initializer usable for static `cui_str` objects. Use `(cui_str)CUI_STR("literal")` in expressions. Length excludes the final NUL and includes embedded NUL bytes; use `cui_string` for runtime C strings. Clipped boxes accept `offset_x`/`offset_y` to translate children while preserving the box viewport and ancestor clips; negative offsets scroll content forward. Fractional offsets are retained. Secondary/middle pointer events carry `pointer_button`, hit-route to previous regions, and never change ordinary primary capture/focus/activation. SDL3 maps all three buttons. `cui_box.fixed_width` and `fixed_height` explicitly constrain a dimension, including exactly zero; without the flags, zero retains the existing FIT rule. Negative/nonfinite explicit dimensions normalize to zero. This supports collapsed viewports without a visible epsilon-sized remnant. `cui_box.layout_only` measures its complete subtree but suppresses paint, semantic nodes and routed input, including nested portals. Bounds tracking still works; callbacks still execute and applications must avoid unrelated side effects. Focus requests from the subtree are ignored; hidden modal scopes do not trap outside focus. Clipping commands remain balanced even when all enclosed paint is suppressed. This is useful for measuring a disclosure before animating its outer viewport. The application retains measured bounds through `cui_track_bounds`. `cui_box.inert` preserves layout and painting while suppressing semantics, hover, routed events, focus requests and modal scope effects throughout the subtree, including portals. It supports visible exit animations without leaving closing controls interactive. `layout_only` implies inert behavior and also suppresses painting. A hidden/inert subtree cannot dismiss an enclosing active focus scope. `cui_set_semantic_role` refines an already-submitted current-frame semantic node without replacing its name, state, range, parent or description. It rejects missing IDs, out-of-range roles and calls from inert subtrees. `CUI_ROLE_LINK` is focusable and participates in existing pointer/keyboard activation; the application owns navigation, so no platform URL opener is implied. Passive semantic nodes can set `details.focus_target` to a focusable control ID. A primary pointer down resolves that target before subsequent queued keyboard or text events are routed, including events in the same frame. Pointer events stay addressed to the passive node and do not capture/activate it or move the target's caret. Disabled, missing and modal-inaccessible targets are ignored. This supports input addons and labels without exposing them as extra buttons or Tab stops. `cui_focus_within(ui, scope_id)` checks actual focus-scope ancestry for the focused semantic node, including nested scopes. It uses current submissions when available and the retained frame before those nodes have been resubmitted. Disabled nodes, inactive/dismissed scopes and calls from inert subtrees return false. It does not infer ownership from overlapping rectangles; notification stacks can use it to pause a timer when any custom child has keyboard focus. `cui_box.max_width` and `max_height` cap natural (FIT), growing and explicitly sized boxes when positive and finite. Caps constrain a fixed minimum as well; short natural content stays short, and an explicit zero dimension stays zero. Nonpositive/nonfinite caps mean unbounded. Combine a cap with `clip` to bound arbitrary custom children without a previous-frame measurement flash. `CUI_ROLE_LISTITEM` and `CUI_ROLE_LOG` describe passive list entries and append-oriented logs without adding automatic Tab stops. Optional `scroll_axis_lock` in semantic details uses the declared orientation to accept only dominant-axis wheel motion (ties count as vertical). Unlocked routing is unchanged; a locked region at its boundary still chains to a movable ancestor. Event deltas remain intact for the recipient. `cui_color_mix_oklab(first, second, amount)` interpolates premultiplied alpha in perceptual Oklab space, then clamps the result to byte sRGB. Amount is the second color weight; finite out-of-range values clamp, and non-finite amounts select the first color. Transparent endpoints do not tint an opaque color while fading it. Set `semantic_details.focusable` to opt a passive container (for example a Log viewport) into keyboard/programmatic/pointer focus without changing its semantic role. Defaults remain passive. `cui_set_tab_stop(false)` suppresses sequential Tab navigation while retaining pointer/programmatic focus; disabled/inert containers remain unavailable, and interactive children take hit precedence over their enclosing container. `semantic_details.no_focus` suppresses a role's normal focus behavior, including Tab and known-node programmatic focus. Combine it with `pointer_activatable` for a pointer-only Button that retains its Button semantics. A `focus_target` can focus an associated editor while the pointer-only Button keeps its own capture and release activation. This supports numeric step buttons without stealing the editor's keyboard focus. `semantic_details.pointer_activatable` makes a passive container receive primary pointer capture and validated release activation, without adding focus or a Tab stop. Its click preserves existing keyboard focus; nested interactive children take precedence. Disabled/inert guards, release outside and cancellation still apply. Set `focusable` independently only when the container should also support keyboard navigation. `cui_set_underlay` paints one rounded rectangle below the children of the current box and above its background. Relative bounds resolve after current-frame layout. The paint is clipped to that box and all enclosing clips, contributes no layout/input/semantics, and respects layout-only suppression. Repeated calls replace the same underlay. Invalid geometry leaves the prior paint unchanged; normal draw-command capacity applies atomically. `cui_paint_bitmap` emits a leaf `CUI_DRAW_IMAGE` from borrowed straight-alpha RGBA8 pixels. The source view supports padded rows, an explicit cache revision, a pixel crop, opacity, and grayscale. Zero source bounds select the entire image; FIT sizing defaults to the crop dimensions. Pixels must remain valid until renderer completion. Dimensions are bounded to 16384 per axis and invalid views/crops are rejected without opening a layout element. Rounded corners and ancestor clips apply normally. Software, SDL3, SDL_GPU/Vulkan, and Sokol render bitmap pixels with crop, grayscale, optional RGBA tint, opacity, and rounded clipping. Native adapters keep bounded 64-entry/64-MiB texture caches keyed by source pointer, revision, crop, raster size, corners, grayscale, and tint. Placement and opacity reuse the cached texture. Canvas renders the same RGBA draw commands with a bounded 64-entry/16-MiB raster cache. Rasterized rounded edges currently use pixel-center coverage; source alpha is preserved. This API does not decode files or fetch URLs. `cui_set_underlay_ex` adds current-frame START/CENTER/END alignment and optional growth relative to the owning box. For a full-width bottom baseline, use bounds `{0,0,0,1}`, `grow_width=true`, and vertical END. Resizing resolves in the same layout pass without retained-size lag; offsets apply after alignment. `cui_begin_absolute_box` opens a zero-flow child using a fixed rectangle relative to its parent. It inherits ancestor clipping, inert/layout-only state and the parent's layer, so overlapping resize handles stay beneath higher portals. It requires an open parent and is balanced with `cui_end_box` even on invalid bounds. `CUI_ROLE_SEPARATOR` is passive unless semantic details opt into focus. Semantic `details.cursor` is a portable pointer hint. `cui_pointer_cursor` returns the captured control's hint while dragging, otherwise the topmost enabled hit in the completed frame, respecting ancestor clips and modal ownership. Hosts apply it after `cui_end_frame`; unsupported hosts may retain their default. The SDL3 host exposes `cui_sdl3_set_cursor` and also applies the last completed frame's hint during polling. System cursors are cached and released with the adapter; headless drivers report unsupported without failing event dispatch. A box may set `custom_opacity=true` and `opacity` to multiply every descendant paint's alpha, including text, bitmap, underlay and logically nested portals. Nested factors multiply; default boxes preserve full opacity. Values clamp to 0..1, with nonfinite values treated as zero. This is per-draw alpha modulation, not isolated group compositing. Opacity alone preserves semantics and input; combine with `inert` when hidden content should stop receiving interaction. Fractional font sizes and explicit line heights are preserved through measurement, word wrapping and draw commands. A context-owned bounded style table supplies stable Clay measurement identities; old generations are reclaimed only between frames, avoiding stale metrics when a line height changes. Text stays vertically centered in an explicit line box. Native font rasterizers may still quantize glyph outlines independently of these float layout coordinates. Pointer hit order follows each semantic's matching layout node, even when behavior is registered before that box. Higher layers win, then floating-root paint order, then child layout order. Ancestor clips and paint-time inert/layout-only state apply to that matched node. Semantics without a matching box retain their registration-parent fallback. Focus-scope ownership remains behavior-owned. `cui_box.width_percent` and `height_percent` interpret the corresponding dimension as a fraction of the current parent's inner extent. Fractions clamp to0..1 and take precedence over fixed flags and max caps. This resolves proportional rows on the first frame and after resize, without previous-frame measurements. Absolute/portal bounds retain their explicit dimension semantics. Cooperative event bubbling uses `cui_event_consumed` and `cui_consume_event`: leaf controls handle input before ancestor callbacks inspect it. Consumption does not erase the original target or activation diagnostics and resets each frame. Both editor event paths consume Left/Right, including at the text boundary. `cui_focus_step_within` traverses current submitted, enabled Tab stops inside a focus scope and wraps; call it after children. Nested scopes participate, while inert content, disabled controls, explicit non-Tab stops and controls outside the active modal are excluded. Missing scopes or removed focused children leave focus untouched. This is an opt-in traversal primitive; ordinary Tab is unchanged. `cui_resource_get` supplies stable zero-initialized context storage keyed by an owner ID and a namespace ID. The default limits are 128 entries and 1 MiB of payload bytes; configure `max_resources` and `resource_bytes` independently. Payload-owned allocations need their own limits. Reusing a key requires the same size and callbacks, preventing accidental reinterpretation. Exhaustion reports `CUI_ERROR_CAPACITY` without discarding another component's live data. Finish rendering each draw list before the next `cui_begin_frame`. At that boundary, the resource collector runs for entries used in the preceding frame; entries omitted for an entire frame are destroyed and their capacity reclaimed. `cui_destroy` releases every remaining entry exactly once. Callbacks must not reenter the context. This supports immutable bitmap versions until rendering finishes, without global mutable component caches. `cui_frame_time` accumulates validated frame deltas; `cui_frame_delta` exposes the current delta. Failed begins do not advance the clock or collect resources. Hosts set `cui_set_reduced_motion`; changes request redraw, and components query `cui_reduced_motion` to choose static presentation. Animated components still request their next frame explicitly through `cui_invalidate`. `cui_set_bitmap_underlay` paints a borrowed bitmap above the current box's background and below its children, with the solid-underlay alignment/grow rules. It supports source cropping, tint, opacity and corner radii through the normal image renderer path. Inherited alpha is applied once. Invalid bitmap geometry leaves an existing underlay intact; a later solid underlay replaces the bitmap. This permits image/gradient backgrounds without floating over interactive text. After `cui_end_frame`, `cui_semantic_parent(ui, id)` returns the explicit semantic parent when supplied, otherwise the closest layout ancestor whose box is owned by that semantic ID. A control registered without its own layout box does not become the semantic owner of its surrounding box. Explicit parent links must be acyclic. It returns zero for roots, unknown IDs and while a frame is open. Hosts can use this alongside `cui_semantics` to build the accessibility tree without guessing parentage from rectangles. `CUI_ROLE_RADIOGROUP` is appended to the role enum, preserving earlier role values. `cui_set_outline` paints an outside border band for the current open box using its current-frame bounds, independent corner radii and inherited opacity. It consumes no layout space, preserves the interior, follows ancestor clipping, and can coexist with a solid/bitmap underlay. Zero width clears the band; invalid geometry leaves the prior setting intact. Like underlays, command-capacity failure produces an empty draw list and a capacity error. Hosts may supply `cui_event.click_count` on pointer events. Zero and one preserve ordinary click behavior; larger values retain the host’s multi-click sequence metadata. The SDL adapter forwards SDL’s count directly, and the core queue preserves it unchanged. Text selection policies remain the component’s responsibility. `cui_pointer_position` returns the latest Move/Down/Up coordinates processed by `cui_begin_frame`; queued events wait until then, idle frames retain the position and a new context starts at `(0,0)`. It does not infer pointer visibility, hover, clipping or occlusion. Invalid/nonfinite values preserve both output variables. Use the accessor for host-driven plot cursors; current-layout prepaint callbacks remain a separate missing Core seam. Portable shortcut identities include `[` and `]` for Editor block-indent bindings. They are appended enum values, preserving existing host key numbers, and round-trip through `cui_key_from_character`/`cui_key_character`. Browser and SDL ASCII fallback mappings use these helpers. Character/IME text input remains separate from shortcut identity. Retained text layout can cache `cui_text_metrics_revision(ui)` with its document, width and complete text style. The context starts at generation1; a successful `cui_text_metrics_changed` outside a frame resets Clay measurement and changes this generation. Calls inside a frame are ignored. Null returns0. Compare by equality: generations wrap while skipping0. Hosts must announce changes to font registries or measurement policy before the next frame. Contexts are independent. --- ## Paint after layout Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CORE_PREPAINT.md # Paint after layout Use `cui_set_prepaint` when drawing depends on a box's geometry in the frame being rendered. Examples include a chart crosshair, a clipped selection overlay or a fixed paint-only tooltip. Normal component construction still determines layout and accessibility before this callback runs. Register on an open box with a nonzero ID. CUI copies the payload into bounded frame storage and invokes the callback after its single layout pass, before the renderer consumes the finished draw list. ```c #include typedef struct { cui_color normal, hovered; } highlight_colors; static bool paint_highlight(const cui_prepaint_info *info, const void *data, cui_prepaint_writer *writer) { const highlight_colors *colors = data; cui_draw_command command = { .type = CUI_DRAW_RECT, .bounds = info->bounds, .color = info->pointer_visible ? colors->hovered : colors->normal, }; return cui_prepaint_emit(writer, &command, false); } bool highlight_panel(cui_context *ui, cui_id id) { highlight_colors colors = {{24, 30, 40, 255}, {34, 55, 78, 255}}; cui_begin_box(ui, id, (cui_box){.width = 320, .height = 120}); bool registered = cui_set_prepaint(ui, (cui_prepaint_options){ .callback = paint_highlight, .payload = &colors, .payload_bytes = sizeof colors, .command_budget = 3, .hover_hitbox = true, }); cui_end_box(ui); return registered; } ``` The three-command budget covers the rectangle and its two clipping commands. The local paint stream uses global coordinates and clips to the box's current visible bounds. It appears above the box's underlay and below its children. Use `info->bounds` to position paint and `info->visible_bounds` to inspect clipping. `pointer_visible` includes current geometry, passive overlay occlusion and modal permission. A pointer position is unknown until a host supplies one. For a floating paint-only tooltip, pass `true` to `cui_prepaint_emit`. That deferred stream clips to the viewport and uses the requested layer; zero inherits the owner's layer. Its clip commands also count toward the budget. A layer cannot precede its owner, and modal rules can deny deferred output. Use `cui_prepaint_measure` for text measurement and emit a text draw command; its string is copied into frame storage. This does not construct an arbitrary component tree inside a tooltip. The callback receives an immutable geometry/input snapshot. Use writer operations for paint, measurement and `cui_prepaint_request_frame` when another animation frame is needed. Do not create boxes, modify focus, dispatch input, invalidate a context or register additional callbacks inside it. Read-only queries are allowed, but the snapshot provides the relevant current-frame geometry. Existing input routing still uses the published dispatch graph; this hook does not replace it. Payload bytes are copied with alignment. Pointers inside them remain borrowed. Image and mesh storage must remain valid until rendering completes; the writer itself exists only during the callback. CUI applies inherited opacity once, so callbacks should not multiply it again. A false callback or invalid emission discards that callback's output. Draw-capacity failure empties the final draw list and reports `CUI_ERROR_CAPACITY`. This guarantee does not roll back side effects in application code. Configure bounded element, command and frame-storage capacities for the workload and handle registration failure. Prepaint adds per-context storage; the detailed capacity and scaling measurements are recorded in the development validation report. Headless tests cover copying, clipping, ordering, opacity, capacity and mutation guards. An actual WASM browser fixture covers stationary-pointer scroll/resize, passive/modal occlusion and deferred pixels. These are Core-hook tests; a component must explicitly integrate the hook to gain those current-frame behaviors. --- ## Date locales and direct year selection Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DATE_LOCALE_YEAR.md # Date locales and direct year selection Calendar and DatePicker now expose an interactive year header. Activate it to choose from a 20-year grid (four columns, five rows), page backward/forward in 20-year steps, choose a year, then a month and an actual day. Selecting the year or month navigates without changing the selected date. A date in 1980 takes three year-page clicks from the gallery's 2026 starting year, instead of hundreds of month steps. The final page ends at 9999 and has one blank cell; year zero is never selectable. Navigation uses icon chevrons, not text `<`/`>` characters. The gallery adds a Date locale selector for Calendar and DatePicker. Its default is ISO (legacy). Built-in locale tables provide English US, English UK, Italian, French, German, Spanish and Japanese month/weekday labels, week starts, numeric date ordering and accessible control labels. US starts on Sunday and formats MM/DD/YYYY; UK/Italian/French/Spanish start on Monday and format DD/MM/YYYY; German uses DD.MM.YYYY; Japanese starts on Sunday and uses YYYY/MM/DD. The dates remain Gregorian model values, independent of presentation. ## Public API Choose an explicit borrowed locale in Calendar options: ```c cui_calendar_options options = { .locale = cui_date_locale_builtin(CUI_DATE_LOCALE_IT) }; cui_calendar(ui, calendar_id, &theme, &calendar_state, &selection, options); ``` Or supply the same options to DatePicker: ```c cui_date_picker_options options = { .calendar = {.locale = cui_date_locale_builtin(CUI_DATE_LOCALE_EN_GB)}, .viewport = {0, 0, width, height} }; cui_date_picker(ui, trigger_id, &theme, cui_string("Date"), &picker_state, &selection, options); ``` A NULL locale preserves the existing ISO trigger/day labels and caller's `first_weekday` (including zero-initialized Sunday). With an explicit locale, its week start wins unless `first_weekday_override` is true. For example, set the flag plus `.first_weekday = 6` for Saturday. Existing zero initializers and Calendar state initialization remain valid. `cui_date_format_locale(date, locale, buffer, capacity)` returns the required byte length excluding NUL, and NUL-terminates byte truncation when capacity is small (a truncated custom UTF-8 separator may end mid-codepoint). Capacity zero may use a NULL buffer. An invalid date returns zero and clears a supplied buffer. `cui_date_locale_builtin()` returns NULL for an unknown enum value. Custom `cui_date_locale` tables and their strings are caller-owned and borrowed. Keep them alive while options reference them. Supply UTF-8 `months[12]` and `weekdays[7]` (Sunday-indexed), week start, numeric `order` and a literal `separator`. Missing labels fall back to English. Calendar, year/month choice and four navigation labels can also be customized. A zero order is ISO; supported other orders are month/day/year, day/month/year and year/month/day. The separator is literal text, not a strftime/ICU pattern. This API does not parse localized input, discover OS locales, handle alternative calendar systems or guarantee fonts covering every label. Supply suitable fonts for Japanese/custom scripts. ## Interaction, constraints and focus Year and month cells use stable `cui_calendar_year_id()` and `cui_calendar_month_id()` IDs. The year header is navigation part 5; existing parts 1–4 retain their month/year behavior in day view and parts 1/4 page the active year grid. Calendar state records the view, year page and keyboard cursor. Initialize state with `cui_calendar_init()` or `cui_date_picker_init()`. Arrows move by one cell horizontally or four cells vertically in the grids. Home/End move to the page's first/last eligible entry. PageUp/PageDown change the year page by 20 years, or change the displayed year in month view. In day view, PageUp/PageDown change month (Ctrl/Meta changes year); existing arrow and Ctrl/Meta-arrow behavior remains available. Enter/Space use ordinary control activation. Focus follows the selected year, month and first enabled day. Escape returns from a year/month view to days; in DatePicker, a second Escape closes the popup and restores trigger focus. Disabled controls cannot change view or selection. A year/month is enabled only if it contains at least one date passing disabled/minimum/maximum/filter rules. Date filters remain caller callbacks and can be consulted repeatedly when checking a grid; keep them pure and inexpensive. Range selection is unchanged: only actual enabled day activation starts/completes a range, and the popup closes after the second day. Hard boundaries 1 and 9999 remain respected. ## Verification `test_picker.c` covers all seven built-in formats and week starts, explicit week start overrides, custom UTF-8 separators/labels, safe truncation, ISO fallback, actual year/month/day controls, leap-day 1980 selection, min/max/filter and disabled rejection, range selection, keyboard navigation, focus transitions, Escape and year boundaries. Existing Picker coverage is retained. Run the strict real browser suite after building the gallery: ```sh uv run tests/web/test_date_locale_year.py --directory build/web \ --chromium /path/to/chromium ``` It exercises all seven locales in both Calendar and DatePicker with mouse and actual Chromium CDP touch (28 cases), checks centered/equal-width year grids, localized month and weekday ordering, actual selected model value 19800229, localized trigger paint/accessibility, popup closing and two-stage Escape. It uses configuration DOM controls and real component input, never direct reducer calls. Screenshots/reports are written to `/tmp/cui-date-locale-year`. This does not establish physical mobile device, OS IME or every font coverage. Warning-enabled native build and the two documented API examples compiled. Full CTest passed 93/94; only root-owned generated distribution was stale pending regeneration. Picker/base-only passed ASAN/UBSAN (2/2). The strict locale/year suite passed 28/28, existing touch coverage 42/42 and 16/16, and the full browser suite rendered all 78 stories, compiled all 78 excerpts and passed its 390 px layout and hosted-path checks. --- ## Debug a native CUI app Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DEBUGGING.md # Debug a native CUI app Start with the smallest failing frame and check the installed revision's public headers. [Layout](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/LAYOUT_GUIDE.md) and [IDs/lifetimes](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/IDS_AND_LIFETIMES.md) explain the contracts most often involved. The feature manifest remains the authority for incomplete behavior across all 78 entries. After `cui_end_frame`, inspect `cui_last_error(ui)` before rendering. Errors are sticky: record the failure before explicitly clearing it with `cui_clear_error`. A draw-command capacity failure returns an empty draw list so clips remain balanced; an empty frame is not proof of a renderer failure. Check configured element, command and string capacities rather than repeatedly clearing errors. `cui_first_diagnostic(ui, &diagnostic)` preserves the first failure and `cui_latest_diagnostic(ui, &diagnostic)` tracks the most recent one. Both return whether a snapshot exists. Snapshots include error/detail, subsystem, operation, bounded message, frame sequence, implicated ID, optional used/requested/limit counts, and a bounded outermost-box ID path with a truncation flag. Zero counts mean unspecified. `cui_clear_error` clears both snapshots too. `cui_set_diagnostic_callback` installs an optional callback; copy the borrowed snapshot if retaining it, and do not reenter/mutate the context from that callback. The library does not print diagnostics automatically. Application/component code can report a failure with `cui_report_diagnostic`. For geometry inspection call `cui_set_layout_debug(ui, true)` before composition. After `cui_end_frame`, and before the next begin, export using `cui_debug_layout_export(ui, CUI_DEBUG_LAYOUT_JSON, buffer, capacity, &required)` or `CUI_DEBUG_LAYOUT_TEXT`. A null/zero-capacity sizing query returns false and sets `required` including the terminating NUL; allocate that much storage and retry. Insufficient buffers remain untouched. Export covers boxes, not individual text nodes: IDs, parent indexes, requested dimensions, resolved bounds/clips and resolution status help distinguish sizing from paint failures. JSON IDs are strings so all 64 bits survive JavaScript parsing. Export performs no file I/O; the application owns persistence and buffer allocation. Disable capture when no longer needed; opt-in snapshots are a debugging aid, not an accessibility tree. | Symptom | First checks | | --- | --- | | Content too wide or not wrapping | Parent width constraint, FIT versus grow, text-line API, font measurement | | Missing or cut-off content | Clip ancestors, fixed height, max dimensions, capacity errors | | Wrong row activates after reorder | Persistent row key and local ID scope; duplicates | | First click seems ignored | Input targets exist only after a completed frame | | Missing icon | `cui_icon_query` distinguishes unknown, catalog-not-embedded and embedded assets; inspect `CUI_ICON_NOT_FOUND`; optionally enable `debug_placeholder` | | Missing glyph or wrong weight | Font script coverage and registered style; no universal automatic fallback | | Native app fails before first frame | Font path, SDL3 error, pkg-config prerequisites and actual host display | Do not use emoji as an icon fallback: font coverage and appearance vary. Use a registered icon name, a deliberate text label, or an application-owned bitmap. A declared optional API does not prove its implementation is in the bundle. For a reproducible report include revision, renderer, platform, window dimensions, font files, triggering interaction, expected result, error, and bounded capture. Consumer captures use `--frames 3 --capture frame.bmp`. Automated native Linux runs must use invisible Xvfb; repository validation uses `python scripts/test_local.py --build-dir build`. Never use `DISPLAY=:0` or the maintainer's Wayland session. Browser tests run headless. GPU hardware behavior unsupported by the virtual display remains explicitly deferred. The bundle host registers a diagnostic callback that writes subsystem, operation, message, error/detail, ID, frame and capacity counters to stderr. This covers reported Core/component failures after context creation; font and SDL setup or render failures use their own explicit host messages. It is not a universal warning stream for every missing asset or every optional API. ```sh ./build/native_starter --frames 1 --debug-layout text ./build/native_starter --frames 1 --debug-layout json > layout.json ``` The option prints the first completed frame once, then continues the normal bounded or interactive run. JSON goes to stdout; diagnostics go to stderr. ## Default context budgets Zero-valued capacity fields in `cui_config` select these defaults: | Field | Default | Budget | | --- | --- | --- | | `max_elements` | 4096 | Layout/component elements | | `max_commands` | 8192 | Draw commands | | `frame_bytes` | 262144 (256 KiB) | Copied frame data | | `max_resources` | 128 | Context-owned resource entries | | `resource_bytes` | 1048576 (1 MiB) | Context-owned resource storage | Use a diagnostic's subsystem and used/requested/limit counters to choose which budget needs attention. Raising draw-command capacity does not repair an unbalanced scope or duplicate ID. These are defaults for this revision, not promises that every application fits them. Missing-icon availability is separate from context error reporting. Read `cui_icon_query(cui_string("clock-3"))`: the default bundle reports `CUI_ICON_CATALOG_NOT_EMBEDDED`; a full-assets build reports `CUI_ICON_EMBEDDED`. Check the icon call's result, and use `.debug_placeholder = true` only when a visible development outline is useful. It retains `CUI_ICON_NOT_FOUND` and the full accessible name. See [Icon](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/ICON.md) for loader and asset limits. --- ## Dependencies Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DEPENDENCIES.md # Dependencies Core: C11 compiler + pinned vendored Clay (zlib). Build: CMake >=3.20, Ninja or Make; Python 3 for generation/checks. Optional native gallery: SDL3 >=3.2, FreeType and HarfBuzz via pkg-config; system font or configured font path. Optional UTF-8 processing dependency utf8proc is available but is not automatically a grapheme/bidi implementation. No upstream/Rust/JavaScript runtime required. Development host observations: GCC 16.2.1; SDL3 3.4.16; FreeType pkg-config 26.6.20; HarfBuzz 14.5.1; utf8proc 2.11.3. System dependencies are discovered rather than downloaded; source snapshot versions and hashes are tracked in third_party/dependencies.json. Offline core builds need no network. Native CI dependencies must be pinned where downloaded. The optional website documentation build uses `uv run scripts/build_docs.py`, with PEP 723 pins for markdown-it-py 4.0.0 (MIT) and mdurl 0.1.2 (MIT). They run only during generation; published pages contain rendered HTML and require no Markdown runtime or Python environment. Raw Markdown HTML is escaped. Run `uv run tests/test_docs.py` to check rendering, links, assets and document coverage. Optional bidi analysis uses vendored SheenBidi 3.0.0, commit `cfe430e7375a7845b679adae9d51dac6deaa8858`, Apache-2.0, Unicode 17. All vendored files and normative conformance fixtures have checked SHA256 pins. `CUI_BUILD_BIDI=OFF` omits the compiled `cui_bidi` library. Core never links it implicitly. The optional static library includes its backend objects, so `pkg-config --libs cui-bidi` needs no additional runtime installation. CUI wrapper/tests use the normal warning policy; four specific unused/fallthrough warnings are suppressed only for unmodified upstream. See [BIDI.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BIDI.md) for current analysis and integration limits. ### MSVC bridge builds The C bridge owner guard uses C11 atomics and thread-local storage. Use a recent MSVC toolset with C11 atomics support; CMake enables `/experimental:c11atomics` for C compilation. Manual bridge builds must enable that flag alongside C11 mode. Portable CI compilation is separate from native Windows runtime acceptance. --- ## Design sizes Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DESIGN_SIZES.md # Design sizes Styled controls accept an appended `cui_design_size design_size`. Zero (`CUI_DESIGN_INHERIT`) keeps their previous legacy size and custom metric behavior. Existing zero initializers remain valid. Public structs have grown: rebuild callers when updating the library. The shared scale is xs, sm, base, md, lg, xl, 2xl, 3xl, 4xl, 5xl, 6xl, 7xl, 8xl and 9xl. Base and md deliberately share metrics. Explicit sizes resolve the existing public `cui_design_measure` table, including font, line height, control height, horizontal/vertical padding, gap and indicator size. Normal styled density is `theme.font_size / 16`; compact density changes those metrics once. The newly supported options are Badge, Progress (including circular Progress), Tag, Attachment model, DropdownButton, Tabs, DescriptionList, Icon, Toolbar, Settings, Questionnaire and Speech button/waveform. These join the previously supported Button, check/radio/switch/toggle, Input, Textarea, NumberInput, OTP, List, Select, Combobox, Menu and Form families. ## Geometry and composition Explicit design size replaces legacy size-derived metrics. Caller-provided widths, height/diameter overrides, custom boxes and artwork transforms keep their existing precedence. Invalid enum values submit no UI and perform no input reduction or callback. Invalid density and bounded bitmap capacity failures remain explicit failures. All public API types remain portable C11. A Badge sizes its count/dot/icon indicator; the application still owns its wrapped content dimensions. Linear Progress uses one quarter of the scale control height unless a height is supplied. Circular Progress uses the scale control height unless a diameter is supplied; raster storage remains caller-owned and capacity-checked. The bounded circle geometry limit is 4096 pixels; raster scale is at most four (16384-pixel extent). Insufficient capacity rejects before touching storage or motion state. Tag padding also accommodates the enlarged font's vertical padding. DescriptionList labels retain their 7/8 text ratio. Attachment preserves caller card width and media aspect; its text, glyph, height and padding follow the scale. Toolbar presentation metrics carry the resolved design size to nested groups and custom children. Settings' built-in field controls use the original theme plus the explicit size, avoiding a second density multiplication. Custom render callbacks receive the original control theme and the design size in their render options; they must apply that size to their own child controls. Questionnaire root options propagate size and density to composable parts. Its `density` defaults to the root theme density, or one for standalone parts. A part with `custom_size` keeps its explicit size choice; an explicit positive density overrides inherited density. Custom choice views carry the design size. Speech waveform width defaults to six font units and height to the scale control height; explicit waveform dimensions remain authoritative. ## Gallery and Tabs The gallery exposes the shared fourteen-size selector for these families and hides their old four-size selectors. A named size changes submitted canvas geometry and text; it is not a label translation. Supersized controls can require scrolling or more application layout space. The Tabs overflow trigger has square geometry, a centered SVG chevron and a minimum 32-pixel hit area even at compact xs. Its semantic Button is named “All tabs”. Horizontal and vertical overflow use the existing menu, keyboard and selection reducer. This change does not alter shared host wheel routing. ## Validation Headless regressions compare the private Base-only table with the public resolver through all fourteen sizes at normal, compact and doubled density, then check actual submitted dimensions, text fonts, invalid-input atomicity and compound propagation. `tests/web/test_design_sizes.py` runs a built gallery in real Chromium, checks all twelve newly exposed story families and both circular Progress variants at every size, compact density, and both overflow axes with centered SVGs and actual menu activation. Run the ordinary warning build and CTest, build the gallery with `python3 scripts/build_web.py`, then use `uv run tests/web/test_design_sizes.py --directory build/web --chromium /path/to/chrome`. Distribution regeneration belongs to the integrator; source-only worker validation may report the expected stale-distribution check. --- ## Sizes, spacing and visual styling Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DESIGN_SYSTEM.md # Sizes, spacing and visual styling Use a shared scale to keep a form, toolbar and application layout consistent. CUI values are logical pixels: a renderer's display scale maps them to physical pixels. The component gallery lets you compare sizes, corner radii and spacing without changing your operating system's display scale. ## Control and typography sizes Set `design_size` on Button, Checkbox, Radio, Switch, Toggle, Input, Textarea, List, Select, Menu, Combobox, NumberInput, Form, InputGroup or OtpInput options. Zero (`CUI_DESIGN_INHERIT`) preserves the existing upstream size enum and its metrics. The shared scale is opt-in; existing applications keep their current dimensions. | Scale | Font | Line height | Single-line control height | | --- | ---: | ---: | ---: | | xs | 12 | 16 | 20 | | sm | 14 | 20 | 24 | | base / md | 16 | 24 | 32 | | lg | 18 | 28 | 40 | | xl | 20 | 28 | 48 | | 2xl | 24 | 32 | 56 | | 3xl | 30 | 36 | 64 | | 4xl | 36 | 40 | 80 | | 5xl | 48 | 48 | 104 | | 6xl | 60 | 60 | 128 | | 7xl | 72 | 72 | 152 | | 8xl | 96 | 96 | 200 | | 9xl | 128 | 128 | 264 | These are CUI's explicit logical-pixel metrics, inspired by utility design scales. `md` is an alias of `base` in this scale. Metrics multiply by the theme's root font density (`theme.font_size / 16`). The legacy upstream Button Large remains 32 pixels; select `CUI_DESIGN_LG` for the new 40-pixel control. ```c cui_button_ex(ui, save_id, &theme, cui_string("Save changes"), (cui_button_options){.design_size = CUI_DESIGN_LG}); cui_input_ex(ui, email_id, &theme, cui_string("Email"), edit, &input_state, (cui_input_options){.width = 320, .design_size = CUI_DESIGN_LG}); ``` Single-line controls use the listed height. Checkbox/Radio indicators use the font size; Switch tracks add four logical pixels to that indicator size. Textarea grows by its row count using the shared line height and padding, plus its border. Popup query fields and option rows share the same scale. Explicit row-height overrides still take precedence. Supply enough width for large text; a larger size does not increase an explicitly fixed container width. `cui_design_measure(size, density, &metrics)` returns font, line height, control height, horizontal/vertical padding, gap and indicator size. Invalid inputs return false without writing the output. A base Textarea receives its metrics from the caller; its legacy `cui_textarea_measure` helper continues to measure legacy sizes. The styled Textarea applies `design_size` before submitting its base behavior. ## Spacing and corners `cui_space(units)` maps one unit to four logical pixels. Fractions work: `cui_space(0.5f)` is two pixels. Use negative units for offsets, and nonnegative units for padding and gaps. ```c cui_begin_box(ui, card_id, (cui_box){ .width = 360, .padding = cui_space(6), .gap = cui_space(3), .radius = cui_radius(CUI_RADIUS_XL, 1), .background = theme.surface }); /* Submit card children here. */ cui_end_box(ui); ``` The radius scale is none=0, xs=2, sm=4, md=6, lg=8, xl=12, 2xl=16, 3xl=24 and full=9999 logical pixels, multiplied by the supplied density. Renderers constrain full rounding to each shape's bounds. Set the theme's `radius` and `radius_lg` where appropriate, or a particular box's `radius`. Comfortable/compact theme choices remain useful starting points; these units give you finer control over an individual layout. ## Typography `cui_text_ex` supports normal, medium, semibold and bold weights, italic and monospace styles, explicit font size and line height. For example: ```c cui_text_ex(ui, cui_string("Workspace"), 24, theme.text, 32, (cui_text_style){.weight = CUI_TEXT_WEIGHT_SEMIBOLD}); cui_text_ex(ui, cui_string("cui_begin_frame(...)"), 14, theme.muted, 20, (cui_text_style){.monospace = true}); ``` The host owns font selection and measurement. Configure styled measurement and font metrics alongside drawing, so the same font faces and styles determine both layout and pixels. See [text adapter](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TEXT.md) and [editing](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/EDITING.md). The website's browser font registry is a host policy; it does not install those fonts for a native application. ## Backgrounds, opacity and motion A box's `background` accepts RGBA color. `custom_opacity=true` and `opacity` apply inherited draw opacity to its children as well as the box. Use `cui_paint_bitmap` for a generated gradient or other image fill; keep its pixels alive until rendering completes and increment its revision after changing them. Use the portable [background effects helpers](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BACKGROUNDS.md) to generate multi-stop gradients, apply opacity or blur caller-owned RGBA pixels. The Theme gallery applies these helpers in C before painting its bitmap panels. A backdrop effect needs a captured image supplied by the host; generic boxes do not capture pixels behind themselves. Progress supports indeterminate animation with host time. Sheet supports timed entry/exit motion through `sheet_animation_seconds`, including reduced-motion behavior. Tabs expose an application-owned spring indicator. See [Progress](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PROGRESS.md), [surfaces](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SURFACES.md) and [choices](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CHOICE.md) for their actual APIs. Animate your own state using frame time and request another frame with `cui_invalidate`; respect `cui_reduced_motion(ui)` in the host's motion policy. ## Font families and text styles The Theme gallery includes an interactive typography specimen with system, sans-serif, serif and monospace families, four weights, italic and xs–9xl sizes. These browser families are host mappings of `cui_text_style.family`; they are not font files bundled with CUI. A native application registers its own faces and uses the same family ID for measurement and rendering. See [TYPOGRAPHY.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TYPOGRAPHY.md) for a complete native program and fallback rules. ## Motion examples TextView exposes duration, word stagger and easing controls in its preview; Sheet demonstrates entering and leaving, and Progress offers an indeterminate mode. Examples forward the operating system's reduced-motion preference. See [TEXT_VIEW.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TEXT_VIEW.md) for a complete headless motion program and [SURFACES.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SURFACES.md) for sheet lifetimes and deferred callbacks. Motion is explicit state driven by host time, rather than a stylesheet or a background thread. --- ## Disclosure applied transitions Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DISCLOSURE_EVENTS.md # Disclosure applied transitions Include `cui/cui_disclosure_events.h`. `cui_base_collapsible_events` and `cui_collapsible_events` add a synchronous observer to the existing owned bool. They preserve the old return in `result.changed`; `change_count` counts actual observer calls and saturates at SIZE_MAX with `count_overflow`. A missing observer still permits editing and ignores its user pointer. ```c static void expanded(void *user, const cui_disclosure_change *change) { bool *needs_save = user; /* unrelated application state */ *needs_save = true; /* Copy *change here if needed after this callback. */ } /* During the normal UI submission: */ /* cui_collapsible_events(ui, id, theme, label, &open, options, panel, panel_user, (cui_disclosure_handler){expanded, &needs_save}); */ ``` Each real bool write emits CHANGE immediately afterward. Two toggles in one frame emit twice even when the final bool equals its initial value. `previous` and `expanded` describe applied values, never a rejectable request. Collapsible uses item_index 0. Notification precedes final expanded semantics and Styled header, panel and motion work; those retain their original timing. There is no notification for animation, passive/layout-only submission, disabled input or absent observers. Metadata targets the compound identity. When Core supplies accepted activation evidence, it is copied before the write; `event.activation.target` retains the original activation identity. Otherwise only actual frame/input-index/type-source facts are copied. Presence flags define what is available; no cause is invented. Payloads contain no borrowed strings/pointers and may be copied by value. The callback and user pointer are borrowed for the operation. The observer must not mutate/rebind/free expanded state, active items/motion/style storage, input or context, recursively submit UI, or destroy resources. Unrelated flags may change. Defer omission, removal and teardown until the outer call returns and the frame's renderer has consumed retained resources. Existing header/panel callback contracts remain unchanged. This C facade adds no bridge or language-binding support. ## Accordion `cui_base_accordion_events` takes an explicit nonzero compound target; `cui_accordion_events` uses its container ID. Item IDs and required pointers must be valid before admission; invalid required arguments return a zero result without calling the legacy operation. Existing unique/stable ID preconditions apply. `item` and `item_index` identify the affected model slot. Opening in single mode closes each true sibling in ascending index order, including a disabled-open sibling, then opens the chosen item. Already-false writes stay silent. Each callback sees this intermediate array; there can temporarily be no open item or several remaining old items. No normalization occurs just because input starts multi-open. Multiple mode only changes the chosen slot. Noncollapsible open activation is silent. The copied activation still identifies the originating trigger, even when keyboard navigation redirects the reducer cursor or single-open policy closes another item. `event.target` remains the compound. Notifications precede the existing final semantic pass: Button checked values reflect initial registration and expanded details have not yet been finalized. Do not infer finalized semantics, panel paint or motion from a callback. No observers run for spring updates or passive cleanup. --- ## DropdownButton paired notifications Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DROPDOWN_EVENTS.md # DropdownButton paired notifications `cui_base_dropdown_button_events` and `cui_dropdown_button_events` add synchronous observers for the primary action and individual menu commands. They preserve the paired DropdownButton presentation and legacy aggregate result; no separate SplitButton family, new queue or binding facade is introduced. [MenuTree events](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MENU_EVENTS.md), [control events](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CONTROL_EVENTS.md) and [ContextMenu events](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CONTEXT_MENU_EVENTS.md) describe the reused payload types. ```c static void action(void *user, const cui_component_event_metadata *event) { /* ACTIVATE, target == action_id; copied accepted Core evidence. */ (void)user; (void)event; } static void command(void *user, const cui_menu_command *event) { /* ACTIVATE, event.target == trigger_id; command is the leaf ID. */ *(cui_id *)user = event->command; } cui_dropdown_event_result result = cui_dropdown_button_events( ui, container, action_id, trigger_id, &theme, cui_string("Save"), cui_string("More actions"), entries, count, &menu_action, &menu, options, (cui_dropdown_event_handlers){{action, NULL}, {command, &last_command}}); ``` The Base facade takes the legacy Base arguments followed by `cui_dropdown_event_handlers`. Its zero action/trigger ID omits that half; both zero and equal IDs remain invalid. Styled uses the existing `hide_action`/`hide_menu` options. `container` is paint identity, not an invented activation target. `cui_dropdown_event_result` contains `valid`, `submitted`, `count_overflow`, `action_count`, `command_count` and `legacy` (`cui_dropdown_button_result`). Both counts mean actual callback invocations: a missing observer counts zero while normal activation, writes and popup closing continue. Counts saturate without stopping dispatch. The two legacy booleans preserve their old aggregate meanings; they do not establish how many events occurred. This differs from Button's facade activation-attempt count. The existing order is preserved: **Base action reduction → action observation → Base menu reduction/observation → Styled role updates, painting, retained metrics and tooltip composition**. Base Button is called once. The observer pass passively enumerates actual accepted activations after that registration and copies each Core activation snapshot before calling user code. It neither re-runs Button nor reconstructs events from its aggregate bool. MenuTree's real per-command commit seam runs once, preserving check/radio writes, keep-open multiplicity and frozen closing-command exit decisions. Trigger opening emits no menu leaf notification. Action metadata targets `action_id`, includes genuine accepted evidence, and preserves mouse/touch/key/accessibility source and frame/index. Menu metadata targets `trigger_id`; any copied activation retains its actual child target. MenuTree's ordinary reducer-before-registration path has no copied activation snapshot. No programmatic evidence is synthesized. Action phase precedes menu phase even if the action's queued event index is larger; callbacks are not sorted, replayed or deferred. An action observer may update caller values or consume events before menu reduction. The normal Styled root menu painter creates a modal focus scope, even if `state.overlay.modal` was changed. Consequently an open Styled popup does not independently admit outside primary-action input. The fixture proves mixed action/menu ordering with a genuine Base composition that paints menu rows in a modeless scope; it does not claim that the normal Styled popup is modeless. No scope behavior changed in this slice. Action disabled/loading suppresses that half; loading retains existing busy/Loading semantics and visuals. Outer/menu disabled policy still suppresses both. Hidden action has no semantic or observer; hidden menu closes the popup and clears depth. Existing Link presentation updates roles only after Base reduction. A genuine accessibility ACTIVATE queued against the previous LINK role is rejected when the current Base registration is BUTTON; this existing mismatch affects legacy and new results. The new facade reports no invented callback/evidence and does not claim complete Link accessibility parity. Pointer behavior and the final Link semantic roles remain unchanged. Handlers and payloads are borrowed only during synchronous submission. Pointer-free metadata/command copies survive frames and context destruction. Keep active descriptors, state, values, users and render/tooltip resources alive and stable through submission. Owner writes are notifications' effects, not recursive change events or vetoes. Direct mutation of in-flight navigation, freeing active storage, context destruction and recursive submission during dispatch remain unsupported; defer shutdown/removal until submission/frame completion. Existing inert/layout-only/omitted invocation behavior applies. [test_dropdown_events.c](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_dropdown_events.c) checks Base and Styled real mouse/touch/key/accessibility action acceptance, multiple actions, missing observers, busy/disabled/hidden halves, old/new geometry and custom painting, repeated keep-open commands, copied lifetimes, inert/omitted calls and Link rejection. Its Base modeless composition proves decreasing action/menu indices, applied owner writes and consumption before menu reduction; Styled proves normal modal exclusion. Existing Choice tests retain broader tooltip, anchor, variant and artwork coverage; ControlEvents and other menu fixtures protect neighboring facades. ```sh python scripts/test_local.py --build-dir build -- -R '^(dropdown_events|choice|control_events_facades|menu_events|simple_menu_events|context_menu_events)$' ``` The integrator registers tests and documentation exports. No generated files, callback retiming, manifest changes or parity promotion are included. --- ## Bounded portable drop shadows Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DROP_SHADOW.md # Bounded portable drop shadows `cui_set_drop_shadows` copies up to eight caller-owned layers onto the open box. They paint in supplied order before its background and before its child-overflow clip, under the current ancestor mask and opacity. `count=0` clears the list. Shadow pixels add no interaction or semantics. A layer contains logical pixel offset, signed spread, Gaussian standard deviation (`sigma`), and straight RGBA8 color. Original caster corner radii clamp against the original dimensions; spread changes bounds without changing those radii. Logical bounds preserve the source offset/dilation operation order. Physical covering floors the materialized near edge, ceils its stored origin plus stored size, then clamps the far edge to the near edge. A fractional logically collapsed dimension can therefore cover one physical pixel; only empty physical covering paints nothing. `cui_prepaint_drop_shadow` emits the same value-owned primitive. It consumes one command per layer plus existing clip wrappers. Deferred paint inherits existing viewport/modal rules and ancestor opacity exactly once. It never borrows a caller layer list or performs layout, semantics, interaction, or invalidation. Existing component/prepaint emission rollback applies; renderer preparation, external callbacks and later device submission have their existing separate failure boundaries. `cui_theme_popover_shadows(theme,strength,out)` copies the source popover's three layers: foreground at alpha `.1`, zero offset/sigma, spread `+1`; black alpha `.1`, offset `(0,4)`, sigma `3`, spread `-1`; black alpha `.1`, offset `(0,2)`, sigma `2`, spread `-2`. Finite strength clamps to `[0,1]`; output is unchanged on invalid input. Theme projection is consumed by both styled Chart tooltip composition and current-frame paint. `NULL` tooltip style retains its legacy behavior; bare style paints neither surface nor shadows. Projected boxed style has three copied layers. `ring_color` overrides every canonical sigma-zero, spread-one, zero-offset ring; non-ring custom layers use their own color. Explicit style with zero layers retains its previous sigma-zero ring fallback. All layer values are copied into deferred payloads, including when caller options/style are destroyed or relocated. ## Kernel and supported domain `cui_effect_drop_shadow_query`, `sample`, and `raster` use the pinned upstream 0.3.8 f32 renderer model: rational erf for the horizontal Gaussian integral, four vertical midpoint samples, and finite three-sigma support. Sigma zero fills the rounded SDF shape with a one-physical-pixel coverage ramp beneath translucent surfaces. This differs from CUI's existing separable **box** blur. It also differs from an infinite exact mathematical Gaussian convolution; the pinned shader itself is a bounded four-sample approximation. Query/raster accept an explicit uniform logical-to-physical scale and physical origin. Scale is `[1/65536,64]`. Caster coordinates/dimensions and radii are finite and bounded to 16384; offsets/spread to absolute 4096; sigma is `[0,256]`. To prevent f32 underflow/division from publishing NaN coverage, positive physical sigma below `4*sqrt(FLT_MIN)` is rejected atomically; sigma zero is a separate supported case. Raster dimensions are at most 16384 per side and 16 million pixels. Invalid/capacity failures leave published query/sample output and caller raster storage unchanged. Raster uses caller storage and performs no allocation. Query `covered_layer` reports the physical integer covered unblurred layer bounds, from the same checked calculation that supplies raster geometry. The bounded scale/origin/caster domain keeps these integer edges exactly representable as floats. Physical covering floors near edges and ceils far edges. Supplied radii retain their original caster clamp through spread. Scene culling mirrors the pinned source: it tests the **unblurred** covered layer bounds against the current covered mask; a tail-only intersection paints nothing. Prepared masks crop to covered physical near/far bounds. Source pixel-grid covering can intentionally expose a full boundary pixel beyond a fractional logical mask; generic logical clip rounding or Canvas clip antialiasing must not replace that rule. ## Adapter preparation and budgets All native adapters prepare shadow pixels/resources before clearing/submitting target paint. Software coordinates already represent physical pixels and use scale 1. SDL Renderer derives actual render scale, viewport origin and logical presentation rectangle; SDL GPU derives acquired drawable/list projection; Sokol derives physical target/list projection. Canvas uses the actual `ctx.getTransform()` scale/origin, rather than backing-store/list ratios that include canvas-dimension rounding. A shadow frame with genuinely nonuniform or unsupported transform fails before clear; frames without shadows preserve their existing transform behavior. Uniformity tolerance is four float ULPs relative to the larger positive scale. Each native adapter owns a bounded 64-entry coverage cache. CPU shadow storage is at most 32 MiB and uploaded shadow images at most 32 MiB, for at most 64 MiB owned cached pixel storage. Public raster query's 16M pixel limit is independent: a raster too large for an adapter's available cache fails explicitly. Frame-used entries cannot be evicted by later preparation. Integer device translations and opacity changes reuse coverage; fractional phase, dimensions, sigma/spread/radii, scale and colors distinguish entries. Actual covered dimensions/position are checked before normalized translation reuse, including large-coordinate f32 cancellation. Resource creation never holds a caller stack pointer. Transient frame command copies, upload staging, C raster caller buffers and graphics-driver overhead are separately bounded by their existing/declared budgets, not included in cached pixel accounting. SDL Renderer suspends its rounded logical clip while painting a prepared, physically cropped shadow, then restores it; target viewport remains active. SDL GPU shadow scissors use actual target bounds and prepared physical crop. Ordinary draws keep their existing clip path. On predictable GPU preflight failure no swapchain is acquired. The separate lifecycle hotfix handles unavoidable post-acquisition resize races legally: it submits a blit of the previous completed offscreen surface when available. It never cancels an acquired swapchain. A first frame without a previous surface and device submission failure cannot promise unchanged presentation. ## Canvas host wiring `web/modules/cui_shadow.js` exports `createCuiShadowRenderer` and `cuiShadowWasmRasterizer`. `web/modules/cui_shadow_bridge.c` is the standalone bridge/example schema for the existing pure C kernel; it is not automatically linked into applications. The gallery links this bridge, copies each shadow value command, preflights all rasters before either resizing or clearing its Canvas, and suspends ordinary fractional clips while drawing the prepared physical masks. The host decodes commands to `{type:'shadow',values:[caster x,y,w,h; original radii TL,TR,BL,BR; offset x,y,sigma,spread; R,G,B,A]}`, clip commands to `{type:'clipPush',bounds:[x,y,w,h]}`/`{type:'clipPop'}`, and other commands to `{type:'other'}`. All 16 values are copied. Call `renderer.prepare(commands,ctx,logicalWidth,logicalHeight)` **before** clearing the target; errors leave target pixels unchanged. The checked C query and raster provider returns copied metadata and borrowed pixels used only synchronously during preparation. WASM memory views are recreated after each call to tolerate memory growth. At each shadow command, suspend the host's generic Canvas clip stack, call `prepared.draw(index,ctx,{unclipped:true})`, then reapply that stack for subsequent ordinary commands. Prepared physical mask cropping owns shadow clipping; inherited `ctx.clip()` would antialias fractional boundaries incorrectly. The explicit flag documents this host responsibility; Canvas cannot inspect or reset an arbitrary caller clip stack itself. Prepared frames expire on the next `prepare` or `clear`; expired draws reject, and their retained pixel references are released even if a host keeps the old frame object. `draw` rejects transform changes after preparation. It performs no clear. Ordinary commands remain the host's responsibility and preserve their paint order. Cache clear/destruction releases module-owned references; Canvas/browser/driver resource retirement is managed by the browser. Bridge exports are `cui_canvas_shadow_values` (pointer to16 writable floats), `cui_canvas_shadow_query`, `cui_canvas_shadow_prepare`, `cui_canvas_shadow_width`, `cui_canvas_shadow_height`, `cui_canvas_shadow_bound(index)`, `cui_canvas_shadow_layer_bound(index)` (physical unblurred bounds), `cui_canvas_shadow_pixels`. Query/prepare return 0 on failure and 1 on success. Pixels are straight RGBA8; copied metadata bounds are logical placement, widths/heights physical raster dimensions. The bridge's single reusable raster buffer is borrowed until its next prepare call and capped to 32 MiB. The renderer copies it synchronously into an offscreen Canvas; caller stack buffers are never retained. ## Verification scope Headless tests compare the pinned four-sample model against independent exact rectangle Gaussian CDF, and exercise symmetry/cutoff, sigma-zero corners, signed spread, subnormal rejection, finite cancellation, atomic output, copied layers, source order/opacity, child overflow, tail-only exclusion and bounded frame/cache failure. Actual native SDL Renderer/Vulkan/Sokol readback and Chromium WASM tests cover both physical scales 1/2 and all three layers beneath translucent surfaces. Existing appearance proof retains both consumers, automatic/copied content, bare behavior, line boxes, corner geometry, progress/ancestor opacity and stationary move/resize. Exact pinned native Metal/WGPU shader antialiasing/color-format image identity is not certified by these portable kernel and adapter tests. Public inset shadows, arbitrary nonuniform transforms, renderer-specific color spaces, and native upstream image captures remain outside this bounded drop-shadow slice. No full BoxShadow or Chart family completion is claimed. The covering regression fixture pins the dependency archive and geometry/window source hashes in `tests/unit/shadow_covering_source.json`. Tests cover high-origin f32 far-edge rounding, fractional negative-spread and zero-size covering, real Core node emission, Software pixels, cache reuse and unblurred-mask culling. SDL Renderer pre-Present readback, SDL GPU readback, Sokol GL readback and Canvas WASM probe each verify the formerly missing fractional pixel at uniform scales 1 and 2. These establish portable geometry and compositing behavior, not native upstream shader AA identity. Inset shadows remain unsupported. --- ## Explicit UTF-8 editing model Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/EDITING.md # Explicit UTF-8 editing model `cui/cui_edit.h` exposes a persistent model independently of any styled Input. The application supplies and owns a NUL-terminated buffer and its capacity, including the terminator. Only the model may mutate that buffer while attached; external changes require destroying and recreating the model. Creation rejects missing termination, malformed UTF-8, embedded NUL, and line breaks in single-line mode. The handle owns its cursor, selection anchor, scratch storage, and optional bounded history. Destroying it leaves the application buffer intact. All offsets are bytes at Unicode scalar boundaries. Selection endpoints may be reversed. Left/right move one scalar and, without extension, collapse an existing selection to its corresponding edge. Home/End move to LF-delimited line boundaries; document start/end are separate motions. Word previous/next skip punctuation and whitespace between word starts. Up/Down preserve a Unicode-scalar column across logical lines, including short intervening lines; in single-line inputs they move to start/end. Explicit selection, edits and nonvertical movements reset the preferred column. Insert replaces a selection, and deletion removes a complete scalar or the selection. UTF-8 validation rejects truncated sequences, overlong encodings, surrogate code points, out-of-range code points, stray continuation bytes, and embedded NUL. Valid CR/LF insertions are rejected with `CUI_EDIT_LINE_BREAK` in single-line mode. Rejected mutations leave text, cursor, selection, and history unchanged. An identical replacement changes the selection without adding history. Storage is allocated at creation, with no allocations during editing. Scratch storage uses one buffer capacity. `history_bytes` bounds the combined snapshot payload and metadata; each snapshot costs `capacity + sizeof(snapshot metadata)`. Fewer than two fitting snapshots disables history. `max_history_steps` optionally limits retained edits, with zero using the byte budget alone. Undo and redo restore text and cursor/selection; new edits after undo discard redo. Full history evicts its oldest snapshot. This snapshot design trades memory for straightforward bounded behavior, so large document editors should use a specialized model. The handle itself and scratch storage are outside the history budget. `cui_edit_get_state` reports length, cursor, anchor, undo/redo availability, multiline mode, and a 64-bit content revision. Actual mutations, undo, and redo advance revision; movement, selection, rejected edits, and identical replacements leave it unchanged. Revision wraps modulo 2^64. `cui_edit_get_text` returns a view into the application buffer. `cui_edit_apply_events` processes frame events only when `cui_event_target` resolves to the supplied control ID. It applies text, scalar left/right movement, Ctrl/Alt+Left/Right word movement, Up/Down logical-line movement, Ctrl/Meta+Up/Down document movement, Home/End, Ctrl+Home/End, Backspace/Delete, Ctrl/Meta+A, and multiline Enter. Shift extends movement selections. Disabled input ignores events. Single-line Enter is left to the control's submit behavior. The helper reports the first rejected event while continuing later independent events. Ctrl/Meta+Z and Ctrl/Meta+Shift+Z perform undo/redo; Ctrl/Meta+Y also performs redo. Text events must contain a terminator within their 64-byte payload. Pointer placement, selection painting, clipboard ownership, and shaping belong to later adapters or controls. Unicode scalars are not grapheme clusters: combining marks, emoji sequences, and regional indicators can be split by movement or deletion. Word classification uses fixed, locale-independent letter/combining ranges plus ASCII digits and underscores; it is not full Unicode UAX #29 segmentation. There is no bidi navigation, shaping or grapheme navigation in this model. Textarea supplies pixel-based navigation across wrapped visual lines and guards composing/preferred-character key events; the model alone does not supply a native IME bridge. This provides tested scalar editing primitives and bounded history; it does not claim full Input/Textarea/Editor parity. Optional integration with libgrapheme, ICU, or an IME adapter can extend the model without imposing a mandatory compiled dependency on the core. Tests cover malformed UTF-8, scalar selection/deletion, aliasing insert sources, capacity rejection, history eviction and branching, revision changes, multiline boundaries, routed same-frame events across focus changes, malformed event payloads, and 15000 deterministic mixed Unicode edit operations under address and undefined-behavior sanitizers. Composite inputs can set `delegate_up_down` so an enclosing command palette or combobox owns vertical list navigation. Combobox reserves Up/Down even while closed so an arrow can open its options. Ordinary Input keeps caret navigation, including in read-only mode; disabled inputs ignore it. This explicit delegation prevents the editor from consuming list-navigation keys. --- ## HoverCard, TitleBar and Toolbar examples Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/EXAMPLE_POLISH.md # HoverCard, TitleBar and Toolbar examples HoverCard's default height now fits its children instead of allocating a fixed 120-pixel panel. Positive explicit heights retain their existing fixed behavior (including viewport bounding). Intrinsic cards keep a fixed-width, non-scrolling inner content box so text wraps at the card width even though the outer panel clips overflow. `max_height` optionally caps an intrinsic card; otherwise the viewport is the cap. This does not add scrolling inside a tall card. Collision placement uses context-owned retained measurements of the unclipped inner content, so a temporary clip cannot lock the card to the wrong side of its trigger. First opening, width/theme/max-height changes and `content_revision` changes schedule a redraw to settle placement using the actual height. Each measurement frame is bounded by the remaining viewport extent; near an edge, placement may take subsequent measurement redraws to settle. Stable content stops requesting those redraws. Increment `content_revision` when changing arbitrary children at the same width so a changed height also receives collision-placement redraws. No caller-owned cleanup is required: the context retains only measurements, not the hover state, child callback or child data. Closing/omitting the card allows its measurement resource to be reclaimed by the ordinary context resource lifecycle. The gallery's two-line profile card now uses intrinsic height. Headless tests verify its actual height, longer-content reflow, narrower-width reflow, bounded top/bottom placement, explicit height, optional height cap and closed-card lifetime. The new default-height assertion fails against the original component. The TitleBar gallery now overlays three colored-circle controls in the space reserved by native traffic-light mode. They are explicitly a **browser simulation**, with real semantic buttons that invoke the gallery's simulated window host. Minimize, maximize/restore, close and the optional close callback update a visible preview status. They respect the gallery's disabled switch and hide in fullscreen with an explanatory message. The public TitleBar's native mode still reserves OS controls and does not draw or claim to implement them. No native host/backend or public Chrome policy changed. Toolbar Find now searches a visible three-line document using the actual editor query. Matching lines are highlighted and prefixed with `Match:`, with a matching line count, an empty-query prompt and explicit no-results state. The bounded document uses ASCII case-insensitive substring matching; this is a focused example, not a general Unicode search engine. Ctrl/Cmd+F focuses Find while the preview has focus, yielding to composition/preferred character input and to disabled/hidden Find. The ordinary Input result reports query changes; existing `gallery_toolbar_activations(4)` now exposes that count for the example regression without changing fields 0–3. Disabled input cannot change the query. ## Validation and integration ```sh cmake -S . -B build -G Ninja cmake --build build ctest --test-dir build --output-on-failure python3 scripts/build_web.py --output build/web uv run tests/web/test_example_polish.py --directory build/web --chromium /path/to/chrome ``` Strict-warning native/WASM builds pass. Full native CTest passes 93/94; the only failure is the expected stale generated Content distribution header, which the integrator owns. ASAN/UBSAN Content and Chrome tests pass. The dedicated headless browser regression covers measured HoverCard height, actual colored-circle canvas pixels, simulated host actions and close override, fullscreen hiding, real keyboard Find text input, query-change notifications, highlighted results/no-results and disabled input. It uses pinned Playwright 1.58.0 and an installed Chromium fixture. The integrator must regenerate distribution headers and update the existing broad `test_browser.py` assertion that native TitleBar has zero gallery buttons: the simulation has three outside fullscreen and zero inside fullscreen. No CMake, global documentation, publishing, Alert, Bubble or asset changes are part of this patch. --- ## Design sizes for forms and numeric controls Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/FORM_DESIGN_SCALE.md # Design sizes for forms and numeric controls Styled `cui_number_input`, `cui_form`, `cui_input_group`, and `cui_otp` accept `options.design_size` from `CUI_DESIGN_XS` through `CUI_DESIGN_9XL`. `CUI_DESIGN_INHERIT` is zero and retains the existing `.size` behavior, so existing zero-initialized options keep their dimensions. BASE and MD share metrics. The explicit design scale uses `cui_design_measure` with theme font density (`theme.font_size / 16`). NumberInput also honors its explicit `.density`. NumberInput resolves its font, line height, padding, and height through `cui_input_measure`. Each step button uses one control height of width; its SVG icon uses the design indicator size. Prefix, suffix, and editor text share the resolved font. Choose a width large enough for both step buttons and your text, particularly for the largest sizes. The existing custom `.size` is a legacy alternative; explicit design sizes select the shared metrics. Form scales label and description typography and internal field spacing. Default column gap is three design gaps; row gap is one. Positive `gap_x`, `gap_y`, `label_text_size`, and `label_width` remain explicit overrides. The callbacks for controls, labels, descriptions, and footer receive a borrowed theme copy whose font, control height, padding, and gap match the chosen size. Use those metrics in callback content instead of capturing the original theme. The copy is valid only during the callback; the caller's theme is unchanged. A child that also explicitly chooses a design size resolves that size using the callback theme's font density, so avoid applying the same scale twice. InputGroup applies the shared input metrics to its editor, addons, and loading icon. A positive `.font_size` changes text while preserving design control height and padding. Positive addon widths remain explicit. Inferred addon widths are bounded to their row, and inline addons leave room for the editor. An impossible sum of explicit widths returns `CUI_FORM_INVALID` before input or activation is processed. Narrow groups reduce editor horizontal padding as needed to retain a usable viewport. Addon content is clipped to its bounds; callbacks receive the resolved width. Block-start and block-end addons have independent width budgets. OTP scales cell dimensions, text, intra-group gap, and group gap. Positive `cell_size`, `font_size`, `gap`, and `group_gap` override those defaults. Group gap is three design gaps. Existing grouping, digit input, completion, masking, and blink behavior are unchanged. Core layout stores box gaps in whole logical pixels; SVG raster extents round up fractional design sizes. Invalid design enums or unsupported theme density return the API's existing invalid-argument result before reducers mutate values, drafts, or state. Base APIs and `cui_form_plan` do not interpret the design scale or call theme measurement functions. Styled Form resolves gaps before calling its base planner; custom base-only compositions provide their own metrics as before. --- ## Go builders for the CUI bridge Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/GO_BUILDERS.md # Go builders for the CUI bridge For installable local wheel, npm, Go module and Rust crate artifacts, see the [packaging guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PACKAGING.md). Linux alpha packages are tested outside the checkout; registry publication and other platform packages remain pending. `bindings/go` is a cgo Go module for the portable CUI bridge ABI v1. Its builders cover the native bridge node kinds through Settings, from layout, controls, and overlays to data views and navigation; the sections below specify each implemented surface and its limits. Builders create a detached tree; `App.Mount` validates it and creates actual CUI nodes. `Step` submits the frame, `QueuePointer` and `QueueKey` send synthetic input, and `Dispatch` invokes Go callbacks after the native frame. Change events carry state and copied text captured when queued. Bridge node coverage does not imply full feature parity with the 78-component manifest. Requires Go 1.23 or newer, a C11 compiler, CMake, Ninja, `CGO_ENABLED=1`, and a built CUI bridge shared library. On Linux, build and test from the repository root: ```sh cmake -S bindings/bridge -B build-go-bridge -G Ninja -DCMAKE_C_FLAGS='-Wall -Wextra -Werror' cmake --build build-go-bridge --target cui_bridge test_bridge_core test_bridge_components python scripts/test_local.py --build-dir build-go-bridge -- -R '^bridge_' cd bindings/go CUI_BRIDGE_LIBRARY="$PWD/../../build-go-bridge/libcui_bridge.so" go test ./... ``` The Go package loads `CUI_BRIDGE_LIBRARY` at runtime with `dlopen` on POSIX or UTF-8 decoding and `LoadLibraryW` on Windows, verifies the ABI version and options size, and calls the C bridge through a small cgo shim. `go test` itself uses the headless backend and opens no window. The library path must be absolute (`.so` on Linux, `.dylib` on macOS, `.dll` on Windows). The first loaded bridge remains active for the process lifetime. Linux has been validated. The loader has POSIX and Windows branches; Windows cross compilation with Zig/MinGW succeeds; Windows runtime and macOS remain unvalidated. Example native application, from `bindings/go`: ```sh CUI_BRIDGE_LIBRARY="$PWD/../../build-go-bridge/libcui_bridge.so" \ CUI_TEST_FONT=/absolute/path/to/font.ttf \ go run ./examples/save_changes ``` The native example opens an SDL window and uses an existing TTF font. A finite native smoke check is available as `go run ./examples/native_smoke` inside Xvfb. For automated native checks on Linux, run it only inside an invisible Xvfb display; never point tests at the desktop display. For example: `xvfb-run -a env -u WAYLAND_DISPLAY CUI_TEST_FONT=/absolute/path/to/font.ttf CUI_BRIDGE_LIBRARY=/absolute/path/to/libcui_bridge.so go run ./examples/native_smoke`. The bridge reports unavailable SDL or font failures directly. For SDL glyph coverage, `Options.FontFallbacks` takes up to 32 absolute UTF-8 TTF paths, or call `App.SetFontFallbacks(paths)` to replace or clear the chain. Font loading is transactional: a failed replacement leaves the previous chain active. Font fallbacks require the native SDL backend. The finite smoke example installs its primary font as a fallback to exercise this API. ```go app, err := cui.New(cui.Options{}) if err != nil { panic(err) } defer app.Close() status := cui.Label("Ready").Key("status") button := cui.Button("save").Text("Save").Size(cui.MD) button.OnClick(func(cui.Event) { _ = status.SetText("Saved ✓") }) err = app.Mount(cui.Column("root").GapUnits(2).Children(status, button)) if err != nil { panic(err) } _ = app.Step(1.0/60) ``` `New` locks its goroutine to an OS thread. Call all methods for that app, including `Close`, on that same goroutine; `Close` unlocks it. Until the core's process-global Clay context is synchronized, callers must also serialize calls across separate apps, even when they use different OS threads. Go callbacks execute during `Dispatch`, outside C. Callback panics propagate as ordinary Go panics. Keep a reference to every app and close it explicitly. Strings are copied into C and limited to valid UTF-8, no NUL, and 4096 bytes. Handles are app scoped and rejected after removal or disposal. Gap values are logical pixels; `GapUnits(2)` equals eight pixels. Button design sizes span `Inherit`, `XS` through `Size9XL`. `Checked`, `Value`, `Range`, `Open`, and `Selected` configure selection, disclosure, and numeric components; `QueueText` sends host text input to the focused Input or Textarea. Hover colors use the bridge's existing palette mapping, and ghost custom hover remains unsupported by the bridge. Grouped components use `Item` children. RadioGroup, Tabs, Select, and ComboBox expose a selected Item; Tabs and Accordion Item children form their panels. `Event.Selected` is a copied full handle snapshot for group changes. `Alert` takes title and message. Collapsible and Accordion Item state is available through `App.Checked`. Select uses a name and placeholder; ComboBox uses a label and editable query. Their options are `Item` children. `App.Text(combo)` reads the current query. DropdownButton has separate action and menu areas. Use `App.DropdownPartBounds(button, false)` for the action and `true` for the menu. `OnClick` receives action presses; `OnChange` receives selected `Item` snapshots from menu choices. Dialog, AlertDialog, Sheet, and Popover have `Open` state and `OnClose` callbacks. `Event.CloseResult` reports accepted, cancelled, or closed. Popover requires `Anchor` with a live node before opening. Dialog, Sheet, and Popover children render inside their surfaces; AlertDialog uses its title and description. Tooltip and HoverCard follow their anchor on pointer hover. Both require `Anchor`; HoverCard may contain child content. `App.Open` reads their hover state, and `OnChange` receives open/close snapshots. Visual builders map to native CUI renderers. `VisualSize(width, height)` applies to Avatar, EmptyView, GroupBox, Skeleton, and Spinner, within 0–4096 logical pixels. Avatar and Spinner currently use the width; their height remains renderer-defined. GroupBox accepts children; EmptyView takes a title and description. List, Menu, and Stepper use `Item` children and selected Item snapshots. Stepper Items accept `StepStatus(0..3)` and a detail description. Pagination and Rating expose `Total` and `Value`; `NumericPartBounds` locates a numbered native interaction part for host input and tests. DescriptionList uses `Item(label).Detail(value)` children. Scrollable accepts children, `VisualSize` for its viewport, and `ScrollExtent` for content dimensions. `QueueScroll` sends host wheel input; `App.Value(scroll)` returns the vertical offset, with each change captured in `OnChange`. StatusBar, Toolbar, and TitleBar use `Item` children. StatusBar Item `StepStatus(0/1/2)` chooses left/center/right. Toolbar Items may contain controls; disabling the Toolbar suppresses their actions. TitleBar Items render text labels and do not expose host window controls. Icon takes a catalog name such as `check` and optional `VisualSize`; an unknown name is reported at `Step`. Message renders one filled message body with an optional header and configurable width. A failed mount removes its partial native tree, so a corrected tree can be mounted on the same app. Attachment renders native status and progress metadata from a title, description, `AttachmentStatus`, `Value(0..1)`, and optional visual width. This bridge surface does not expose file transfer, remove, or retry actions. Image accepts decoded RGBA8 pixels with `RGBA(pixels, width, height, stride)` and optional display `VisualSize`. Go copies the input immediately; the bridge copies it again for rendering, so callers may reuse their byte slice. Dimensions must be 1–2048 pixels, stride at least four bytes per pixel, and the exact buffer at most 16 MiB. `SetRGBA` replaces pixels on a mounted image. File decoding remains the application's responsibility. Tree accepts up to 64 flat `Item` children in preorder. `Item.Depth(0..63)` sets indentation and `Item.Checked(true)` starts an item expanded. `Tree.Selected(item)` chooses an Item; `App.Selected(tree)` and `App.Checked(item)` read live state. `Tree.OnChange` receives selection snapshots from pointer or keyboard input. `VisualSize` sets the tree viewport; disabling Tree suppresses interaction. TimeField renders an editable 24-hour `HH:MM:SS` value. Configure it with `Time(Time{Hour, Minute, Second})`, update it with `SetTime`, and read it with `App.Time`. Each native edit emits `OnChange` with a copied eight-character `Event.Text` snapshot; disabling the field suppresses edits. ColorPicker accepts packed `0xRRGGBBAA` with `ColorRGBA`, updates via `SetColorRGBA`, and reads via `App.ColorRGBA`. `App.ColorPartBounds(picker, 1/2/3)` locates the hue, color plane, or alpha part for host input. Native changes emit `OnChange` with the exact packed value in `Event.Value` and a copied `#RRGGBBAA` string in `Event.Text`. Calendar and DatePicker use a validated `Date{Year, Month, Day}`. Set one with `Date`, update with `SetDate`, and query with `App.Date`. `App.CalendarDayBounds` locates a visible day for pointer input. DatePicker can be opened or closed with `Open` and sized by width with `VisualSize`. Native selections emit `OnChange` with numeric `YYYYMMDD` in `Event.Value` and copied `YYYY-MM-DD` in `Event.Text`. The current bridge uses English single-date mode. OTPInput uses `Total(1..256)` for its target cell count (default six), `Text` or `SetText` for its current value, and `App.Text` to read live edits. Queued text input to a focused OTPInput emits `OnChange` with a copied text snapshot. Configure `Total` before `Text`; changing `Total` on a mounted input resets its value. Form accepts up to 64 `Item` children. Each Item's text and detail become a field label and description, and its children render as the field controls. `Form.VisualSize(width, 0)` sets its width. Disabling either the Form or an Item suppresses descendant control input. The bridge does not supply form validation or nested Forms. InputGroup combines an editable value with `Item` button addons. Set its placeholder with `Detail`, width with `VisualSize`, initial value with `Text`, and read edits with `App.Text` or copied `OnChange` snapshots. Each addon may use `StepStatus(0..3)` for inline start/end or block start/end and `OnClick` for its native action. Disabling the group suppresses editor and addon input. Notification creates one retained in-app card from a title and message. `Open(true)` presents it; `App.Open` reads its state. `OnClick` receives a card press, and `OnClose` receives its completed close transition. The bridge does not deliver OS notifications or provide action buttons or automatic hiding. FocusTrap contains arbitrary child nodes. `Open(true)` activates a native modal focus scope that blocks pointer interaction outside its subtree; `Open(false)` restores ordinary input. `App.Open` reads its live state. It does not create a visual dialog surface by itself. MessageScroller accepts up to 64 `Item` children. Item text is the message body, `Detail` is the sender, and `StepStatus(0/1)` selects incoming or outgoing. `VisualSize` sets the viewport. After the first `Step`, `App.Value(scroller)` reads the live vertical offset and `SetOffset` changes it; `OnChange` receives native offset changes. The initial frame follows the newest message. Carousel accepts up to 64 `Item` slides with text or child content. `VisualSize` sets the viewport, `Selected(item)` changes the slide, and `App.Selected` reads it. Native wheel, drag, and keyboard navigation emit `OnChange` with a full selected Item handle snapshot. The bridge currently uses horizontal orientation and does not support nested Carousels. Resizable accepts up to 64 `Item` panels in a horizontal split. Set an Item's initial width with `PanelSize(100..4096)`, read its live width with `App.Value(item)`, and locate a divider with `App.ResizableHandleBounds(group, precedingItem)`. Dragging a divider emits `OnChange` on the resized Item with numeric `Event.Value`. `VisualSize` configures the group and `Disabled(true)` suppresses dragging. TextView renders owned Markdown (default), HTML, or plain source. Use `Format(Markdown/HTML/Plain)`, `Text` or `SetText`, and `VisualSize`. `App.SelectText(view, anchor, cursor)` selects rendered UTF-8 byte offsets; `App.CopySelection(view)` returns plain selected text. Pointer selection emits `OnChange` with a copied selected-text snapshot. Disabled TextView suppresses pointer selection. Editor owns a multiline UTF-8 buffer. `Editor(key, source, language)` sets initial text and language metadata; `VisualSize` sets its viewport. `App.Text` reads live content and `OnChange` receives copied text snapshots. The current bridge limits content to 4096 bytes and 512 lines and does not expose completion, syntax callbacks, search, or clipboard actions. Chart renders caller-supplied `ChartDatum{Label, Value}` data as line, area, bar, or pie via `ChartKind`; `Data` and `SetData` copy at most 64 points into native storage. `App.ChartDatum` reads a copied point back. Labels are valid UTF-8 up to 128 bytes, values are finite and within ±1e9, and pie values must be nonnegative. `VisualSize` sets its dimensions. The bridge draws a native raster with hover feedback and a "No data" empty state; it does not fetch data. Table is a compositional native table: its `Item` children are rows, and each row's `Item` children are text cells. The first row renders as a header. `VisualSize(width, 0)` sets its width; cell `SetText` updates the next frame. Sorting, selection, and virtualization belong to DataTable rather than this basic Table. DataTable uses `TableData(headers, rows)` or `SetTable` with 1–16 columns and up to 32 rows; every cell and header is valid UTF-8 up to 128 bytes. Go and the bridge copy the matrix. `SelectionMode(SelectRows/SelectColumns/SelectCells)` chooses native row, column, or cell selection. `App.DataTableCell`, `DataTableCellBounds`, `DataTableHeaderBounds`, and `DataTableState` expose live data and hit targets. Native selection and header presses emit `OnChange`; `DataTableState` reports one-based selected row/column and sort column/direction. Sorting is a signal: the application must reorder and re-supply its rows. DataTable `OnChange` also includes a copied JSON `Event.Text` snapshot with `reason`, `row`, `column`, `sortColumn`, and `sortDirection`. Parse that payload when a callback needs the exact queued transition rather than a later live state. Plot accepts up to 256 finite `PlotPoint{X, Y}` values within ±16384 via `Points` or `SetPoints`; Go and the bridge copy the points. `App.PlotPoint` reads one point and `VisualSize` sets the viewport. The native plot currently draws themed dots; axes, paths, and hit interactions are not exposed. Command accepts up to 64 `Item` actions. Item text is the label and `Detail` supplies one filter keyword; `Command.Text` or `SetText` changes the query, and `App.Text` reads it. `App.CommandItemBounds` locates a visible action for pointer input. Native filtering and keyboard navigation update `App.Selected(command)` and emit `OnChange`; an Item's `OnClick` receives confirmation. Grouped/custom rows and host action execution are application responsibilities. Sidebar accepts up to 64 `Item` navigation actions. `Open` controls the collapsed state, `VisualSize` sets its size, and `App.Selected(sidebar)` reads the active Item. A native press emits a Sidebar `OnChange` event with an exact `Event.Selected` snapshot and an Item `OnClick` event. Disabled Items do not activate. `App.ThemePresets()` lists names from the loaded bridge. `SetThemePreset(index)` applies one to subsequent frames, and `ThemePreset()` returns the selected index plus a `bool` indicating whether an explicit preset was chosen. The default theme has no selected preset index. `RootView(key)` can be mounted as the sole root container. It renders child widgets in the native root surface; `RootPadding(0..256)` sets its content padding before or after mounting. Row and Column roots remain available. SDL apps expose the system clipboard with `SetClipboard(text)` and `Clipboard()`. Text is copied, valid UTF-8 without NUL, and limited to 64 KiB. Headless apps return a backend-unavailable error. The native smoke example checks small, empty, and exact 64 KiB Unicode SDL round trips under invisible Xvfb. Speech renders a native speech button and retains a transcript. The host supplies recognition results through `StartSpeech`, `ReportSpeech(text, finalPhrase)`, and `FinishSpeech`; `SpeechTranscript` reads the current copied text. `OnChange` snapshots start, report, and finish transitions in `Event.Value` (0, 1, 2), with copied transcript text. The bridge does not capture microphone audio or run speech recognition. Reports are valid UTF-8 up to 4096 bytes. Questionnaire accepts 1–16 `Item` questions, each with `Item` choices, up to 256 choices total. Configure question flags with `Item.Question(required, multiple)` before the first frame. `QuestionnaireState` returns the current question and completion flag; `ChoiceSelected`, `NextQuestion`, `PreviousQuestion`, and `SubmitQuestionnaire` expose native state/navigation. Submit rejects unanswered required questions, emits one completion event on the first successful call, and emits a submit event on each successful call. `OnChange` carries copied JSON in `Event.Text`: `event`, `item`, `current`, `complete`, and one-based `selected` choice indices. The schema freezes after its first frame; this bridge surface does not support dynamic question/choice edits. Dock accepts up to 64 `Item` panels, whose child widgets render as panel content. `VisualSize` sets its viewport; after the first frame, `ActiveDockPanel`, `ActivateDockPanel`, `DockPanelBounds`, and `MoveDockSplit(panel, reference, DockHorizontal/DockVertical, ratio, before)` access the native model. `SerializeDock` returns a copied model string for inspection. Activating a panel emits `OnChange` with a full `Event.Selected` handle. Panel schema freezes after the first frame; serialized-model restore and drag docking are not exposed by this bridge API. Settings contains up to eight `Item` pages, each with up to eight `Item` groups, containing Switch, Checkbox, Input, or NumberInput fields. Totals are limited to 32 groups and 128 fields, with at most 16 fields per group. Page/group text supplies headings; boolean field text supplies its title, while Input and NumberInput use `Detail(title)` so `Text` can hold the editable value. `Query(text)` filters native navigation using up to 256 UTF-8 bytes. After the first frame, `SettingsPage`, `SetSettingsPage`, `SettingsFieldBounds`, and `ResetSettingsPage` access native page and field state; page `OnChange` carries an exact selected handle and field changes use their existing copied event values. Reset restores values captured at first render and emits field changes. Page/group topology and titles freeze after that frame; only individual fields support `Disabled`. The bridge does not provide host persistence or custom fields. VirtualList accepts up to 64 keyed `Item` rows with fixed 32-pixel height and an overscanned viewport. `VisualSize` sets its viewport, `Value` sets a vertical offset, and `App.Value` reads the live offset. `App.VirtualListItemBounds` returns bounds only for a visible row. Native wheel and keyboard scroll emit `OnChange` with the offset; disabling the list suppresses scrolling. The composed workspace example lives at `bindings/go/examples/workspace`. From `bindings/go`, run `CUI_BRIDGE_LIBRARY=/absolute/path/to/libcui_bridge.so go run ./examples/workspace --headless` to validate native hit targets, Account/Preferences tab navigation, name editing, notifications checkbox, an older birthday, save dialog, and status update without opening a window. To use the SDL UI, run `CUI_BRIDGE_LIBRARY=/absolute/path/to/libcui_bridge.so go run ./examples/workspace --font /absolute/path/to/font.ttf`. Automated SDL runs on Linux must use invisible Xvfb, for example `xvfb-run -a env -u WAYLAND_DISPLAY CUI_BRIDGE_LIBRARY=/absolute/path/to/libcui_bridge.so go run ./examples/workspace --font /absolute/path/to/font.ttf`; native mode remains open until the user closes its window. ## Packaged build-time CUI bridge The canonical module path is `github.com/mattmezza/cui/bindings/go`. Linux cgo builds compile separate CUI translation units from the tracked SDK and statically link the bridge by default. `go build -tags cui_native` adds SDL3, FreeType and HarfBuzz through pkg-config; portable builds open no window. A copied executable needs no CUI checkout or runtime compiler, while native system libraries and a font remain required. Explicit `Options.Library` or `CUI_BRIDGE_LIBRARY` still selects a shared bridge. The optional `cui_dynamic` build tag uses packaged shared-library discovery and its verified cache. See [local artifact install commands](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PACKAGING.md) for source-only module ZIPs, optional prebuilt modules, and release/tag limitations. ## Hidden native windows `New(Options{Native:true, FontPath:font, InitiallyHidden:true})` passes hidden creation to SDL before the first frame. The zero option stays visible. Use `app.SetWindowVisible(true)` and `app.WindowVisible() (bool, error)` on the owning UI thread, outside Core stepping; handlers dispatched after a native callback frame may use them. Headless hidden requests/control return unavailable. The Go loader resolves the new symbols optionally: default apps still load older ABI1 libraries; feature calls fail explicitly if unavailable. See the [shared contract and Linux proof](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BINDING_BUILDERS.md#native-window-visibility). Existing Go Options keyed literals remain source compatible; unkeyed literals need the new field. ## Bounded typed root shadows See [typed root shadow authoring](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_SHADOWS.md) for the six-kind implementation, owned values, canonical CSS/preset factories and explicit clear/reset behavior. Focused portable runtime tests cover this subset; integration remains pending. This does not expose compound parts or portals. For bounded semantic ROOT/MAIN/indicator/track/thumb authoring, read [typed part shadows](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_PART_SHADOWS.md). Slider has no thumb; owner topology, whole-group naming and separate reset are explicit parts of that contract. --- ## Hover model-open observers Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/HOVER_EVENTS.md # Hover model-open observers Include `cui/cui_hover_events.h` for `cui_hover_update_events`. This additive pure Base adapter preserves `cui_hover_update` and all its parameters, state and timing. It observes actual model-open transitions for shared HoverCard/Tooltip policy. It does not report painted visibility, rendered geometry, animation completion, input acceptance or controlled requests. Styled `cui_tooltip_events` and `cui_begin_hover_card_events` add final-model observation around existing composition; see below and the [checkpoint](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/LIFECYCLE_RESULT_EVENTS_SLICE.md). ```c #include typedef struct { bool details_open; } model; static void open_changed(void *user, const cui_hover_lifecycle_event *event) { model *app = user; app->details_open = event->open; /* Copyable notification, no acceptance return. */ } cui_hover_event_result update_details(cui_hover_state *hover, model *app, bool trigger_hovered, bool content_hovered, bool focused, bool escape, bool disabled, float dt) { return cui_hover_update_events(90, hover, trigger_hovered, content_hovered, focused, escape, disabled, dt, .3f, .2f, (cui_hover_handler){open_changed, app}); } ``` The application owns persistent `cui_hover_state`; the function owns no context, clock or listener. Supply timing and boolean facts as with the old pure reducer. Do not call this and the old reducer on the same state/timestep merely to inspect both results: that advances policy twice. Omission does not advance timers or invoke a late callback. Multiple calls advance according to their supplied dt; there is no implicit once-per-frame guard. `valid` requires a nonzero metadata target and nonnull state. Invalid arguments return a zero result before any state/callback work. Other parameters keep legacy policy: finite positive dt advances elapsed, invalid/nonpositive dt does not; nonfinite or negative delay becomes zero. `control_result` is the exact legacy bool (entry open differs from final open), not successful submission. The explicit `changed` flag independently records the same entry/final comparison even without a handler; it is distinct from Styled composition admission. Pending, target, elapsed or suppression-only changes are not open transitions. One actual open transition invokes the optional handler once, after reduction, with frozen `previous_open` and `open`. `change_count` counts actual observer calls, zero or one; `count_overflow` is always false. Missing handler preserves ordinary state mutation and `control_result`, with count zero and `changed` still observable. Reading a result does not invoke another observer. Callback does not veto or confirm the state change. Disabled pure policy closes an open state and may notify. Escape closes and suppresses reopening until trigger/focus/content facts are absent. This function has no UI ancestry or routing: disabled closing is a model transition, not accepted user input; it cannot identify inert/layout-only frames or promise UI callback suppression. The Styled adapters handle those boundaries separately, below. Payload metadata is LIFECYCLE with the supplied target and UNKNOWN source. All presence flags are clear: no context/frame/index/activation/reason is inferred from policy booleans. The metadata target is application-selected stable identity, not a new ID allocator. The pointer-free payload can be copied beyond callback and state lifetime; it does not retain state, context or application resources. Handler, user and payload pointers are borrowed only through the call. No handler is retained while a delay is pending. The callback can update unrelated owner state, but must not mutate the active hover state, recursively run its reducer, free active storage or unwind a foreign exception through C. Defer active-resource teardown until the call returns. No runtime lifetime/reentrancy guard is added. Tests prove explicit delay/reversal/content-hold/close/suppression/reentry/focus/ disabled sequences, missing handlers and repeated-state counts; compare all state fields and legacy bool across 576 combinations/steps with finite, negative, NaN and infinite timing/delays; verify invalid target/null-state atomicity, metadata absence and copied payload after state deallocation. Strict C11 Release/C++ header and ASan/UBSan checks run alongside existing content regressions through the private test wrapper. Sanitizer validation uses prebuilt instrumented Core/software archives, not a new full-project sanitizer build. No Focus Trap, virtual-window completion, MessageScroller, bridge producer or language callback is added. Existing binding notification allowlists remain unchanged. This is a bounded model observation slice, not full-family or uniform coverage of all 78 manifest families. The explicit `changed` field extends the unreleased event-result layout. Rebuild consumers rather than mixing earlier objects; no legacy result/layout changed. ## Styled Tooltip and HoverCard ```c cui_hover_event_result tooltip = cui_tooltip_events( ui, tooltip_id, theme, &tooltip_state, cui_string("Help"), options, (cui_hover_handler){open_changed, app}); (void)tooltip; cui_hover_event_result card = cui_begin_hover_card_events( ui, card_id, theme, &card_state, cui_string("Details"), card_options, (cui_hover_handler){open_changed, app}); if (card.control_result) { /* Arbitrary child controls/content keep their own event contracts. */ cui_end_hover_card(ui); /* Existing end, exactly once on true admission. */ } ``` Both functions call their legacy counterpart once, then compare the final model. `control_result` is the exact old Tooltip bool or HoverCard begin admission; `changed` independently compares entry/final open state, even without a handler. `valid` requires nonnull context/theme/state and nonzero ID, not successful geometry, resources, paint or full-frame completion. Invalid arguments reject before model work. Missing observers preserve state/composition with count zero. Callback count remains zero/one and overflow false. Placement can force the model closed after delayed policy opens it. Closed→open→ forced-closed within one call is net-zero and silent. Conversely intrinsic card measurement resource failure can return false with the model open: `changed=true`, `control_result=false` and one OPEN model notification are valid. The callback does not claim that a portal was composed or displayed. Never condition HoverCard end on `changed` or callback count; pair only on `control_result`. Notification follows the complete legacy Tooltip call or the legacy HoverCard begin decision, **before arbitrary HoverCard children**. It is not a deferred end callback. Do not call the new Base observer internally/on the same state first; that would advance delay twice. Original content, placement, measurement redraw, trigger description, child semantics and end balancing remain unchanged. Styled metadata has only HAS_FRAME with the genuine nonzero local frame sequence; UNKNOWN source, no source-presence/index/activation/reason. Delays, focus, geometry fallback and several inputs may contribute. Frame-zero inert/layout-only/protected work keeps legacy maintenance and `changed` results but suppresses observers. Calling UI composition from protected measurement is still unsupported: the adapter does not hide the old lifecycle diagnostic or grant permission to do it. Legacy Escape policy scans globally without filtering consumed/repeated/modified keys. This adapter preserves it rather than changing routing. Trigger focus opens; HoverCard can hold open for panel hover/contained child focus, Tooltip cannot. Omission does not close model state or retain handlers for a later close. The original hover-state/options/text and arbitrary child storage obligations remain; users/payloads are callback-borrowed, not retained during pending delay or measurement redraw. Do not mutate active hover/trigger/input/options, recursively compose, free active resources or destroy the context during callbacks. Styled tests compare old/new paint command geometry/colors/text size, panel bounds, state and semantics; prove pointer delay, contained child focus, global consumed repeat Escape, disable close, missing handlers, omission, viewport/anchor fallback, resource-capacity failure, inert/layout-only maintenance, protected-measurement suppression with unchanged legacy diagnostic, and copied payload lifetime. Strict Release and ASan/UBSan private-wrapper runs include Base and legacy content regressions; sanitizer checks reuse instrumented Core/software archives. No actual visibility/presentation, retained listener, bridge producer or foreign callback is claimed. --- ## IDs and lifetimes Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/IDS_AND_LIFETIMES.md # IDs and lifetimes The declarations and comments in `include/cui/cui.h` are authoritative. Layout, semantics and interaction share stable application identity across frames. Nonzero layout IDs must be unique within a frame; semantic IDs must also be unique. A semantic control normally owns the box with its matching ID. Zero is an anonymous layout ID, not an interactive identity. Duplicate public IDs and collisions in the internal layout ID mapping report errors. For repeated rows, scope by a persistent record key, not its display position: ```c if (cui_push_id(ui, message_key)) { cui_begin_box(ui, cui_id_from(ui, "row"), (cui_box){.width = -1}); /* Submit this record's children using local keys such as "subject". */ cui_end_box(ui); cui_pop_id(ui); } ``` Keep `message_key` distinct for each record. Reordering records then preserves identity. Generating an ID does not open an ID scope; nesting boxes does not replace explicit scoping. Balance only successful `cui_push_id` calls. | Data | Required lifetime | | --- | --- | | Application values, editable buffers, controlled models | Across frames while used; application owns them | | Submitted text and semantic names | Copied into bounded frame storage during submission | | Draw list and semantic snapshot | Borrowed until the next `cui_begin_frame`; render/read first | | Bitmap pixel data | Borrowed until renderer completion; update its revision when changing cached content | | Callback user data | Alive whenever the callback can run; follow each component's contract | | Font and host/context objects | Font alive during measurement/rendering; destroy in reverse ownership order | Queue host events before beginning the frame. Interaction targets and bounds queried during submission come from the previous completed frame; the first frame has no targets. Completed semantics describe current layout. Render the completed draw list before beginning another frame. Do not retain pointers into frame strings or snapshots as durable app state. Component models and optional resource/session APIs have additional ownership rules in their public headers. --- ## IME composition Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/IME.md # IME composition CUI supports a reusable single-selection composition session for Input, Textarea, Editor and Questionnaire input controls. Native SDL and the web gallery transport preedit updates, the selected preedit range, commit and cancellation. Preedit is rendered with an underline and selected range; it does not modify the edit document or emit document-change callbacks until commit. Commit is one undo step when edit history is enabled. Cancellation leaves document, original selection and history intact. Starting composition separates typing groups on either side. ## Public byte offsets and bounded ownership `CUI_EVENT_COMPOSITION_START`, `UPDATE`, `COMMIT` and `CANCEL` use `text_data` and `text_length` for arbitrary-length UTF-8 within configured bounds. Legacy inline `text[64]` remains available. `composition_anchor` and `composition_cursor` are UTF-8 byte offsets in preedit, not offsets in the document. They must lie on scalar boundaries. `cui_queue_event` deep copies payload bytes before returning; caller storage can immediately be changed or released. Dispatched payloads remain valid until the next `cui_begin_frame`, including while queuing that next frame. `cui_config.event_text_bytes` bounds aggregate queued bytes (zero defaults to 65536). Queue overflow/allocation failure returns false and reports `CUI_ERROR_CAPACITY`, without partially enqueueing an event. `cui_edit_composition_event` uses a caller-owned `cui_edit_composition` with separate preedit and rendered snapshot buffers. Buffers must remain alive and disjoint from the model and session. Set `buffer`/`capacity`, `view_buffer`/`view_capacity`, and zero the remaining fields before first use. Capacities include a trailing NUL. Attach its pointer to `cui_input_state.behavior.composition` or `cui_textarea_state.composition` (Editor uses `editor.view`). Leave `composition_owned` false for caller-owned storage. Built-in controls lazily allocate a retained default resource when composition first arrives, bounded to 4095 preedit bytes. Styled Input, Textarea, Editor and Questionnaire enable `grow_view`: their edit model privately owns rendered storage sized from the actual document plus preedit and grows geometrically when needed. There is no 65535-byte document limit for these built-in consumers. Growth is bounded by the model's configured document capacity plus bounded preedit capacity; overflow or allocation failure returns `CUI_EDIT_CAPACITY` before changing the previous visible preedit or document. Snapshots are built only on successful composition updates; idle view reads reuse the existing snapshot. The default UI resource remains included in `resource_bytes`; dynamic rendered storage is owned by the edit model and freed by `cui_edit_destroy`, independently of UI resource collection. Its borrowed view is valid until the next composition update/growth or model destruction. The session's original `view_buffer` remains caller/UI-resource owned and never points at freed model storage. A retained session rebound to a replacement model discards its old active composition. Keep session and preedit buffers alive during use, and do not use borrowed views after model destruction. Caller-owned sessions retain their explicit fixed rendered-buffer bound unless they opt into `grow_view`; this flag also allows an initially null rendered buffer. Applications needing larger preedit must attach appropriately sized caller buffers. Fixed rendered capacity failure likewise preserves composition and document. No adapter truncates text to 63 bytes. A reusable headless consumer can call `cui_edit_composition_view` and `cui_edit_composition_selection` to paint the temporary document and caret. `composition_target` optionally identifies the originating focused control; the core drops stale host updates/commits addressed to another focus. SDL captures this owner and rejects text input between window focus loss and regain; the browser rejects composition commits after a canceled session. Untagged manually queued events use the current focus. Read-only, disabled, unfocused and removed controls cancel their session. External document revision or selection changes invalidate the old replacement range. Keys and ordinary text events yield while composition is active. Pointer selection cancels preedit before moving the document selection. Multiple active selections reject composition with `CUI_EDIT_INVALID_ARGUMENT`; CUI does not claim multi-cursor IME parity. Token annotations and folds are temporarily excluded from preedit layout; committing retains the model's normal atomic token replacement policies. ## Host adapters and validation `cui_set_text_input_rect` / `cui_text_input_rect` expose the last painted focused caret in logical pixels. SDL polling forwards this rectangle to `SDL_SetTextInputArea`; browser input positions its native textarea at this caret. SDL `TEXT_EDITING` selection offsets are Unicode scalar counts: the pinned SDL source converts Cocoa UTF-16 to UTF-32 counts and Wayland byte positions with `SDL_utf8strnlen`. CUI converts those counts to UTF-8 bytes. Provenance: [SDL Cocoa keyboard](https://github.com/libsdl-org/SDL/blob/7f3ae3d57459e59943a4ecfefc8f6277ec6bf540/src/video/cocoa/SDL_cocoakeyboard.m), [SDL Wayland events](https://github.com/libsdl-org/SDL/blob/7f3ae3d57459e59943a4ecfefc8f6277ec6bf540/src/video/wayland/SDL_waylandevents.c). The browser bridge converts native textarea UTF-16 selection offsets to UTF-8 bytes, commits `compositionend` once and excludes composing key shortcuts. The host receives the preceding frame's caret rectangle; candidate presentation and virtual keyboard behavior remain browser/OS dependent. Numeric uses an optional `cui_number_state.composition` caller session or a lazy UI-owned default with 4095 preedit bytes and model-owned rendered storage. It renders arbitrary valid preedit without changing the numeric draft/value. Commit uses the existing normalization (ASCII plus the already-supported fullwidth digits/signs/decimal point and ideographic decimal point), existing prefix grammar and 127-byte draft bound. Invalid commit leaves the previous preedit and draft intact. One successful composition commit is one edit history transaction; Ctrl/Meta-Z, Shift-Z and Y support Undo/Redo. Existing Enter/blur clamping remains in effect. Read-only/disabled/focus loss and controlled-source or edit-model replacement cancel composition, and stale commits remain suppressed until a new start/update. Caller sessions keep the reusable edit-session lifetime rules above. OTP uses `cui_otp_state.composition`, optionally pointing to a zero-initialized caller-owned `cui_otp_composition` with `buffer`/`capacity` (including NUL). Keep both alive and disjoint from the OTP value/state during use. Otherwise it lazily retains a UI-owned default with 4095 preedit bytes, accounted in `resource_bytes`. The default pointer is internal to the UI resource lifetime; do not dereference it after UI destruction or retain it outside the widget state. Each frame renews the resource, so omitted-widget collection cannot leave a dereferenced old resource. Caller-owned sessions and buffers remain caller-owned. OTP deliberately preserves its existing first-scalar filtering: only the first ASCII or fullwidth digit in a commit is normalized and appended. Trailing scalars are ignored (`"34"` appends `3`, `"2x"` appends `2`); an invalid first scalar (`"x3"`) is ignored. Multi-digit composition commits are therefore limited to one digit, as in the pinned reference `crates/base/src/otp_input.rs`, `edit_value` (`chars().next()`). Preedit paints only the first eligible proposed scalar in the next cell; masked preedit reuses the existing `*` rendering and never draws raw preedit digits. Selected ranges use UTF-8 byte boundaries; the cell caret is clamped to that proposed scalar and published for the host candidate rectangle. Full OTP targets ignore further input. Buffer exhaustion reports `CUI_EDIT_CAPACITY` before any append/callback and preserves preedit. A successful append reports one change and, when it fills the target, one completion. OTP has no Undo history. Cancel, disabled/focus loss, and document pointer/length/content fingerprint changes discard preedit without modifying the value. Normal composing shortcuts yield; stale commits after source replacement or a successful commit are ignored until the next start/update. OTP has no read-only option. Reference behavior was inspected in the frozen upstream source `crates/base/src/input/base/state.rs` (`marked_text_range`, `unmark_text`, `replace_text_in_range`, `replace_and_mark_text_in_range`). upstream may mutate marked text transactionally; CUI's explicit virtual snapshot keeps document mutation at commit. This is substantive single-selection input support, not full SDK parity with surrounding-text reconversion, platform replacement ranges or candidate UI. Headless unit tests cover Unicode/emoji ranges, queue deep-copy lifetime, bounded failure, large caller buffers, cancellation, external drift, single undo and multiple-selection rejection. Large-document tests cover more than 200000 bytes, owned allocation growth, idle reuse, scrolling, commit/Undo and model rebinding. `tests/web/test_ime.py` uses Chromium CDP native `Input.imeSetComposition` and `Input.insertText` for all four text consumers; it also checks read-only and blur/disabled cancellation. `tests/web/test_ime_additional.py` covers Numeric/OTP/Combobox through real CDP composition, Numeric Undo, masked OTP first-scalar commit, cancel and disable. Native headless Numeric/OTP tests cover filtering, trailing payload, callback counts, caller capacity, source replacement and stale-focus rejection. SDL injected preedit checks scalar-to-byte conversion with an emoji and an accented scalar. Linux and Chromium are exercised here; macOS/Windows native IME UI remains unverified. --- ## Additional text consumer IME audit Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/IME_ADDITIONAL_AUDIT.md # Additional text consumer IME audit Audited source: `b6fbb70`, isolated branch `audit/ime-additional`. The initial audit added no implementation changes; the follow-up below records the scoped fix. The existing four-consumer IME test does not establish IME support for Numeric or OTP. | Consumer | Browser native composition | Commit/cancel | Candidate caret | Disabled/read-only | | --- | --- | --- | --- | --- | | Numeric (`NumberInput`) | Focus reaches the bridge; preedit is missing | Composing `57` leaves initial value `42`; cancel preserves it | Available from input painting | Disabling releases the bridge and preserves value; read-only source policy only | | OTP (`OtpInput`) | Focus reaches the bridge; preedit is missing | Composing `7` leaves digit count zero; cancel preserves it | Missing (`gallery_ime_rect(0) == -1`) | Disabling releases the bridge and preserves value; no read-only option | | Combobox | Preedit `ap` appears without changing query | Commit produces two query bytes exactly once; cancel preserves query; one Undo restores empty query | Available | Disabling active composition preserves query and releases the bridge; no read-only option | These results use Chromium's `Input.imeSetComposition` and `Input.insertText`, which dispatch real DOM composition events to the focused host textarea. The script records native start/update/end events, including nonempty commit and empty cancellation. It does not fabricate CUI mode flags or DOM composition objects. Tests select Numeric's existing draft before committing a different value, avoiding a false pass when initial and committed values match. OTP uses one ASCII digit so the failure cannot be explained by unsupported nonnumeric characters. The Combobox check exercises the single-selection gallery story; multiselect and large-query capacity are not established by this audit. Run the strict regression with an existing gallery build and installed Chromium: ```sh uv run tests/web/test_ime_additional.py --directory /tmp/cui-next16-integration/build/web \ --chromium /home/matteo/.cache/ms-playwright/chromium-1228/chrome-linux64/chrome ``` The observed result is **five failed requirements**, collected before exit status 1: Numeric preedit and commit; OTP preedit, caret and commit. Combobox's checked requirements pass. Cancel and disabled-state checks pass, but do not prove a working composition session for consumers that ignored its creation. Browser runtime errors were absent. The failures intentionally remain strict assertions for future fixes; this script is not registered as a passing CTest check. ## Source findings and native implications * `src/base/cui_numeric.c`, `cui_base_number_input`, handles `CUI_EVENT_TEXT` and keyboard editing directly. It neither creates a composition session nor reduces composition events. It reads the legacy inline text array rather than the variable payload. Its existing numeric grammar, draft/controlled-value transition and Enter/blur commit behavior need an explicit composition policy. Numeric's `readonly` option blocks its editing loop and stepping; the gallery does not expose that option, so this audit makes no browser read-only claim. * `src/base/cui_otp.c`, `cui_base_otp`, handles only ordinary text and Backspace. The ordinary-text branch converts one accepted digit per event from the inline text array. Composition events are ignored. OTP also lacks a model composition session and candidate caret publication. A future commit path must define how multiple digits, capacity and completion callbacks are processed atomically; this audit does not infer those policies from ordinary typing. * `src/base/cui_choice.c`, `cui_choice_reduce_combobox`, delegates query editing to `cui_base_input_ex` with retained `query_behavior`. The default composition session is therefore available. `src/components/cui_choice.c`, `cui_choice_paint_query`, passes that behavior to `cui_input_paint`, which renders preedit and publishes the caret. Filtering uses the committed query, preserving document/query semantics during preedit. The base-created default retains its fixed rendered buffer; it does not opt into the new styled Input default's dynamic snapshot sizing. This audit does not claim large-query support. * `backends/sdl3/cui_sdl3.c` converts active SDL text editing into composition update/cancel, and the following SDL text input into composition commit. Numeric and OTP's shared reducer omissions therefore also affect native SDL IME input. Native SDL injection was not added in this two-new-file audit scope; this is a source-supported implication, not a measured platform IME result. * `web/gallery.js`, `syncImeTarget`, enables the native bridge for every focused, enabled semantic textbox. Bridge focus alone does not imply that its CUI consumer handles composition. Numeric and OTP are concrete examples. OTP and Combobox public options have no read-only field. Disabled controls were checked through the existing gallery control. Numeric read-only coverage requires a dedicated host fixture or an authorized gallery option addition. ## Validation Fresh portable warning build succeeded without warnings. Full native CTest ran 90 checks: 89 passed; only `distribution` failed because the base's generated headers are stale. Distribution regeneration belongs to the integrator and was not performed in this audit. The strict browser audit fails for the five product gaps above. Only this document and `tests/web/test_ime_additional.py` were changed. ## Scoped Numeric/OTP follow-up The isolated implementation branch starts at `46d7010`. Numeric now retains an edit composition session, renders it through existing input painting, normalizes commit through existing Numeric filtering and groups it into one Undo transaction. OTP now retains bounded preedit, paints the first eligible proposed scalar using its existing mask, publishes the focused cell caret and consumes composition commit. Source/focus/disabled changes cancel; Numeric also cancels for read-only. OTP retains the pinned reference's first-scalar policy: trailing scalars ignored, invalid first scalar ignored, full target ignored, actual buffer exhaustion atomic. This does not promise whole-string or multi-digit OTP composition. The strict CDP audit now passes all original requirements and additionally checks Numeric one-step Undo plus masked fullwidth OTP commit (only its first digit). The mask control is an HTML checkbox: the test explicitly refocuses the canvas OTP before invoking native composition, so it exercises the intended host textbox. The original four-consumer native CDP regression also passes. Headless tests cover ASCII/fullwidth/trailing/invalid-first filtering, callback counts, capacity and UTF-8 boundaries, masking, composing shortcuts, stale focus and source/model replacement. Four focused ASAN/UBSan tests pass. Warning build is clean; full CTest passes 90/91, with only expected stale generated distribution failing. No shared Core/SDL/browser implementation or distribution files were changed. The Combobox large-query and Numeric browser read-only fixture limitations above remain unverified. Native platform UI behavior remains source-supported rather than tested through an OS IME in this follow-up. --- ## Frames, state and callbacks Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/IMMEDIATE_AND_STATE.md # Frames, state and callbacks CUI uses immediate frame composition with persistent application and context state. Call components inside `cui_begin_frame` / `cui_end_frame`; they submit this frame's layout, draw commands and semantics. Keep values and long-lived models across frames. These are two parts of the same API, rather than separate immediate and retained rendering engines. ## What persists for each kind of component | Components | Frame composition | Application state retained across frames | | --- | --- | --- | | Button, Label, Badge, Avatar, Separator | Call the component each frame | Usually no separate control model; keep application data such as click counts | | Checkbox, Radio, Switch, Toggle, Slider, Rating, Pagination | Submit with the current value | Boolean, enum, number or selected page; animated controls may also use an explicit state struct | | Input, Textarea, Editor model | Submit an editable control | `cui_edit` and its application-owned buffer; styled input/textarea behavior and layout state | | Dialog, AlertDialog, Sheet, Popover | Submit while its surface is active | `cui_surface_state`, open state, decision result and any form data | | Select, Combobox, Menu | Submit trigger and current popup contents | Choice/menu state, selected values and query editor where applicable | | DataTable, Tree, Chart, TextView, MessageScroller | Compose visible content from the model | Data, keys, selection and the explicit model/state required by the public header | | VirtualList, Dock, Plot infrastructure | Use the model to compute geometry/ranges for a frame | Virtual-list/dock handles or application-owned plot scales/data; their current gallery stories demonstrate partial base models | A retained data model is not a retained application widget tree. CUI's context also retains focus, prior hit regions, resources and transient behavior. Destroy the context after the host stops consuming its draw lists; destroy separately owned models according to their headers. The table describes ownership and submission. It does not claim that every entry has reached complete reference behavior. The gallery's Implementation scope lists the remaining features. ## Handle return-value events Many controls report a change or activation by returning `true`. Invoke your application function in that branch: ```c /* Inside an active frame; ui, theme, save_id and disabled are supplied. */ if (cui_button(ui, save_id, &theme, cui_string("Save"), disabled)) save_document(application); if (cui_checkbox(ui, notify_id, &theme, cui_string("Notifications"), &application->notifications, disabled)) persist_preferences(application); ``` The button reports activation for the frame's routed input. The checkbox writes the caller's value and reports a change. Rendering another frame does not call these application functions again unless another activation/change occurs. Keep application actions out of paint-only child callbacks, which may run during layout measurement. ## Use a controlled callback Some option structs expose `on_change`. For Switch and Toggle, a supplied callback receives the requested value; the component leaves the authoritative application value to your code. Without the callback, the control updates its value pointer directly. ```c #include "cui/cui_components.h" typedef struct { bool sync_enabled; cui_switch_state sync_motion; } preferences; static void request_sync(void *user, bool requested) { preferences *app = user; app->sync_enabled = requested; /* Persist or validate here, using the application's own services. */ } void draw_sync(cui_context *ui, const cui_theme *theme, preferences *app, double now_seconds) { cui_switch_ex(ui, cui_id_from(ui, "sync"), theme, cui_string("Automatic sync"), &app->sync_enabled, &app->sync_motion, (cui_switch_options){.on_change = request_sync, .change_user = app, .now_seconds = now_seconds}); } ``` Zero-initialize `preferences` before use and retain it between frames. The callback is synchronous; keep its user pointer valid during submission. A controlled callback may reject a request by keeping the old value. The next frame submits the accepted value. ## Connect host events The host queues `cui_event` values before a frame. CUI routes them using previous-frame regions, focus, capture and overlay scopes. Your app submits controls for the new frame, obtains its draw list and semantic tree, then paints and bridges semantics through the chosen adapters. Use [core lifecycle](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CORE.md) for event ordering and [host interfaces](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/INTERFACES.md) for renderer/platform callbacks. A platform callback such as clipboard access is different from a component callback such as `on_change`; the host supplies the former, and application behavior supplies the latter. ## Schedule redraws After application state changes outside a component, call `cui_invalidate`. Hosts redraw when `cui_needs_redraw` is true and honor component-specific animation deadlines. Pass real elapsed time and system reduced-motion preferences through the host. Avoid rerunning application side effects solely because an animation paints another frame. --- ## Whole-value Input acceptance Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/INPUT_ACCEPTANCE.md # Whole-value Input acceptance The contract follows pinned upstream kit commit `87d10ae5e1299d1be18670a37570c5402f952e34`, [replacement and preedit validation](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/crates/base/src/input/base/state.rs) (`is_valid_input`, `replace_text_in_range`, `replace_and_mark_text_in_range`). This implements a bounded predicate for the single-line composed Input, not full Input-family parity or source regex/mask/content-type behavior. Set `cui_input_options.validate` and `validate_user` (or the corresponding Base options). The callback receives the complete proposed UTF-8 value, never merely the inserted payload. Empty candidates are implicitly valid. Otherwise call the candidate predicate first; only if it returns false is the previous value tested. Reject only when that previous value is valid. This permits repairing invalid programmatic defaults without trapping the user. Programmatic legacy edit APIs remain unvalidated; history Undo/Redo bypass acceptance, as does a multiline model. Multi-selection attachment is currently a multiline extension, so it retains its existing behavior without this source single-line predicate; no validated multi-cursor extension is claimed. ```c static bool digits(void *unused, cui_str value) { (void)unused; for (size_t i = 0; i < value.length; ++i) if (value.data[i] < '0' || value.data[i] > '9') return false; return true; } /* state and edit are retained caller-owned objects. */ cui_input_result result = cui_input_ex(ui, id, theme, cui_string("Digits"), edit, &state, (cui_input_options){.validate = digits}); if (result.rejected) { /* An edit was declined, without changing the value. */ } ``` A declined edit sets `result.rejected` with `error == CUI_EDIT_OK`; it does not implicitly mark the control invalid. `invalid` remains an explicit semantic/paint flag and `required` remains semantic metadata. UTF-8, boundary, capacity and forbidden single-line line-break errors remain distinct and publish the existing same-frame error appearance. The source strips CR/LF from single-line insertion; CUI retains its explicit `CUI_EDIT_LINE_BREAK` engine policy in this batch. ## Engine and host dispatch `cui_edit_apply_checked` takes a by-value request and acceptance policy, returning `{error, rejected}`. EVENT delegates existing keyboard/text behavior, INSERT is atomic clipboard insertion, DELETE_SELECTION removes a selected cut range, and COMPOSITION applies the reusable IME session. Invalid request kinds/null models fail without callback invocation. Raw legacy APIs and null-policy checked requests keep their existing behavior; no permanent callback/userdata is retained in the model. Invalid UTF-8/boundaries/capacity fail before a predicate is invoked. The actual Input reducer routes typing, paste, selected/grapheme/word erasure and composition through this seam. Copy is unchanged. Cut copies first, then attempts validated deletion, matching source `cut`: a rejected cut can still copy its selection. Clipboard failure leaves the document unchanged and does not invoke the predicate. Readonly/disabled controls retain existing mutation guards. IME UPDATE validates a complete provisional view without changing committed text or history. The previous predicate value is the prior composed view when active, not merely the committed document. Rejected updates preserve that view. Engine COMMIT rejection also preserves session state; its standalone caller may retain or cancel it. The built-in Input reducer then explicitly cancels a rejected host COMMIT as a subsequent lifecycle transition: native/browser composition has ended, corresponding to source `unmark_text`. Committed text, selection and history remain unchanged, and following typing/shortcuts work. A successful commit is one Undo step. START/CANCEL and history replay do not invoke the predicate. Existing focus-loss, readonly/disabled and source-revision cancellation policies remain intact. ## Ownership, bounds and rollback There is no additional acceptance allocation or caller preview buffer. Ordinary edits/commit reuse the model's existing creation-time scratch, bounded by document capacity. Provisional views reuse existing fixed caller view storage or the opted-in model-owned `grow_view` cache, bounded by document capacity + preedit capacity - 1. The existing grow cache can allocate on necessary growth, not on every edit. Fixed-view capacity remains an explicit error; oversized preedit is not truncated. The engine validates known workspace/session/model aliases before writes. Payload slices of the stable document or preedit buffer are supported; payloads overlapping the working candidate workspace are invalid. Each predicate borrows an immutable value only for that synchronous call. On a failed candidate the shared view may be rebuilt from unchanged document/preedit storage for the old-value predicate, then restored or rebuilt for acceptance. Predicates are never replayed as part of commit. Rejection preserves logical model metadata, coalescing, selection, history/redo, annotations and session ownership, and the previous view's defined bytes through its NUL terminator. Internal scratch and unused capacity tails are unspecified; this is not an entire-allocation byte identity promise. No idle-frame document copy is added. Same-model mutation during a predicate is guarded: mutating APIs and scratch/cache operations return INVALID_ARGUMENT; void destroy/detach/coalescing setters do nothing and record the violation. The outer checked request rejects with INVALID_ARGUMENT, restores its logical prepared state and leaves the model alive. Destroy it normally after the checked call returns. Pure getters for text/state, content, selections and columns remain available. Nested same-model checked calls are rejected. Other models, UI/host callbacks and external side effects are not blocked or rolled back. Direct writes to caller buffers or borrowed strings, freeing caller storage, retaining candidate pointers and cross-thread model access violate the borrowing contract and cannot be protected by a C callback guard. ## Validation and integration `tests/unit/test_input_acceptance.c` exercises actual composed Input/Core dispatch for typing, paste/copy-first cut, grapheme/word/selected erasure, healing, history replay/redo retention, readonly/disabled/error separation and IME host lifecycle. It also checks same-model mutation/destruction guards, malformed/capacity/alias requests, fixed/growing provisional views larger than committed capacity, prior view restoration, rejected growth, a 200 KB whole-value candidate and multiline bypass. Register it linked only to `cui`, including WASI. Root owns CMake, distribution and registry changes; this source batch does not claim full native/browser accessibility or all Input reference features. --- ## InputGroup addon and text observers Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/INPUT_GROUP_EVENTS.md # InputGroup addon and text observers Include `cui/cui_form_events.h`. `cui_base_input_group_events` and `cui_input_group_events` mirror the legacy arguments plus a borrowed `cui_input_group_handler`, returning `cui_input_group_event_result`. `control` is the unchanged legacy result, including the last activated addon in descriptor order and aggregate Input changed/submitted/error/rejected fields. `addon_count`, `change_count`, `submit_count` count actual callbacks; counts saturate with `count_overflow`. Reading results never replays callbacks or mutations. ```c static void addon_activated(void *user, const cui_component_event_metadata *event) { bool *work_after_frame = user; *work_after_frame = true; /* Identify action using event->target. */ } static void text_changed_or_submitted(void *user, const cui_component_text_event *event) { bool *work_after_frame = user; *work_after_frame = true; /* Inspect event->event.kind: CHANGE or SUBMIT. Text is borrowed/redactable. */ } /* During submission with existing caller-owned model/state/addon descriptors: */ /* cui_input_group_event_result result = cui_input_group_events( ui, group_id, input_id, theme, edit, &state, addons, count, options, (cui_input_group_handler){.on_text = text_changed_or_submitted, .on_addon = addon_activated, .user = &pending}); */ ``` Base preserves addon source traversal. Each built-in Button addon first runs its old interaction and last-addon write, adds its existing semantic details, then notifies once per actual accepted activation in that addon's input order. Two activations of B and one of A may dispatch A then B then B when A precedes B in the descriptors. They are not sorted into global input order. Metadata kind is ACTIVATE, target is the actual addon ID, with genuine accepted snapshot evidence. If snapshot data is unavailable but accepted input identity is proven, only actual frame/index/type facts are supplied; no activation is fabricated. A legacy aggregate boolean alone does not invent a callback without accepted input evidence. All addon notifications precede the nested Input reducer. `on_text` reuses `cui_base_input_events` exactly once, preserving its per-event committed CHANGE and eligible Enter SUBMIT notifications, revisions, rejection/errors, composition and history behavior. Its metadata target is the nested **Input ID**, not the group. Multiple inputs/submits can each notify; preedit and unchanged revisions do not become CHANGE. A failure after earlier edits retains earlier notifications and the old aggregate error. No extra whole-group final-text comparison or replay occurs. Callbacks run before the group's final input-parent association and before Styled paint. Missing handlers still permit all old work. Readonly input does not disable otherwise enabled addon Buttons; disabled input, disabled/loading addons retain their existing separate policies. Passive/layout-only/inert submissions preserve old work but emit no new observation. Text/custom addons have no built-in action notification; controls in custom renderers keep their own APIs. Later custom renderer edits are not synthesized as nested Input events. Text payloads inherit Input's secure redaction: masked or password-purpose inputs have `has_text=false` and empty text; scalar snapshots remain available. Otherwise UTF-8 is borrowed only through the callback. Use `cui_component_event_copy_utf8` with explicit storage/byte limit and check `CUI_COMPONENT_EVENT_COPY_OK` to retain it. Copy metadata/scalar snapshots by value. Handler/user/descriptors and all active model/state/frame resources must remain live. Do not mutate/free/rebind active model/state/descriptors/input/context, recursively submit UI or destroy context in observers. Unrelated flags and copying are allowed; defer omission and teardown until outer return plus frame/renderer consumption. Notifications cannot reject already applied changes, consume by return or imply COMMIT/form submission. Styled InputGroup now shares standard Input's mask preparation and checked resource gate before its single nested reduction, then paints once in the existing Group layout. Masked committed text and preedit use bullets; source-byte selection and caller-provided hit testing retain their existing model-offset policy. The default plain hit fallback is replaced with masked mapping. The actual caller-owned Group behavior remains current inside text callbacks; temporary Styled configuration does not redirect state ownership. No public layouts or event timing change. Masked Styled InputGroup rejects an actual custom `presentation.prepare` or `presentation_complete` with `CUI_EDIT_INVALID_ARGUMENT`: the mask stage needs the single checked presentation gate. Rejection registers a disabled, secret, readonly, invalid input without reducing or exposing raw text. Earlier addon work remains applied. Failure after accepted text progress retains those changes/notifications and the last valid mask; the failing edit is atomic. Custom Base and unmasked presentation policies remain supported. Password purpose alone intentionally uses visible-password painting while semantics and text events remain redacted. `tests/unit/test_input_group_events.c` compares legacy/facade state, aggregate results, focus/redraw, semantics and paint for Base/Styled, including addon ordering, text/submit multiplicity, secure event redaction, IME/undo, validation rejection, progress before capacity error, readonly addons, disabled/loading, custom children, missing handlers, invalid admission, actual passive/inert scopes and deferred omission. Existing `form`, `form_base_only`, `input`, `text_input_events` remain regressions through `scripts/test_local.py`. No browser or full-family parity claim. Bridge and language wrappers retain existing queued generic text notifications; this does not expose synchronous typed addon/per-event handlers through bindings. Focused regressions inspect committed/preedit draw commands, secret semantics, custom model-offset hit testing, forbidden custom presentation, actual owner state inside callbacks, visible-password behavior, and progress before format-capacity failure. These are headless command/semantic tests, not GPU pixel acceptance. --- ## Bounded Input normalization Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/INPUT_NORMALIZATION.md # Bounded Input normalization Source pin: upstream kit `87d10ae5e1299d1be18670a37570c5402f952e34`, [state.rs normalize_input](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/crates/base/src/input/base/state.rs#L3520). Its single-line path removes CR and LF before replacement and validation. Number mask Unicode normalization is separate. This slice implements only explicit CR/LF removal; it does not implement format masks, regex or password presentation. Set `.normalization = CUI_EDIT_NORMALIZE_SINGLE_LINE_CRLF` on styled/Base Input options or a `cui_edit_request`. Zero preserves existing `CUI_EDIT_LINE_BREAK` errors. Multiline checked edits retain CR/LF and bypass this single-line policy. Raw edit APIs and model creation retain their existing behavior. Applications must explicitly opt into source-compatible normalization; no automatic seed conversion is claimed. For a bounded initial value, call: ```c char seed[128]; cui_str value; cui_edit_result error = cui_edit_normalize_text(cui_string("a\r\nb"), CUI_EDIT_NORMALIZE_SINGLE_LINE_CRLF, seed, sizeof seed, &value); /* On success value borrows seed and contains "ab". Create the model from seed. */ ``` The helper validates the complete original UTF-8 value and enum, checks all known source/destination/output-descriptor overlaps, then verifies capacity including NUL before writing. Failure leaves destination and output unchanged. No in-place or overlapping operation is supported. It owns no storage; source remains immutable and the returned value lives as long as destination. Unicode scalar bytes are unchanged: removal matches ASCII CR/LF only, not U+2028, U+2029 or other whitespace. Empty normalized output is valid. This helper is independent of a model; writing any caller-owned model buffer during a predicate remains forbidden by the existing borrowing contract. Checked edits use existing engine/session workspaces without additional staging allocation. Ordinary document capacity applies to the normalized resulting value, so a long CR/LF-rich original payload can fit a smaller document. IME original payload length must first fit caller-owned preedit capacity; removal does not bypass that input bound. Fixed/growing rendered-view capacity applies to the normalized full view. Existing lazy growth occurs only when that view needs it. For IME, anchor/cursor are validated against the original UTF-8 payload first, including scalar boundaries. Each endpoint maps to the count of surviving bytes before it. The resulting session stores normalized preedit and normalized byte ranges, not original-host provenance. Neither original Core event strings nor host offsets are rewritten. UPDATE does not mutate the committed document; COMMIT creates one Undo step. Empty updates preserve the existing CUI active-empty session contract until explicit CANCEL/COMMIT; this does not claim source empty marked-text lifecycle equivalence. Whole-value acceptance sees normalized candidates and the previous visible value. Rejected updates retain prior preedit/view bytes and ownership. Engine rejected COMMIT retains its prepared session; the built-in host reducer subsequently cancels because the host ended composition. UTF-8, range, capacity and alias errors precede mutation where possible. Same-model predicate mutation remains guarded, and no callback is replayed while committing. Undo/Redo restore recorded values without normalization or acceptance. Normalized typing coalesces using its existing intent; paste and IME retain atomic history behavior. The composed test `test_input_normalization.c` covers typed/pasted selection replacement, grouped Undo/Redo, normalized rejection, readonly/disabled and zero policy, Unicode/emoji endpoint mapping, fixed/growing IME views, empty update and cancel, helper aliases/rollback, model capacity and guarded destruction. It runs through CTest and the portable WASI runner. The website's validated Input example also exercises ordinary typing and native browser IME rejection/recovery on desktop and a 390px viewport. Browser clipboard paste, physical keyboard candidate windows, autofill and complete Input parity remain unverified. --- ## Input Number formatting Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/INPUT_NUMBER_FORMATTING.md # Input Number formatting `CUI_EDIT_FORMAT_NUMBER` is an opt-in single-line, single-selection checked-edit formatter. Zero initialization keeps existing editing behavior. Styled `cui_input_ex` and Base Input forward `.format` and caller-owned `.format_workspace`; no locale, floating-point parser, extra dependency or per-edit allocation is required. ```c char formatting[256]; cui_input_options options = { .format = {.kind = CUI_EDIT_FORMAT_NUMBER, .has_separator = true, .separator = ',', .fraction_limited = true, .fraction_digits = 2}, .format_workspace = {formatting, sizeof formatting}, .normalization = CUI_EDIT_NORMALIZE_SINGLE_LINE_CRLF, }; ``` The workspace must hold the final UTF-8 value and terminator and remain disjoint from the model, payload, composition buffers and declared presentation resources. It is borrowed only during the synchronous call. Invalid configurations and insufficient capacity fail before predicates or document/history/selection changes. Presentation prepares the final grouped value before acceptance callbacks, including masked display resources; failure preserves logical state and prior committed presentation. Scratch and unused capacity tails are unspecified. The implementation follows pinned upstream-component 0.7.1 commit `87d10ae5e1299d1be18670a37570c5402f952e34`, `crates/base/src/input/base/mask_pattern.rs`: validity lines 189–245, formatting 286–340, unmasking 375–393, numeric normalization 428–458; `input/state.rs` normalization orders numeric conversion before single-line line-break removal. A configured separator is removed before formatting. Integer scalars group from the right in threes, with the rightmost sign moved to the front. Fraction length truncates only when a separator is configured; zeros are never padded. Without a separator, formatting is identity even with a fraction limit. Empty text, `+`, `-`, `.`, `-.` and `.5` are valid intermediate values. Multiple dots, misplaced integer signs and other characters are invalid, except that configured separators are permitted in integer/fraction parts. This deliberately preserves source quirks, including special separators such as `.` or `+`, rather than parsing a numeric value. `cui_edit_format_valid`, `cui_edit_format_text`, `cui_edit_format_placeholder` and `cui_edit_unformat_text` accept the Number descriptor. Its placeholder is empty. Unformatting removes configured separators and, if a dot remains, trailing ASCII zeros: `1,234.00` becomes `1234.`. Pure formatting does not validate automatically, allowing the source's invalid-old-value healing policy. The checked engine normalizes the candidate, prepares the final presentation, calls the user predicate on the unformatted candidate, then checks Number validity. If that fails but the previous value was already invalid, the edit can heal it under the existing acceptance contract. Empty candidates bypass predicates. Replay restores recorded values without formatting or acceptance replay; presentation still prepares replayed values. Fullwidth digits, plus, minus, dot and comma convert to ASCII; U+2212 converts to `-`, and U+3002 to `.`. Other Unicode stays unchanged. `cui_edit_normalize_number_text` performs this conversion for explicit seed setup, optionally removing CR/LF; `cui_edit_number_offset` maps an original UTF-8 scalar-boundary byte endpoint to the normalized byte endpoint. Pure helper output descriptors and buffers are unchanged on errors, and input/output aliasing is rejected. A seed is not automatically normalized, formatted or validated when creating a model. IME UPDATE applies numeric normalization and optional CR/LF removal but keeps preedit unformatted and committed text unchanged. Selection endpoints are mapped from original host UTF-8 bytes. COMMIT formats once and creates one history edit; CANCEL restores the committed view. The original preedit payload must fit the configured preedit storage before shrinking normalization: this is a bounded ownership rule, not a promise that normalized size alone controls capacity. The final grouped value must fit both model capacity and formatting workspace. Existing source byte-based caret adjustment is retained and snapped to valid UTF-8 boundaries. CUI differences are explicit: embedded NUL remains unsupported by the editing engine, so an enabled NUL separator is rejected; checked single-line formatting also rejects CR/LF separators. Disabled separator requires `separator == 0`; unlimited fraction requires `fraction_digits == 0`. Single-line CR/LF removal remains opt-in rather than changing legacy controls. Multiline models, multiple selections and inline tokens reject enabled formatting atomically. Raw engine APIs are unchanged. This slice does not implement regex validation or all source content-type builders, and does not claim complete Number-mask or Input parity. Coverage is in `test_input_number_engine.c`, `test_input_number_control.c` and `test_input_number_native.c`: source intermediate/grouping/unmask cases, UTF-8 endpoint conversion, alias/config/capacity failures, callback order/reentry, invalid-old healing, actual styled paste/IME/semantic state/history, fixed bullet-storage failure and actual-font bullet pixels/factory rollback. Native font test accepts argv font or `CUI_TEST_FONT`, returning 77 when unavailable. Integrators must register these new tests; generated distributions require regeneration after the appended public descriptor fields. For a registered native build, the engine and control tests link only `cui`; the font test links `cui_text`, `cui_bidi` and `cui`, and uses the optional native text dependencies already pinned by the project. All three compile with `-std=c11 -UNDEBUG -Wall -Wextra -Wpedantic -Werror`. The font test must have CTest skip return code 77. A WASI engine probe uses the engine test plus `cui_edit.c`, `cui.c` and `cui_effects.c`; it requires no filesystem, environment or platform services. --- ## Pattern formatting for single-line Input Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/INPUT_PATTERN_FORMATTING.md # Pattern formatting for single-line Input This opt-in feature formats the stored value. It is independent of password bullet display, regular-expression matching, numeric grouping, and semantic content type. Legacy zero options are unchanged. No full Input parity claim follows. ```c char formatted_workspace[128]; cui_input_options options = { .format = {.kind = CUI_EDIT_FORMAT_PATTERN, .pattern = {"99-99", 5}}, .format_workspace = {formatted_workspace, sizeof formatted_workspace} }; /* Paste 1234 stores/paints 12-34; the final caret is byte 5. */ cui_input_result result = cui_input_ex(ui, id, &theme, label, edit, &state, options); ``` The appended fields also exist in `cui_base_input_options` and `cui_edit_request`. Use `cui_edit_apply_checked` for an independent reducer. Direct raw edit functions have no retained format policy. Pattern/configuration changes never eagerly rewrite existing text or history. Pure helpers support seed/readback setup: `cui_edit_format_valid`, `cui_edit_format_text`, `cui_edit_format_placeholder`, and `cui_edit_unformat_text`. Seed creation itself still does not automatically validate or format; call the pure helper explicitly if that is the desired policy. ## Source behavior Pinned reference: `87d10ae5e1299d1be18670a37570c5402f952e34`, `crates/base/src/input/base/mask_pattern.rs` and `state.rs:3534–3553,4109–4198`. The source's incomplete builder comment is not the token contract: | Token | Consumes | | --- | --- | | `9` | One ASCII digit, not a dot or fullwidth digit | | `A` | One ASCII letter | | `#` | One ASCII letter or digit | | `*` | One Unicode scalar, not one grapheme | | Other scalar | Literal separator | Validation scans tokens, skipping mismatches and consuming matching scalars; all input must be consumed, but not every token must be filled. Formatting inserts unmatched separators, consumes matching separators, and stops at the first unmatched input token or exhausted input. It does not append trailing separators. These source rules are intentionally preserved, including `A9` accepting `1` while formatting it to empty. There is no token escaping syntax. Unformat walks token positions and removes literal positions, rather than stripping all punctuation. Placeholder uses `_` for input tokens and preserves literals. For `9999年99月`, `202412` formats to `2024年12`; placeholder is `____年__月`. An empty pattern behaves as NONE. Styled Input uses the generated placeholder when no explicit nonempty `.placeholder` is supplied; an explicit placeholder wins. This frame-options rule is distinct from the reference's ordered builder setters. For each checked committed edit: normalize insertion if requested; build whole unformatted candidate; compute formatted final text in caller workspace; hard prepare final presentation resources; then run custom validator followed by token validity on the original candidate. Empty bypasses both. If invalid, run that same chain on the old visible value; reject only when old is valid. Thus invalid seeded text remains editable. Hard capacity/resource errors never use invalid-old healing. The user predicate is not replayed for formatting. Masked Input prepares only final bullet geometry; no plaintext geometry fallback is introduced. IME UPDATE validates/prepares an unformatted composed view and never mutates the committed document in CUI. COMMIT formats once and creates one Undo transaction. Rejected UPDATE preserves prior visible preedit; host COMMIT rejection cancels its ended session afterward. START/CANCEL/PRESENT do not format. Undo/Redo restore exact recorded bytes and selection, bypassing format/validation while retaining resource preparation. A formatting rewrite breaks typing coalescing and records a whole document change; unchanged formatting preserves ordinary typing grouping. Caret adjustment preserves the source byte-length formula, then snaps an interior UTF8 endpoint backward to a scalar boundary. This additional CUI safety rule keeps the portable byte-offset contract valid with Unicode literals. ## Ownership and failure rules Pattern bytes are immutable synchronous borrowed input. Engine workspace is caller owned and includes NUL. It must be disjoint from pattern, event payload, every model allocation, IME descriptor/buffers, and all declared presentation spans. No hidden per-edit allocation is added. Model scratch bounds the unformatted candidate too: an insertion that exceeds model capacity fails even if formatting could truncate it to fit. Formatting never silently truncates for destination capacity. Pure helpers require disjoint destination/result descriptors and input bytes; malformed input, alias and insufficient capacity leave output unchanged. Internal scratch/workspace tails are unspecified; rejection preserves document, history, selection, coalescing, session and the prior view's defined bytes plus terminator. Active stale/wrong-model checked composition requests reject before implicit session cancellation, preserving prior preedit on hard failures; Base still performs its normal explicit focus/selection lifecycle cancellation. Known same-model mutators invoked from predicates/presentation are guarded. Caller writes and external callback side effects remain outside rollback. For styled Input, keep workspace alive and unchanged through frame draw consumption: its generated placeholder can be frame-borrowed. Styled placeholder capacity is preflighted before reduction, and reused afterward. Base/engine usage only borrows workspace during the synchronous request. No workspace pointer is retained by the engine. Presentation resources follow their existing caller completion contract. Nonempty patterns reject multiline models, multiple selections and inline tokens with INVALID_ARGUMENT before writes or callbacks. Checked single-line patterns containing CR/LF also reject before reduction, preserving CUI's existing single-line document invariant; pure helpers may still format those literals. These are explicit bounded CUI restrictions. Unicode `*` can split a grapheme in source formatting; grapheme navigation otherwise keeps its established editing policy. ## Registration and proof Integrator registers `test_input_format_engine` and `test_input_format_control` against `cui`, and native optional `test_input_format_native` against shaped-text libraries. The native test accepts argv font or CUI_TEST_FONT and exits 77 without a usable font. It paints actual NotoSans bullet pixels and forces a geometry factory failure before value/history/selection mutation. After changing host factory availability, it sends `cui_text_metrics_changed`, honoring existing font-cache generation invalidation. Unit scenes cover real Core/styled Input paste, paint, semantics, IME, history, readonly and password-copy policy, plus pure source cases, Unicode, alias, capacity, predicate/guard and prior-preedit rollback tests. Independent public headers affected: `cui_edit.h`, `cui_base.h`, `cui_components.h`. No additional private source/header or dependency registration. Distribution regeneration remains integrator-owned. Numeric formatting, regex, broader content purposes and the remaining source Input lifecycle/platform features remain separate work. Worker validation: strict full native build passed; CTest 142/143 passed, with only the expected stale distribution headers failing. Three new tests passed strict manual compilation and ASan/UBSan with leak detection. The engine test also passed wasm32-wasi with Wasmtime49; independent public-header checks passed. These new tests are not yet in worker CTest because registration is integrator-owned. Logs: `/home/matteo/.cache/cui-validation/input-pattern-{build,ctest}-final.log`. --- ## Single-line Input pointer selection Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/INPUT_POINTER_SELECTION.md # Single-line Input pointer selection The stateful Base Input reducer and styled `cui_input_ex` now consume host click counts for ordinary single-line text. Count zero/one preserves caret placement and Shift extension. A double click selects the source-defined word/whitespace range; a triple click (or higher count) selects the whole single line. Shift does not override double/triple selection. Masked double/triple click retains whole-value selection, avoiding disclosure of plaintext word boundaries. This follows upstream-component 0.7.1 commit `87d10ae5e1299d1be18670a37570c5402f952e34`: `crates/base/src/text_boundary.rs:1–47`, `input/base/selection.rs:25–91`, and `input/base/state.rs:2297–2415,3190–3240`. The word classifier is deliberately distinct from Unicode word-navigation primitives: ASCII letters/digits/underscore, Latin U+00C0–024F and U+1E00–1EFF, Cyrillic U+0400–04FF and combining U+0300–036F connect; Unicode whitespace connects separately; punctuation, CJK and other scalars select individually. At most128 previous and128 following scalars connect. A400-character run clicked at byte200 therefore selects bytes72–329. End-of-value double click has no word and leaves selection unchanged. UTF-8 byte endpoints remain scalar boundaries; this is not an arbitrary grapheme/Unicode word-classification claim. A double-click drag keeps its original selected word covered while extending the moving endpoint. Crossing left reverses the anchor; returning inside the original range retains the word; extending right uses the original start. It does not snap the moving endpoint to the whole destination word. The source clears sticky word state on triple-click: subsequent drag moves the line selection's end and may shrink it. This implementation preserves that behavior rather than inventing persistent whole-line drag. Readonly controls permit selection; disabled controls suppress it. Consumed presses (including inline-token actions) do not reposition the caret or start word selection. Existing token-safe atomic selection expands token-interior endpoints. Consumed primary release still clears drag state. Keyboard/text events, cancel, blur, disable, model rebind and document revision invalidate the sticky range. No document mutation, validator/presentation call, hidden allocation or extra history edit occurs; normal selection breaks typing coalescing through the existing edit API. Keep one zero-initialized `cui_input_behavior_state` per stable ID/model session, or one styled `cui_input_state`. Appended internal fields retain only offsets, numeric revision and an active flag; they never borrow text or retain the model pointer. Keep the model alive during reduction; reset caller state when destroying/recreating a model at a reused address, as with existing model identity contracts. The stateless legacy Base wrapper cannot retain a word-drag range between calls; use the stateful ex/reducer API for this interaction. Existing multiline reducers are unchanged: new word/line branches explicitly require a single-line model. Host adapters must provide actual click counts; zero remains an ordinary click. `tests/unit/test_input_pointer_selection.c` exercises actual Core event targeting and Base composition: both drag directions/return, Shift, source triple-click shrink, end boundary, readonly/disabled/masked, consumed annotated-token press/release, Latin/combining/CJK/emoji/punctuation/whitespace, bounded long word, cancellation and model rebind. The initial ordinary double-click assertion fails against pre-change `c866950` and passes afterward (`input-pointer-before.log` records the failure). `tests/integration/test_input_pointer_native.c` drives actual styled Input using real shaped caret positions and native font geometry, checks byte selections and painted selection widths against native geometry, and verifies glyph alpha pixels. It accepts argv font or `CUI_TEST_FONT`, returning77 when unavailable; register with skip return code77 and link `cui`, `cui_text`, `cui_bidi`. Headless unit links `cui`; it also runs without host dependencies under WASI. No browser fixture, global registration or generated distribution is changed in this scoped slice. Remaining Input wheel/menu/clear/reveal/loading, regex and most content-purpose gaps are recorded separately. This change is not a complete Input parity claim. Validation for this scoped commit: strict C11 warning build passes; existing CTest144/145 passes, with only the inherited generated-distribution stale check failing. Scoped unit and actual NotoSans native-font tests pass under ASan/UBSan with leak detection; the unit scene passes Zig0.16.0 WASI under Wasmtime49.0.0 without filesystem or environment access. Independent public Base header compiles. Logs use `/home/matteo/.cache/cui-validation/input-pointer-*`; integrator must register the two new tests and regenerate distributions. No browser/runtime parity proof beyond these native/headless paths is claimed. --- ## Input reference contracts Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/INPUT_REFERENCE_CONTRACTS.md # Input reference contracts Audit pin: upstream kit commit `87d10ae5e1299d1be18670a37570c5402f952e34`. Primary source: [movement](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/crates/base/src/input/base/movement.rs), [state/validation](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/crates/base/src/input/base/state.rs), [styled Input](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/crates/component/src/input/input.rs), and [history contracts](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/crates/kit/tests/input/history.rs). This change addresses two widget behavior gaps and adds tests through the actual styled `cui_input_ex` control. It does not establish full Input-family parity. The source `crates/base/src/input/base/movement.rs` `move_vertical` returns immediately for a single-line Input; `state.rs` `select_up`/`select_down` do too. CUI's single-line Input now leaves selection unchanged for Up/Down, including Shift/Ctrl modifiers and read-only inputs. Its Base reducer consumes those keys unless `delegate_up_down` explicitly yields to a popup/list owner. Multiline edit models retain existing vertical movement. The generic edit engine's line movement APIs remain unchanged. Source `state.rs` `on_blur` breaks undo transaction coalescing while preserving selection. CUI's retained `cui_input_behavior_state` now records focus and numeric model identity, splitting coalescing on focus transitions, first binding and model rebinding. It never dereferences an old model. These operations do not change document revision, clear history or discard selection. Zero-initialize state and retain it with its Input; reset state when replacing a model if the allocator can reuse the exact old address, or when transferring state to a different UI/ID. The state observes transitions when the widget is submitted: applications that omit it or change focus away and back entirely between submissions must explicitly call `cui_edit_break_coalescing` at that application lifecycle boundary. This is not an OS focus subscription or engine-wide focus observer. The legacy stateless `cui_base_input` wrapper preserves its prior engine grouping; use retained `cui_base_input_ex` state for observed focus-transition grouping. The styled `cui_input` convenience wrapper already retains state through Core resources. Existing composed paths covered by the new tests include grouped consecutive typing Undo/Redo, Ctrl-Z/Ctrl-Y/Meta-Shift-Z, grapheme arrow/backspace over combining marks and regional-indicator flags, history separation after blur, model rebinding, multiline selection, delegated popup keys, readonly/disabled mutation guards, required/invalid semantics, same-frame error presentation and IME commit/Undo plus focus-loss cancellation. IME preedit remains outside committed document/history; commit is one Undo step. Existing size/geometry/IME APIs remain intact. ## Whole-value validation The previously missing source predicate is now implemented by the checked engine seam and composed Input options; see [Input acceptance](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/INPUT_ACCEPTANCE.md) for exact callback, healing, IME, borrowing and rollback contracts. Explicit `invalid` and `required` flags remain distinct from edit acceptance. Source preedit updates also run the predicate; CUI preserves provisional rendering without committed mutation while providing that validation. This does not implement regex/mask constraints or source content-type roles. Other source-specific gaps are deliberately preserved: source single-line normalization strips CR/LF while CUI's edit model rejects them with `CUI_EDIT_LINE_BREAK`; mask/regex validation, source content-type/password roles, context-menu capabilities and source lifecycle event callbacks are not supplied by these two fixes. This guide does not claim those behaviors or full parity. Integrator: register `tests/unit/test_input_reference_contracts.c` linked only to `cui`, including portable/WASI configurations. Strict warnings and CTest are required; root owns registration and generated distribution regeneration. --- ## Unwrapped Input visual geometry Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/INPUT_VISUAL_GEOMETRY.md # Unwrapped Input visual geometry An optional `cui_config.text_geometry` factory lets unwrapped styled Input use host-supplied visual caret, pointer-hit and selection geometry. Core and Base contain only portable CUI types; they do not depend on native fonts, HarfBuzz or platform APIs. Existing measurement-only configurations keep their established Input path. Textarea and automatically wrapped paragraph provenance are separate integration work. Native hosts using a `cui_font *` as `measure_user` can register: ```c cui_config config = { .measure_user = font, .measure = cui_font_measure, .measure_styled = cui_font_measure_styled, .font_metrics = cui_font_get_metrics, .text_geometry = cui_font_text_geometry, }; ``` Register explicit font fallbacks on `font` before use. The callback shares `measure_user`, so a host using a wrapper object for measurement must supply a matching geometry adapter that calls `cui_font_text_geometry(wrapper->font, ...)`. No OS font discovery occurs. Native BIDI-off builds retain the factory symbol and return `CUI_TEXT_LAYOUT_UNAVAILABLE` without changing output. ## Factory and query contract `cui_get_text_geometry` calls the optional factory with original UTF-8 bytes, size and style. It preserves the caller's output on failure and rejects malformed or nonfinite session metadata. A successful `cui_text_geometry` owns its session and exposes an operation table that stays valid until release. Text is borrowed only during factory creation: the factory must retain everything its later queries need. Each successful session requires one `cui_release_text_geometry`; the helper zeros the handle so a second release is harmless. Core defensively releases a partial session returned with a failure when it supplies a valid release operation. Queries use original byte offsets. Carets report at most two affinities at an exact supported boundary: upstream attaches to the preceding logical cluster, downstream to the following cluster. Native dual caret positions come from the actual bidi runs and shaped cluster advance pens. Hit tests choose the nearest visual cluster edge. Selection queries normalize reversed endpoints in the native implementation and return complete-cluster rectangles in visual order; a mixed-direction logical range can have disconnected coverage. NULL output with zero capacity queries the required count. INVALID and CAPACITY preserve both output buffers and counts; buffers/counts must be disjoint. Hit-test failure preserves its output. Native queries reject nonfinite points. `cui_font_text_geometry` wraps the existing owned native line layout. It retains the actual root/registered/fallback faces and shaped arrays, and does not retain or reread the caller's text buffer. Its queries remain usable after source mutation, owned fallback replacement, or closing the root font. A font handle is still required for future factory, measurement and raster calls; this does not authorize closing a host font before ordinary rendering finishes. Native factory input is one unwrapped line: hard paragraph separators and U+2028 are rejected. Empty text has two affinities at x=0. ## Input lifetime and behavior Input owns a private immutable source copy and the session in a context resource, keyed by widget ID. Caller `cui_input_state` receives no new handle or cleanup duty. Reduction and paint share one session for matching bytes/size in that frame. A same-frame text mutation releases it and builds a fresh session before further hit testing or painting. Beginning the next frame releases the previous session, so font registration changes are observed; omitted widgets and context destruction also release it exactly once. Model rebinding clears stored affinity, and text revision changes invalidate that affinity. Resource collection never dereferences a previous model pointer. The visual session supplies caret x, pointer hit, selection spans, horizontal reveal and the IME candidate-window x. Pointer-selected upstream/downstream positions persist through event-free repaint, including a boundary whose two affinities have different visual x positions. Logical keyboard movement keeps its existing edit model behavior; a new logical boundary defaults to downstream (or the sole available edge at a line end). Geometry does not implement visual arrow navigation. Selection and composition underlines use individual visual spans. Their vertical extent uses the existing Input line box, while the native text path keeps its common fallback baseline. Text and placeholders use one unwrapped line on the visual path. IME geometry resolves the actual painted caret child's final bounds after layout through `cui_set_text_input_geometry_rect`, so changes in size, alignment and viewport origin do not use the previous frame's position. Query the final candidate rectangle after `cui_end_frame`. The context resource requires one additional slot when geometry is configured. Its private source copy is bounded to 65,535 bytes; selection/composition workspace is bounded to 4,096 rectangles each. These nested allocations are released with the resource. Failure to allocate or exceeding these bounds uses the documented legacy geometry fallback. A context resource capacity error remains observable through `cui_last_error`. Host font/style registrations must remain consistent between measurement, geometry creation and ordinary rasterization of a completed draw list. After changing host font metrics outside a frame, call `cui_text_metrics_changed` to refresh Core's measurement cache before the next frame. ## Explicit limits and fallback policy Native geometry accepts complete shaped-cluster boundaries. A UTF-8/grapheme boundary inside a ligature or merged mark cluster can return INVALID. Input then uses its measurement-only geometry for that whole painted line, preserving the editor's original logical anchor/cursor bytes. It does not silently snap editing offsets to a nearby glyph or claim that this fallback is visually correct for interior ligature carets. Factory/query UNAVAILABLE, INVALID, MEMORY, MISSING_GLYPH and CAPACITY likewise use the legacy path. The public factory and query APIs expose those statuses for callers requiring strict geometry. `cui_base_input_hit_test` tries the optional visual host for reusable callers; `cui_base_input_measured_hit_test` explicitly requests the legacy scalar prefix path. `cui_base_input_visual_hit_test` consumes a borrowed session, maps viewport and scroll coordinates, and returns the original byte offset; an optional caller affinity output is unchanged on failed or nonfinite hits. Native cluster-edge hits are still checked by the editor's UTF-8/grapheme selection rules. This is not full international editing parity: no GDEF interior ligature carets, cross-run grapheme analysis, visual arrow navigation, multi-line geometry, automatic Unicode line breaking or Textarea integration is claimed. Automatically wrapped Core commands still lose original paragraph context; the audit preserves that evidence separately. ## Validation Portable headless tests exercise owned session cleanup, malformed/nonfinite and capacity results, unchanged caller outputs, model rebinding, size changes, private source copies, same-frame edits, omitted-widget cleanup and explicit interior fallback without changing logical selection. Native tests compare the factory with styled metrics and keep querying after owned fallback replacement and root close. Enabled and BIDI-off API checks are included. `tests/integration/test_native_text_geometry.c` defaults to a passing unwrapped Input suite with actual Hebrew, Hebrew marks, mixed Latin/Hebrew/numbers, dual-affinity idle repaint and supported Arabic joining/mark fixtures. It compares real selection paint/IME/hits to native geometry, verifies HarfBuzz source glyph/cluster/advance data and actual nonzero raster pixels, and reports optional font cases explicitly. `--audit` retains the known Textarea and wrapped-paragraph failures. No missing-glyph raster counts as success. --- ## Bounded inset shadows Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/INSET_SHADOW.md # Bounded inset shadows `cui_set_box_shadows` copies up to eight total DROP and INSET layers onto the open box. It replaces the complete list. Zero count clears both phases; the existing drop-only setter also replaces the complete list, so it clears previous insets. Invalid kinds, counts, dimensions, radii or nonfinite values fail before changing the owner. Existing drop APIs and enum values retain their behavior. ```c cui_box_shadow layers[] = { {.layer = {.offset_y = 2, .sigma = 3, .color = {0, 0, 0, 64}}, .kind = CUI_BOX_SHADOW_DROP}, {.layer = {.spread = 2, .sigma = 1, .color = {0, 0, 0, 96}}, .kind = CUI_BOX_SHADOW_INSET} }; /* Between begin_box and end_box. Failure leaves the previous list intact. */ bool ok = cui_set_box_shadows(ui, layers, 2, (cui_corner_radii){4, 4, 4, 4}); ``` DROP layers paint before the background. INSET layers paint after the background, before local mesh/underlay/prepaint content and children. Supplied order survives within each phase. Both use ancestor opacity and the current ancestor mask, before the box's own child-overflow clip. Shadows create no interactions or semantics. The existing outline and ordinary content/border paths keep their prior ordering. The source hole is the original caster offset by the layer, dilated by **negative** spread. Positive spread shrinks the hole. Original radii clamp against the original caster; hole radii are `max(original_clamped_radius - spread,0)`, with no second hole-size clamp. Materialized source f32 origin/size determine the far edge before physical floor/ceil covering. Even a logically collapsed hole can cover a physical pixel. Sigma-zero coverage uses the source SDF ramp and unrounded `max(qx,qy)` fast path. Gaussian coverage uses source erf/four-midpoint integration without a DROP support-rectangle cutoff. The result complements the raw hole convolution and multiplies independent element SDF coverage, then clamps/quantizes for straight RGBA8 storage. Scene insertion/culling uses the **covered hole**. Rasterization and final cropping use the **covered element**, intersected with the covered ancestor mask and target. An empty or mask-disjoint hole suppresses the whole primitive even if the element overlaps. An intersecting hole can produce inset pixels in element regions outside that hole. This intentionally follows pinned upstream-pre 0.3.8 Scene behavior; it is not an unconditional mathematical complement for an empty hole. `cui_effect_inset_shadow_query` returns logical raster placement, physical integer `covered_hole` and `covered_element`, and raster dimensions/bytes. The raster is the covered element, without Gaussian tail expansion. Query validates before publishing output. `cui_effect_inset_shadow_sample` evaluates a physical point and returns zero outside the element or for an intrinsically empty hole. These pure functions have no ancestor-mask input; mask-dependent insertion culling belongs to the prepared renderer. `cui_effect_inset_shadow_raster` validates the entire caller-owned buffer before writing. No pure operation allocates or retains caller pointers. `CUI_DRAW_INSET_SHADOW` is appended; its `shadow` field stores the paint by value. `cui_prepaint_inset_shadow` emits this value into the existing bounded writer and supports deferred output. Count the emitted command and its clip wrappers in the callback's budget. The payload registration copies values; contained host pointers remain borrowed under the existing prepaint contract. Manual callbacks choose their own surface/layer order. They cannot call layout, semantics or Core mutation during prepaint. The portable supported domain matches DROP: finite caster coordinates/dimensions up to16384 (dimensions nonnegative), absolute offset/spread up to4096, radii in[0,16384], sigma in[0,256]; uniform scale[1/65536,64], origin magnitude up to1048576. Positive physical sigma below `4*sqrt(FLT_MIN)` is explicitly rejected; sigma0 is separate. Raster sides are at most16384 and total raster area at most16M texels. Hole geometry is not charged as a raster allocation. DROP/INSET share the eight-layer limit,64 cache entries and combined64MiB owned CPU/upload budget. Unsupported nonuniform shadow transforms and resource failures reject before target resize/clear or swapchain acquisition. Frames without shadows keep their existing transform behavior. Existing late SDL GPU acquisition failures retain their legal-submit/previous-surface boundary. Software uses existing physical coordinates. SDL Renderer derives actual presentation/scale/viewport; SDL GPU and Sokol derive actual target/list projection. All native paths preflight resources, then paint the prepared cropped physical bitmap without applying another rounded element clip. Cache keys distinguish kind, paint values, transform and f32 phase; alpha-only changes reuse coverage. Normalized translation reuse requires both hole and element geometry to agree with actual checked covering. All prepared resources remain pinned until their frame submission; an earlier prepared frame expires when preparing another frame. Canvas's reusable module recognizes `type:'insetShadow'` alongside `'shadow'`, with the same sixteen copied paint values. Its rasterizer/query accept an optional fifth argument `kind` (0 DROP,1 INSET). Existing DROP calls remain unchanged. New C bridge exports are `cui_canvas_inset_shadow_query`, `cui_canvas_inset_shadow_prepare`, and `cui_canvas_inset_shadow_element_bound`. Existing layer-bound getter returns the covered hole for inset; existing raster getters return the covered-element raster. Prepare reads the actual `ctx.getTransform()` uniform scale/origin before backing-dimension assignment or clear. Draw requires ordinary Canvas clips suspended/restored because prepared crops own physical mask coverage. WASM pixels are copied into cache-owned images before subsequent bridge calls. Gallery serialization/export wiring belongs to the integrating host. Headless proofs cover literal square inset pixels, asymmetric independent radii, source square SDF diagonal, element AA, Gaussian complement versus independent double rectangle convolution, beyond-hole support, fractional collapse, zero/invalid/small-sigma atomics, copied Core/prepaint values, mixed phase/translucent/ancestor composition, legacy clearing, hole-mask culling, cross-kind and translation cache reuse, and bounded cache-slot failure preserving pixels. Native integration probes preserve actual DROP compatibility and compare INSET pixels through SDL Renderer pre-Present readback, SDL GPU Vulkan and Sokol GL at scales1/2. Canvas WASM covers DPR1/2, literal pixels, Gaussian/asymmetric composition and rejection before clear. The inset source fixture pins exact dependency/file hashes. This capability follows the pinned public inset contract within the declared portable domain. Native upstream Metal/WGPU shader/target-format/Hsla/transcendental/AA image identity remains unverified. Named convenience shadow factories and unrelated component owners remain separate contracts; no full BoxShadow or Chart family completion is claimed. Small uniform target scales retain the checked physical raster budgets. A normalized translation that exceeds the public caster domain falls back to the original validated paint and origin; it does not widen that domain. Shadow bitmap dimensions use the already checked physical raster rather than the ordinary logical bitmap size cap. The headless cache, actual SDL Renderer, and Canvas probes cover this fallback and rejected-frame preservation. SDL Renderer draws prepared shadows in physical target coordinates and restores logical presentation, scale, viewport, and clip before subsequent commands. Real OpenGL and software readback fixtures cover the tiny-scale edge oracle and normal-scale ordinary drawing after shadow emission; this does not change ordinary command geometry at extreme SDL scales. --- ## Interaction and touch routing Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/INTERACTION.md # Interaction and touch routing ## Custom clickable rows Register interaction before opening the box, using the same stable, nonzero ID for both. The box supplies geometry; `cui_interact` supplies semantics and routed input. Register each ID once per frame. For an action row without child controls: ```c bool mail_row(cui_context *ui, cui_id id, const cui_theme *theme, cui_str sender, cui_str preview, bool selected) { cui_interaction in = cui_interact(ui, id, CUI_ROLE_BUTTON, sender, false, false, 0); cui_color fill = in.pressed ? theme->accent : in.hovered ? theme->surface : selected ? theme->accent : theme->background; cui_begin_box(ui, id, (cui_box){.width = -1, .padding = 8, .background = fill, .border_width = in.focus_visible ? 1 : 0, .border = theme->focus}); cui_text(ui, sender, theme->font_size, theme->text); cui_text(ui, preview, theme->font_size, theme->muted); cui_end_box(ui); return in.activated; } /* During a frame: if (mail_row(...)) open_message(...); */ ``` `hovered` paints hover, `pressed` paints the held pointer/keyboard state, `focus_visible` requests the keyboard focus indicator, and `activated` triggers the action once. Selection remains application state. Input uses completed-frame hit geometry, so submit the same IDs every frame and establish a frame before injecting pointer input. A button role provides ordinary Tab/Enter/Space action behavior. `CUI_ROLE_LISTITEM` describes passive list membership; it does not automatically add button keyboard behavior or list selection/navigation. Prefer an existing choice/list component when you need that interaction model. Keep nested interactive children out of this simple row recipe. Core accepts mouse, touch, and pen pointer events. Existing zero-initialized `cui_event` callers remain mouse callers. Touch adapters supply a stable `pointer_id` until up/cancel, paired with portable `pointer_device` (zero when the host has no device namespace). SDL preserves both `touchID` and `fingerID`; identical finger IDs on two devices remain separate contacts. Core retains at most 16 contacts; excess contacts are ignored. The public queue accepts 256 events per frame; separate bounded 512-event dispatch storage reserves room for every possible touch-capture cancellation without dropping queued events. SDL finger coordinates are normalized by SDL and converted to logical window pixels. The browser uses PointerEvents and pointer capture, with `touch-action: none` on the canvas. Both adapters suppress compatibility mouse clicks generated by touch. One contact presses and taps through the ordinary focus/activation path. Movement beyond eight logical pixels prevents tap activation; ordinary control drag events remain available when no scroll/viewport owner claims the gesture. Sliders, scrollbars, and focusable Separator resize handles retain pointer drag ownership over their scroll ancestors. A custom draggable ID can use `cui_set_touch_drag_priority(ui, id, true)` after registration; this preserves its other semantics and takes priority over ancestor scroll/viewport pan. Cursor selection does not affect drag policy. Pan takeover sends a targeted Cancel event to the formerly pressed control before later queued contacts, clearing retained selection/drag flags. A second contact cancels primary activation. Lifting one finger does not turn the remaining finger into a new tap. Cancel/focus loss clears capture. Scroll owners accept touch scrolling by default, or can opt out using `touch_scroll_disabled` in semantic details. Once the eight-pixel threshold is crossed, touch moves become precise `CUI_EVENT_SCROLL` events. Their deltas are logical pixels with the same sign convention as wheel input. The initially hit owner is retained by ID; routing can chain only to its actual ancestors when its configured range reaches an edge. Hit routing respects clipping, modal scopes, disabled owners, and higher interactive portal layers. Scroll end/cancel events carry zero deltas. Reducers must use one pixel per precise delta instead of their ordinary wheel line size. There is no inertial fling. Internal contact subtraction, centers and pinch distances use double intermediates; generated deltas/scales saturate to the finite float range. Non-finite input contact positions are ignored while cancel can still terminate their lifecycle. Viewport panning and pinch zoom are explicit opt-ins, independent of scrolling: ```c cui_id plot = cui_id_from(ui, "plot"); cui_rect previous_bounds = cui_bounds(ui, plot); size_t count; const cui_event *events = cui_frame_events(ui, &count); for (size_t i = 0; i < count; i++) { if (events[i].type != CUI_EVENT_GESTURE || cui_event_target(ui, i) != plot || cui_event_consumed(ui, i)) continue; cui_plot_pan(&scale, events[i].dx); cui_plot_zoom(&scale, events[i].gesture_scale, events[i].x - previous_bounds.x); cui_consume_event(ui, i); } cui_plot_view(ui, plot, &theme, &view); cui_set_gestures(ui, plot, true, true); cui_set_cursor(ui, plot, CUI_CURSOR_GRAB); ``` `gesture_scale` is relative to the previous contact positions (one for pan or end/cancel); `x/y` are the current center in window coordinates. `dx/dy` are center movement when pan is enabled. `scroll_phase` carries started, moved, ended, or cancelled. Pinch requires exactly two contacts owned by the same viewport. Zoom is disabled unless `gesture_zoom` is explicitly enabled. The gallery Plot opts in and applies both transformations to its scale. Every registered interactive ID can use the shared hooks after its component has built, including IDs inside compound controls: ```c cui_id button = cui_id_from(ui, "run"); cui_theme styled = theme; cui_interaction before = button_state; /* Caller-retained state from last frame. */ if (before.pressed) styled.primary = theme.danger; else if (before.hovered) styled.primary = theme.info; if (cui_button(ui, button, &styled, cui_string("Run"), false)) run_action(); cui_set_cursor(ui, button, CUI_CURSOR_CROSSHAIR); button_state = cui_interaction_state(ui, button); cui_id toggle = cui_id_from(ui, "pin"); cui_toggle_ex(ui, toggle, &theme, cui_string("Pin"), &pinned, NULL, cui_toggle_options_default()); cui_set_cursor(ui, toggle, CUI_CURSOR_HELP); cui_interaction state = cui_interaction_state(ui, toggle); ``` `cui_set_cursor`, `cui_set_gestures`, and `cui_set_touch_drag_priority` change only their named fields and preserve the component's scroll range, role, focus behavior, relationships, and accessibility details. Apply them each frame after the component. `cui_interaction_state` does not register semantics or consume activation. It reports hover, pressed, focus, focus-visible, and activation for an ID already registered in the current frame (previous frame when outside a frame). Hover follows clipped/modal hit visibility and can apply to passive registered viewport IDs. Pointer activation is a tap/click released over its captured control, or the existing keyboard activation. A queried activation remains visible after `cui_interact` consumes it; explicit `cui_cancel_event_activation` removes it. Build a component before querying it during a frame. For styling before its build, query the preceding completed frame and retain the result in caller state. `cui_interact` remains the registration/activation-consuming API. Built-in cursors include default, pointer, text, horizontal/vertical resize, move, not-allowed, crosshair, grab, grabbing, zoom-in, zoom-out, wait, and help. Browser mappings use matching CSS cursor names. SDL has no corresponding system cursors for grab/grabbing, zoom, or help: its fallback is move for hands, crosshair for zoom, and default for help. Its cursor cache is bounded by the built-in enum count and is destroyed with the adapter. Caller-owned custom RGBA cursor images/hotspots are not implemented by this API. ## Coverage inventory | Path | Shared behavior and evidence | Remaining coverage limits | | --- | --- | --- | | Registered interactive controls (Button, Toggle, Checkbox, Radio, Switch, choice rows, toolbar items, numeric controls, and compound child IDs) | Core identity/tap/press/cancel, state query, and cursor hooks; Core tests verify tap, repeated non-consuming state query, cursor override, multi-contact ghost suppression, drag versus tap and cancel | Each of the 78 families is not separately touch/device tested; dragging controls keep their ordinary pointer reducers | | Scrollable, Sidebar, VirtualList | Shared precise-scroll reducer used by these scroll owners; styled/base Scrollable tests verify threshold, exact pixel offsets, release, and no row activation, including a full 256-event input queue with targeted cancellation; nested actual Slider/Resizable and custom drag-policy tests verify the ancestor does not steal their drag | Device tests directly exercise Scrollable; Sidebar/VirtualList reuse the reducer but are not independently touchscreen tested | | Textarea and Editor | Textarea precise pixel scrolling (Editor uses its text view); Textarea tests verify fractional precise delta and cancellation of retained selection dragging on pan takeover | Editor touch selection/completion/folding interactions are not separately device tested | | Table | Existing Table reducers already consume scroll deltas as pixels; Core routes contact pans to registered body/header owners | Table-specific touchscreen scrolling has not been added | | MessageScroller | Precise delta respects pixels; Message tests verify fractional offset | Touch prepend anchoring and jump actions are not separately device tested | | Tree, tabs, choice/list/menu panels, Surface bodies | Precision-aware existing reducers; Tree/Tab/Surface tests verify fractional pixel deltas; row-window choice/menu converts pixels to retained row units | Variable-height menu touch sequences and every popup combination are not separately device tested | | Nested ownership, clipping, portal/modal routing | Core tests combine touch threshold with nested range chaining, portal occlusion, disabled viewport and cancel; existing hit-routing tests remain in suite | No cross-device full interaction matrix is claimed | | Opt-in viewport | Core tests verify relative scale/center, zoom disabled by default, cancellation, disabled owner; Plot gallery applies pan/pinch | Applications must implement domain transformations and consume gesture events; other views do not automatically zoom | | Native SDL adapter | Native SDL event injection tests verify normalized finger coordinates/identity and exclusion of touch-generated mouse events, including two device namespaces sharing a finger ID; cursor enumeration/cache checks | System cursor fallbacks listed above; no custom RGBA cursor. The legacy poller consumes the process-wide SDL event queue and scales fingers using its own window; multiwindow routing is not validated | | Browser adapter | `tests/web/test_touch.py` drives real Chromium CDP touch tap, drag suppression, cancel, threshold pixel pan, and two-contact Plot pinch | No physical-device, Safari, or Firefox claim; existing mouse/keyboard/wheel browser suite is separate | This inventory describes shared infrastructure and the tested cases. It does not establish complete source parity or verification of all manifest families. --- ## Frozen initial integration contract Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/INTERFACES.md # Frozen initial integration contract Core types in include/cui/cui.h; core implementation src/core/cui.c. Public C11, no Clay/platform types. All dimensions logical pixels. Width/height 0 fits contents, negative grows, positive fixed. Explicit begin/end element composition backed by Clay. Frame strings copied to context frame arena; draw-list/semantic pointers valid until next begin. Context fixed capacities reported by errors, no per-frame allocation. Single UI thread across contexts: Clay's current context is switched by adapter, not safe concurrent calls. Input events queue before begin, dispatched against previous frame regions in order; first frame has no targets. Controls consume per-ID activation exactly once. Focus is retained only for submitted enabled controls; cancellation clears capture. Stable scoped 64-bit IDs with debug duplicate detection; Clay uses a folded internal ID. Renderer vtable consumes draw list synchronously; returns bool and reports actual backend/capabilities. Platform produces generic events and owns OS resources. Text measurement callback is independent, default approximate metrics explicitly documented. Base owns interactions; style wrappers call base and theme tokens. Worker changes to public contract require integrator coordination. Ownership: core worker core header/source/tests; base/style worker base/theme/components and tests; graphics worker backends/text/gallery. Integrator build/scripts/docs/manifest. Workers use isolated git worktrees and commit scoped changes; no direct mainline edits. --- ## Python, Go, Rust, Node JavaScript and TypeScript with CUI Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/LANGUAGE_BINDINGS.md # Python, Go, Rust, Node JavaScript and TypeScript with CUI For installable local wheel, npm, Go module and Rust crate artifacts, see the [packaging guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PACKAGING.md). Linux alpha packages are tested outside the checkout; registry publication and other platform packages remain pending. For UI trees authored directly in Python, JavaScript or TypeScript, use [the component builders](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BINDING_BUILDERS.md). They expose the real C bridge components in Python, JavaScript and TypeScript, with dedicated [Go](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/GO_BUILDERS.md) and [Rust](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/RUST_BUILDERS.md) APIs as well. See the [coverage table](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_COMPONENTS.md) for the current component scope and limits. The examples below also demonstrate hosting an existing C-authored application. The examples below remain useful for embedding an application whose UI is written in C. These runnable examples call the actual CUI library through a small C host. Each creates a styled **Increment** button, renders a counter, and calls your language synchronously when the button changes it. With SDL3 and shaped text available, the same clients open a native desktop window. Without a font argument they run a deterministic headless interaction check instead. This is an integration starting point, not a complete binding of CUI's 78 manifest entries. UI construction currently lives in `host.c`; application callbacks live in Python, Go, Rust or Node. Extend that host ABI to expose the controls and state your application needs. No Clay or SDL types cross this example ABI. ## Build and run ### Python only: standard-library ctypes Use Python 3.9+, CMake 3.20+, Ninja and a C11 compiler. Python needs no pip packages, Node, Go or Rust. Native windows additionally need installed SDL3 3.2+, FreeType, HarfBuzz and a TrueType/OpenType font. Build just the shared host: ```sh cmake -S examples/foreign_languages -B examples/foreign_languages/build -G Ninja cmake --build examples/foreign_languages/build --target cui_example_host # Headless: two actual CUI button activations and Python callbacks. python3 examples/foreign_languages/python/main.py # Native: click Increment in the actual SDL3 window; close the window to return. python3 examples/foreign_languages/python/main.py /usr/share/fonts/noto/NotoSans-Regular.ttf ``` For another build directory, pass `--library /absolute/path/libcui_example_host.so`. Python imports the [small ctypes wrapper](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/foreign_languages/python/main.py): ```python from main import run def changed(count): print("Application callback:", count) run(changed, font="/path/to/your/font.ttf") ``` Place this Python code beside the wrapper or import it from your application's module path. The callback stays alive throughout the synchronous C call. Python exceptions are captured in the callback and re-raised after the host returns; they never unwind through C. The native loop blocks the calling Python thread until close, just like the small Node host below. A production application should expose a per-frame host API appropriate to its runtime. ### Node JavaScript and TypeScript only Use the CMake/compiler and native dependencies above, plus Node 22.18+ and Node development headers (`node_api.h`). Go and Rust are unnecessary for these clients. No npm packages or node-gyp are required: ```sh cmake -S examples/foreign_languages -B examples/foreign_languages/build -G Ninja cmake --build examples/foreign_languages/build --target cui_node node examples/foreign_languages/node/main.cjs node examples/foreign_languages/typescript/main.ts # Open the same native CUI window from either runtime: node examples/foreign_languages/node/main.cjs /usr/share/fonts/noto/NotoSans-Regular.ttf node examples/foreign_languages/typescript/main.ts /usr/share/fonts/noto/NotoSans-Regular.ttf ``` The TypeScript sample uses Node's built-in type stripping; it does not perform static type checking. Both clients use the same N-API addon and C host. ### All five clients From the repository root, install/use CMake 3.20+, Ninja, a C11 compiler, Go 1.22+, Rust 1.85+ and Node 22.18+ (with Node development headers containing `node_api.h`). TypeScript runs through Node's built-in type stripping; no npm, Cargo or Go packages are downloaded. The examples add no third-party dependencies. The repository pins Clay and optional fetched SDL3. This build uses installed SDL3 3.2+, FreeType and HarfBuzz for native windows; if they are unavailable it prints `headless only`. ```sh examples/foreign_languages/build.sh examples/foreign_languages/check.sh ``` The build compiles the C bridge and Node addon with `-Wall -Wextra -Wpedantic -Werror`, Go's C trampoline with warnings as errors, and Rust with `-D warnings`. It places all artifacts in `examples/foreign_languages/build/`, including the shared C host used by all five clients. The CMake subproject builds CUI directly from this checkout with position independent code. Run on Linux with GCC/Clang; `build.sh` uses ELF rpath linker flags and needs adaptation for other platforms. To force a portable headless build, pass `-DCUI_EXAMPLE_NATIVE=OFF` to `build.sh`. Passing a font to that build returns status 4. To enable repository pinned SDL fetching when system SDL3 is absent, pass `-DCUI_FETCH_SDL=ON`; FreeType and HarfBuzz still need to be installed. Choose an existing TrueType/OpenType font on your machine, then open a native window with any client. The example below uses the font present on our Linux validation machine: ```sh FONT=/usr/share/fonts/noto/NotoSans-Regular.ttf python3 examples/foreign_languages/python/main.py "$FONT" examples/foreign_languages/build/go-demo "$FONT" examples/foreign_languages/build/rust-demo "$FONT" node examples/foreign_languages/node/main.cjs "$FONT" node examples/foreign_languages/typescript/main.ts "$FONT" ``` Close each window before starting the next command. Add a positive frame count (e.g. `"$FONT" 120`) to close automatically; zero runs until window close. Click **Increment** to update the on-screen count and print the callback value. Native SDL3 event dispatch, CUI layout, font shaping and rendering run on the calling thread. Go locks its goroutine to that OS thread. Node runs this loop synchronously: timers and other JS event-loop work wait until the window closes. For a production app, design a per-frame host API integrated with your runtime's main-thread event loop. ## C host contract [host.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/foreign_languages/host.h) deliberately exposes a small ABI: ```c typedef void (*cui_example_changed)(void *user, int count); int cui_example_run(const char *font, unsigned frames, cui_example_changed callback, void *user); ``` The callback is invoked on the calling thread and is never retained beyond the call. Its `user` storage must remain alive through `run`. Headless mode lays out the real button, obtains its hit bounds, queues pointer down/up events twice, and verifies two state changes and nonempty draw lists with no CUI errors. The native mode polls SDL3, renders CUI draw commands and optionally captures its last bounded frame when `CUI_EXAMPLE_CAPTURE` names a BMP output path. Text backing storage remains alive while the renderer consumes the draw list. Status zero means success; 2 is font failure, 3 backend creation failure, 4 native support unavailable, 5 CUI creation failure, 6–8 headless validation failure and 9 native layout/render failure. Native window initialization does not silently fall back to a headless test. ## Language examples [Go](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/foreign_languages/go/main.go) uses cgo and an exported Go callback: ```go //export changed func changed(count C.int) { observed = int(count) fmt.Println("Go count:", observed) } ``` A C trampoline passes that callback to the host. No Go pointer is stored in C. `runtime.LockOSThread()` keeps SDL operations on one OS thread. The build script links the host shared library through `CGO_LDFLAGS`. [Rust](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/foreign_languages/rust/main.rs) uses the C ABI directly: ```rust extern "C" fn changed(user: *mut c_void, count: i32) { unsafe { *(user as *mut i32) = count; } println!("Rust count: {count}"); } ``` The `i32` lives on the caller's stack throughout the synchronous host call. The narrow unsafe boundary covers the FFI call and pointer conversion. A production callback must avoid panicking across the C boundary. [JavaScript](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/foreign_languages/node/main.cjs) uses a locally built [N-API addon](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/foreign_languages/node/addon.c), with no node-gyp: ```js const { run } = require('../build/cui.node'); let observed = 0; const callback = count => { observed = count; console.log(`Node count: ${count}`); }; const status = run(callback); // Omit font for the headless test. ``` The addon invokes JS only synchronously on Node's calling thread, propagates callback exceptions and never retains a JavaScript callback after return. [TypeScript](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/foreign_languages/typescript/main.ts) declares the addon shape, then uses the same N-API implementation: ```ts interface Host { run(callback: (count: number) => void, font?: string, frames?: number): number; } const host = require('../build/cui.node') as Host; const status = host.run(count => console.log(`TypeScript count: ${count}`)); ``` Node strips erasable TypeScript syntax; this run does not perform static type checking. Use your project's pinned TypeScript compiler for type checking if integrating the sample into an application. ## Validation and limits Validated on Linux with Go 1.27.2, Rust 1.99.0, Node 25.8.0, SDL3 3.4.18, FreeType and HarfBuzz. The C host check verifies callback order, repeated independent runs and optional callbacks, in both native-enabled and core-only builds. Headless clients verify counts 1 then 2. Python additionally checks exact callback order, exception identity and a subsequent independent run. JavaScript also checks rejected arguments, a thrown callback and a subsequent successful run. Native Linux/X11 checks use Xvfb, xdotool and xwininfo to click the actual window button, verify that the foreign-language callback prints `count: 1`, and save a BMP of the final frame. They exercise a native window and SDL event dispatch, rather than merely generating headless commands: ```sh FONT=/usr/share/fonts/noto/NotoSans-Regular.ttf EXAMPLES=examples/foreign_languages # Use TMPDIR pointing to a writable directory if your /tmp quota is constrained. timeout 15 xvfb-run -a "$EXAMPLES/native-check.sh" "$FONT" python python3 "$EXAMPLES/python/main.py" timeout 15 xvfb-run -a "$EXAMPLES/native-check.sh" "$FONT" go "$EXAMPLES/build/go-demo" timeout 15 xvfb-run -a "$EXAMPLES/native-check.sh" "$FONT" rust "$EXAMPLES/build/rust-demo" timeout 15 xvfb-run -a "$EXAMPLES/native-check.sh" "$FONT" node node "$EXAMPLES/node/main.cjs" timeout 15 xvfb-run -a "$EXAMPLES/native-check.sh" "$FONT" typescript node "$EXAMPLES/typescript/main.ts" ``` Each check writes `build/-native.log` and `build/-native.bmp`. The fixed click coordinates belong to this sample's 480×240 layout. Xvfb tests use a virtual Linux display; physical-display behavior, Wayland, macOS, Windows and performance across language boundaries have not been validated here. The examples do not implement a browser renderer or promise complete bindings, IME support or native operating-system widgets. The button is a CUI control rendered into an SDL desktop window. --- ## Layout and custom content Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/LAYOUT_GUIDE.md # Layout and custom content Use `include/cui/cui.h` as the exact field/signature authority. This guide is the canonical introduction; [Core](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CORE.md) records advanced contracts. Dimensions are logical pixels. A box is a column unless `.row = true`. | Intent | `cui_box` fields | Effect | | --- | --- | --- | | FIT | `.width = 0` | Natural content width; the default | | Grow | `.width = -1` | Share available parent space | | Fixed | `.width = 120` | Request 120 pixels | | Exactly zero | `.width = 0, .fixed_width = true` | Collapsed width | | Maximum | `.max_width = 320` | Cap FIT, grow or fixed width | | Clip | `.clip = true` | Clip child paint and hit regions to the box | The same rules apply to height and its corresponding fields. Positive finite maximums constrain even fixed minimums; other maximums are unbounded. A maximum is a cap, not a request to grow. Give an ancestor a constrained width before expecting descendants to wrap. Padding and gaps consume available space. `align_x` and `align_y` use physical axes; centering needs unused space. ```c cui_begin_box(ui, cui_id_from(ui, "message"), (cui_box){.width = -1, .max_width = 480, .padding = 12, .gap = 8, .clip = true}); cui_text(ui, cui_string("A paragraph that may wrap within this card."), 16, (cui_color){30, 30, 30, 255}); cui_end_box(ui); ``` `cui_text`/`cui_text_ex` use normal layout wrapping. `cui_text_line` preserves an unwrapped line; put it inside a clipping ancestor if overflow must be hidden. `cui_text_paragraph_colored` explicitly selects word wrapping with its `wrap` argument and supports hard paragraphs. Clipping alone does not insert an ellipsis or reflow text. Font registration must precede measurement/layout. Compose arbitrary content with boxes and public leaf/component calls. A convenience component that takes a label does not automatically accept arbitrary children. For a custom card or mail row, compose the surface yourself rather than inventing a component content callback. Balance every `cui_begin_box` with `cui_end_box`, including skipped/capacity-failed boxes; APIs returning a boolean begin result have their own documented successful-begin balancing rule. For a mail row, use a growing row with a fixed avatar, a growing text column and a fixed trailing timestamp. Constrain the text column, clip long single-line subjects, and wrap the preview only when its row height may grow. Do not size a whole row from last frame's measured width: resize should resolve in this frame. See [IDs and lifetimes](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/IDS_AND_LIFETIMES.md) before repeating the row. ## Container-responsive layouts Use [responsive containers](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/RESPONSIVE_LAYOUT.md) for Tailwind-style named breakpoints in C. Query the current available **logical** width every frame; window framebuffer density is a separate host concern. A main pane can use its own query after subtracting sidebar/padding/gaps. ```c #include "cui/cui_responsive.h" cui_responsive size = cui_responsive_query(main_width, NULL); if (size.valid) { bool row = cui_responsive_fits(size, 260, 260, 12); float padding = cui_responsive_value(size, CUI_BREAKPOINT_MD, 12, 24); cui_begin_box(ui, 200, (cui_box){.width = -1, .row = row, .padding = padding, .gap = 12}); /* Submit the same application-backed cards in either arrangement. */ cui_end_box(ui); } ``` The selector arguments are query, threshold, base value, expanded value. Use `cui_responsive_at_least(size, CUI_BREAKPOINT_LG)` to choose a persistent sidebar; conditionally submit a closed drawer's controls so hidden input/semantics do not remain active. Keep one state tree across breakpoint changes. Width policies supply no CSS parser, automatic drawer/modal scope, or host event loop. The [dashboard fixture](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/responsive_dashboard/app.c) demonstrates the working composition; its guide includes native and headless run commands. Text can use [body/heading/code role tokens](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TYPOGRAPHY_TOKENS.md) inside these containers. Wrapping still requires a constrained parent and matching measurement and renderer fonts; tokens do not replace those contracts. ## Single-line ellipsis with fixed trailing controls Use `cui_text_ellipsis` from `include/cui/cui_text_overflow.h` when a single-line subject must shorten visibly. It resolves width in the current frame, preserves extended grapheme boundaries, and keeps the full text as its semantic name. Unlike clipping, it paints a trailing ellipsis when enough space remains. ```c cui_begin_box(ui, cui_id_from(ui, "mail-row"), (cui_box){.width = -1, .row = true, .gap = 8}); cui_text_ellipsis(ui, cui_id_from(ui, "subject"), subject, (cui_text_ellipsis_options){.width = -1, .font_size = 16, .color = theme->text}); cui_begin_box(ui, cui_id_from(ui, "star-slot"), (cui_box){.width = 32, .height = 32, .fixed_width = true}); /* Submit a star button/icon with another unique ID here. */ cui_end_box(ui); cui_end_box(ui); ``` Constrain an ancestor's width. A positive helper width is fixed; negative grows; zero is invalid. Height uses natural font metrics. Newlines are rejected, and prefix/ellipsis are shaped separately. The helper does not provide paragraph reflow, font fallback, or contextual shaping across the ellipsis boundary. Check its boolean result and the context diagnostic after submission. Give each repeated row a persistent ID scope as described in [IDs and lifetimes](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/IDS_AND_LIFETIMES.md). ![Native constrained subject rows with fixed star actions and a deliberate missing-icon outline](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/screenshots/developer-usability.png) A real SDL3 software capture of an external application using these APIs. The [evaluation record](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/validation/developer-usability-agent.md) contains its source and observed limits; it is a correctness smoke test, not a blind usability study. --- ## Letter spacing Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/LETTER_SPACING.md # Letter spacing Set `cui_text_style.letter_spacing` to a signed distance in logical pixels. A value of `2` adds two logical pixels between eligible visual shaping clusters; `-1` compresses them by one. Density scales the distance with the rest of the UI. Zero preserves the existing natural shaping and layout path. This changes the C ABI: rebuild Core, providers, renderers and applications against the same headers. Zero-initialize style/config values before setting individual fields, or use designated initializers. `cui_text_style`, embedded draw commands and `cui_config` have grown. Do not mix prebuilt libraries or generated bindings from an older build. The flat bridge style API does not yet expose tracking. ## Configure the provider Tracking is opt-in. The provider must measure, shape contextual lines and draw with the same cluster policy. Native `cui_text` with Bidi enabled supports it: ```c cui_config config = { .measure_user = font, .measure_styled = cui_font_measure_styled, .text_geometry = cui_font_text_geometry, .text_geometry_line = cui_font_text_geometry_line, .text_capabilities = cui_font_text_capabilities(), }; cui_context *ui = cui_create(config); /* Inside a frame, within the desired available width. */ cui_text_style style = {.letter_spacing = 1.5f}; bool ok = cui_text_paragraph_colored( ui, cui_string("Clear typography"), 24, (cui_color){255, 255, 255, 255}, 30, style, true, NULL, 0); ``` `cui_text_capabilities(ui) & CUI_TEXT_CAP_LETTER_SPACING` reports the configured provider promise; it requires both styled measurement and contextual geometry. Custom providers may set the bit only when all their measurement, geometry and rendering paths implement this contract. Their caches must include tracking where they retain positioned shapes. A legacy measure callback is insufficient. The capability does not guarantee that a particular font covers the text. | Provider / renderer | Nonzero tracking | | --- | --- | | Native HarfBuzz + Bidi, software and SDL3 | Supported | | Native build without Bidi | Unavailable | | Canvas gallery provider | Unavailable | | Sokol / SDL_GPU adapters | Rejected during preflight | The native bridge host configures the capability, but its foreign style representation still needs a separate additive tracking API. Other native hosts must opt in through the configuration above. Manual glyph callbacks receive already positioned glyph coverage; do not add spacing again. Unsupported geometry returns `CUI_TEXT_LAYOUT_UNAVAILABLE`; measurement returns zero, boolean submission/drawing returns false, and void text helpers submit nothing. Prefer boolean paragraph/contextual APIs when failure matters. Invalid values return the existing invalid/failure result. No provider silently counts UTF-8 bytes, draws individual characters or substitutes solid default text. Canvas `letterSpacing` is deliberately not used: it has not been verified to match this shaping-cluster policy and the native caret/ligature contract. ## Shaping and negative values HarfBuzz shapes complete directional/script runs first, preserving required and optional ligatures, kerning, Arabic joining and combining-mark placement. A ligature remains one cluster; tracking does not split it into individual letters. Spacing is then inserted between positive-advance clusters in visual order, including spaces and across visual run boundaries. Zero-advance clusters, including standalone default-ignorables, earn no gap. Combining and emoji sequences follow the shaper's cluster boundaries. This is cluster tracking, not CSS per-character spacing. There is no gap after the final eligible cluster of a visual line. Hard breaks reset spacing; empty lines and a single cluster gain no width. Tabs retain the provider's existing shaping behavior; this API introduces no tab stops. Negative tracking can overlap glyph ink. Each eligible cluster's advance after its following gap must remain nonnegative and all geometry must remain finite. A value that would reverse progression rejects the line; it is never clamped. Glyph ink may extend outside advance bounds, as it already can for italic text. Cluster-edge carets and selection include the following gap. Hit testing remains based on those edges, with its existing affinity rule for coincident positions. Original glyph advances remain available in `cui_text_glyph`; adjusted glyph positions, cluster spans and layout width describe the tracked result. Wrapping measures the exact contextual candidate line, so its last cluster has no trailing gap. It never breaks an intact shaped cluster. Tracked wrapping may shape multiple candidate lines and cost more than natural wrapping; the zero path retains its existing algorithm. As with ordinary contextual wrapping, joining or ligatures can change at a chosen line boundary. Color spans, gradients, alignment, clipping and inherited opacity use the same tracked geometry. Paint changes do not change shaping. Native glyph raster cache keys stay unchanged because tracking moves glyph origins and does not change their glyph IDs, faces or raster sizes. ## Verification scope `test_letter_spacing.c` checks real-font cluster and glyph identity, positive and negative widths, no final gap, combining marks, ligatures, zero-width text, caret/hit/selection consistency, narrow/wide reflow, unsupported providers and software pixels. An optional Arabic font argument exercises joining, RTL and mixed-direction runs. `test_letter_spacing_sdl.c` checks actual SDL pixels at 1×, 1.5× and 2×, including gradient coverage. Native tests run only through the private-display wrapper. GPU hardware and unimplemented Canvas tracking are not claimed as verified. --- ## Linux live-resize evidence Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/LINUX_LIVE_RESIZE.md # Linux live-resize evidence The callback-driven SDL3 host is tested on Linux independently of macOS modal resize behavior. The automated test uses X11 on the private Xvfb display created by `scripts/test_local.py`. It does not connect to the maintainer's desktop. ## What the test does `tests/integration/test_continuous_resize.c` runs the real responsive dashboard through `cui_sdl3_run`, using the pinned Inter font and SDL software rendering. It presents an initial 800-by-760 frame before resizing begins. The separate Python parent in `tests/packaging/test_continuous_resize.py` finds that process's uniquely named X11 window through libX11 and sends a timed sequence of `XResizeWindow`/`XFlush` requests: 360, 800, 1400, 480, 1100 and 640 pixels, repeated four times. Requests arrive while the callback runner is already running. The UI callbacks neither wait for the parent nor sleep/block waiting for resize. Each callback obtains current host dimensions, submits the scene and captures its real rendered BMP before emitting a presentation record. The parent collects records during the burst, requiring at least six presentations and captures at 360, 800 and 1400 widths **before the burst ends**. A final-only redraw cannot satisfy this test. It verifies: - Window dimensions and root layout dimensions agree for every sampled frame. - Main content stays within the current width; cards stack at 360 and sit beside each other at 800/1400. The sidebar becomes persistent at the LG breakpoint; narrow frames submit Menu and omit the closed navigation subtree. - Captured BMP dimensions match that frame's dimensions. Actual pixels sampled inside both current card rectangles equal the theme's card color; screenshots also contain rendered UI variation. This checks fresh scene geometry against raster output rather than accepting a stretched old frame. - The original Reports page, signed-in account and closed-drawer state survive all breakpoint crossings. The baseline `5a76db06` passed: **24 actual presentations at six distinct widths while a 1.46-second burst was ongoing**. This scoped callback-runner path did not require a production fix. It does not establish that an older manual loop or another host integration handles the user's resize path correctly. ## Run safely After the integration target is registered, configure native SDL3/text support and use the isolated wrapper: ```sh cmake -S . -B build -G Ninja -DCUI_REQUIRE_NATIVE=ON cmake --build build --target test_continuous_resize python scripts/test_local.py --build-dir build -R '^linux_continuous_resize$' -V ``` The Python driver requires the wrapper's `CUI_TEST_VIRTUAL_DISPLAY=1`, a private X11 DISPLAY and no Wayland display; unsupported platforms/drivers return 77. The child independently checks the isolation flag. The driver selects X11 and SDL software rendering. libX11 is loaded dynamically through Python's standard `ctypes`; no Python package or new production dependency is introduced. CTest applies `SKIP_RETURN_CODE 77` and a finite timeout. Temporary screenshots and the child are cleaned up on success or failure. Never replace the wrapper with `DISPLAY=:0` or the user's Wayland session. ## Coverage boundaries Xvfb has no physical desktop window manager in this test. Programmatic X11 requests prove continuous external resize dispatch, current-size layout and real presentation while the process runs. They do **not** prove physical mouse window-border dragging, compositor-specific event scheduling, Wayland, hardware GPU rendering, macOS live resize or HiDPI behavior. No custom window manager or its potential autostart programs are launched. Those paths need separate controlled evidence before claiming coverage. See [responsive containers](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/RESPONSIVE_LAYOUT.md) for the layout policy and [callback host lifecycle](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/LIVE_RESIZE.md) for runner versus manual-pump behavior. --- ## Typed List transitions Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/LIST_EVENTS.md # Typed List transitions Include `cui/cui_list_events.h`. `cui_base_list_events` adds an explicit compound control ID to the old Base arguments; `cui_list_events` uses the Styled container ID. Both accept the existing `cui_selection_handler` and return `events` plus `legacy_activated`, the original activation bool. A missing callback ignores user and preserves reduction and old callbacks. Each actual selected-ID transition delivers `cui_selection_change` after the owner write and existing `on_activate` then `on_confirm`. Multiple transitions can return to the initial owner and still notify separately. Reconfirming the same item invokes the old callbacks but emits no CHANGE unless they redirect the owner. Navigation, typeahead, secondary highlight, Escape and scroll-window state are not selection CHANGE. Old cancel/confirmation and popup behavior are retained. Payloads are pointer-free ID snapshots, copyable beyond the call. Metadata keeps the existing private forwarding seam: root target, actual frame/index/source, and activation snapshot only if available. List registration follows reduction, so HAS_ACTIVATION is often absent. Ordinary OPTION accessibility ACTIVATE is not supported by Core's current allowlist; MENUITEM differs. No accessibility parity or new input-routing behavior is implied. Non-pointer activation still uses the legacy active cursor; this facade does not redefine its item resolution. Callbacks/user borrow synchronously. During typed callbacks do not mutate/rebind owners, state, descriptors or borrowed resources; recurse; destroy storage/context; or unwind foreign exceptions. Copy payloads/change unrelated application state. As with existing selection forwarding, consuming later queued events is allowed; it does not authorize arbitrary model/resource mutation. Defer edits/removal and teardown until submission and renderer consumption finish. Legacy callbacks keep their existing owner-update timing; typed changes read the resulting owner after them. Disabled/inert/layout-only calls retain old behavior without typed events. List multi adds `cui_base_list_multi_events`/`cui_list_multi_events`, accepting `cui_choice_item_handler`. Each actual bool transition delivers a pointer-free `cui_choice_item_change` with affected `item`, causal `trigger_item`, `previous` and `value`. The adapter captures the bool before its flip, then preserves legacy activate/confirm order and observes the resulting bool. Legacy callbacks may redirect that bool and cancel its net transition; unrelated writes by legacy callbacks get no fabricated notifications. Repeated toggles remain distinct even when the final array matches entry. Item/selected-array ordering and storage stay borrowed throughout submission/paint. The result's `legacy_result` preserves the old activation bool; `change_count` counts actual typed callbacks with saturation. ToggleGroup adds matching Base/Styled `_events` functions with the same bool payload and result. Unlike List multi, it notifies immediately after each actual write. Single-mode selection clears previously true entries in array order, then sets the chosen entry; callbacks deliberately see intermediate arrays. Sibling clears use the affected `item` and causal activated `trigger_item`, sharing input metadata. False-to-false stores produce no event. Disabled siblings can be cleared by an enabled item's single-mode selection, preserving the legacy array policy. `allow_empty` rejection emits nothing. Multiple mode emits only the chosen flip. No workspace or array snapshot is allocated. `legacy_result` here is the old accepted-change bool, which can remain true after returning to the initial array. BUTTON activation support differs from ordinary List OPTION; no role remap occurs. New facades require a nonzero compound ID. Descriptors, strings and bool arrays must keep identity/order/storage throughout the call and rendering. Initial multi-true arrays retain their old behavior; no normalization policy was added. Bridge and Python/Node/Go/Rust behavior is unchanged. --- ## Native live resize and pointer motion Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/LIVE_RESIZE.md # Native live resize and pointer motion Use `cui_sdl3_run(argc, argv, callbacks)` for native applications. Initialization creates the backend and Core context; the frame callback composes and presents one frame using freshly queried `cui_sdl3_size`; quit releases application resources. Return zero from frame to continue, positive to finish successfully, negative on failure. The starter and native gallery show the complete pattern. All callbacks run on the main thread. Do not call event waits or nest a runner inside these callbacks. `cui_sdl3_poll` remains valid there for IME/cursor synchronization and does not recursively pump SDL. The runner uses SDL's supported callback entrypoint `SDL_EnterAppMainCallbacks`. The existing ordinary `main` entrypoints remain code-driven; no SDL types enter CUI's public APIs and no extra SDLMain library is required. The existing macOS bundle font lookup and static SDL dependency linkage remain in place. This distinction matters during native resize. Pinned SDL 3.4.18 implements `SDL_OnWindowLiveResizeUpdate` in `src/video/SDL_video.c`: callback-main apps get `SDL_IterateMainCallbacks(false)` while ordinary loops only receive a queued EXPOSED event. Cocoa's live-resize timer calls that function at approximately 60 Hz; Windows' modal size/move timer calls it too. A conventional poll loop can remain inside the OS event pump until dragging stops, so invalidating it alone cannot guarantee intermediate composition. The runner lets SDL invoke composition from its main-thread modal-loop iteration, without drawing in an event watcher. A reentrancy guard prevents nested frame callbacks. Foreign-thread lifecycle notifications never mutate Core or draw through the adapter. Custom poll/step loops remain supported. They must adopt callback-main scheduling to obtain this modal live-resize behavior; calling `cui_sdl3_size` more often or reducing a sleep interval does not replace that scheduling change. Logical resize, pixel-size change, display-scale change and expose notifications invalidate Core. Density-aware text rasterization, rounded-strip batching and elapsed frame timing remain enabled. Idle callback scheduling uses SDL's event wait; active animations keep continuous iteration. Call `cui_invalidate` for main-thread model changes or when a frame-limited capture needs another frame. The adapter coalesces consecutive mouse motion before forwarding it to Core's bounded event queue. It flushes the latest position before clicks, leave, focus and other non-motion events, preserving ordering. This prevents a burst of old positions from filling the queue and dropping the latest hover position. It does not coalesce touch motion or discard click transitions. `cui_bridge_run(app, after_frame, user)` exposes the same native scheduler through the canonical C bridge. Its optional callback dispatches language/application events after each successful frame; return OK to continue or a status to stop. Catch foreign exceptions before returning through C. Nested run/step returns INVALID_STATE. Closing during the callback ends with CLOSED. Destroy during the callback requests close and defers release until the runner exits; that pointer must not be used afterward. Otherwise the terminal app must still be destroyed by its owner. The native host is released at run completion. Portable builds return BACKEND_UNAVAILABLE. Existing language `App.run` loops must call this new symbol to benefit; retaining a sleep/step loop does not enable live modal resize. Older bridge libraries require a clear missing-symbol/unavailable fallback. Headless Linux coverage exercises real SDL frames after a 320x160 to 480x240 resize, main-thread callback dispatch, and a 3000-motion burst reaching the next frame. Bridge cases cover close, callback error, reentrant calls, deferred destroy and a null callback. These tests run through `scripts/test_local.py` in private Xvfb. Cocoa/Windows source inspection supports the scheduling contract; actual macOS/Windows drag responsiveness remains host acceptance, not a Linux runtime claim. Hardware/GPU display migration remains deferred. Linux additionally has a [continuous X11 resize test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/LINUX_LIVE_RESIZE.md): an external process resizes an already-running responsive dashboard through repeated breakpoint crossings. Captures and geometry prove intermediate presentation while the resize burst is ongoing, including sidebar/card adaptation and retained app state. This is stronger than a final-size assertion, but does not establish physical window-manager dragging or Wayland behavior. --- ## MenuTree command notifications Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MENU_EVENTS.md # MenuTree command notifications `cui_base_menu_tree_events` and `cui_menu_tree_events` add synchronous per-command ACTIVATE observers. They preserve Base/Styled MenuTree mutation, navigation and close behavior. Simple Menu, ContextMenu, Dropdown, SplitButton and other forwarding are outside this slice; no uniform menu-family or binding coverage is implied. ```c #include static void command_activated(void *user, const cui_menu_command *command) { cui_id *last_seen = user; *last_seen = command->command; } /* During composition; action/tree/descriptors and pointed-to values belong to app. */ static cui_menu_command_result file_menu(cui_context *ui, const cui_theme *theme, const cui_menu_entry *entries, size_t count, cui_id *action, cui_menu_tree_state *tree, cui_id *last_seen) { return cui_menu_tree_events(ui, 2, theme, cui_string("File"), entries, count, action, tree, (cui_menu_tree_options){.popup = {.viewport = {0, 0, 640, 480}}, .keep_open_checks = true}, (cui_menu_command_handler){command_activated, last_seen}); } ``` Initialize tree once with `cui_menu_tree_init` and a stable nonzero popup ID. The new entry points match the legacy argument order and append `cui_menu_command_handler`. Base draws nothing; caller submits its normal menu-entry semantics/geometry after reduction. Styled retains its existing trigger, metrics and popup painting order. Descriptor/child IDs remain globally unique throughout the tree; pointed-to check/radio storage stays caller-owned. `cui_menu_command_result` contains `valid` (applicable preflight passed), `submitted` (ordinary active submission), `command_count` (actual observer invocations), `count_overflow`, and `legacy_activated` (the original aggregate bool). Counts saturate at `SIZE_MAX` while dispatch continues. Missing observer preserves all commands, mutations and close behavior with count zero; `legacy_activated` may still be true. Disabled controls can submit but cannot command; inert/layout-only ancestry cannot notify. Later Core/rendering errors remain possible after preflight. Every command branch reached emits once, including repeated same ID, CHECK toggled twice in one call, and RADIO confirmed while its value already matches. This is ACTIVATE, not a value CHANGE or owner-rejectable request. CHECK/RADIO writes and action output are applied before the observer; no callback return can veto them. Navigation/typeahead, submenu opening, scrolling, dismissal, labels/separators, disabled or malformed entries and external state writes do not emit command activation. Missing check/radio storage or empty submenu follows existing disabled policy. The callback receives pointer-free `cui_menu_command { event, command }`. `command` is the actual committed leaf ID; `event.kind` is ACTIVATE and `event.target` is the public trigger. Payloads omit descriptor pointers, labels, shortcut/icon text and generic check/radio snapshots. Applications own their model and can inspect applied state synchronously. Copying the payload preserves it beyond frame/context lifetime; referenced users/state/resources remain subject to their existing lifetime boundaries. The order at each command is existing active/depth updates, check/radio write, action output write, existing close policy, then observer. Thus callbacks see applied values and already-applied close/focus state. The reducer freezes whether that command must return before invoking the observer, preserving the closing command boundary. Keep-open commands continue through remaining eligible events in original reducer order. Observers may update command-owner values or unrelated application state and consume later input; those writes are not recursively synthesized commands. Do not perform duplicate side effects through both callback and aggregate result. Metadata is frozen before writes/close. A genuine accepted Core activation snapshot is copied only if already available, retaining its original child target. Normal MenuTree entry semantics register after reduction, so HAS_ACTIVATION is ordinarily absent. Fallback metadata contains only actual frame/index and source proven by pointer-up, keyboard or accessibility event type. No coordinates, touch details, accepted accessibility snapshot or programmatic source is invented. Keyboard redirection can commit a different active leaf from the original routed target; command ID and any genuine snapshot each retain their actual meaning. See [shared metadata](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMPONENT_EVENTS.md). Core already supports accessibility ACTIVATE for MENUITEM, MENUITEMCHECKBOX and MENUITEMRADIO. The tests use genuine supported menu accessibility actions; this does not remove Select/Combobox OPTION activation limitations. Touch input establishes pointer source at this seam without implying a copied touch activation snapshot. Handler/user/payload are borrowed synchronously. Copy handler/options at call entry; descriptor arrays/children and active storage must remain stable/alive throughout submission, and rendering resources through their existing completion boundary. Directly mutating in-flight popup/navigation state, freeing active state/users/resources, destroying the active context or recursively submitting the same frame is unsupported. Request removal/shutdown in application state and perform it after submission/frame completion. The frozen return policy is not a navigation-mutation API or a runtime destruction guard. No registration, queue, routing, scheduler or foreign request hook is added. `tests/unit/test_menu_events.c` exercises real Base/Styled commands, repeated check/radio/action IDs, post-write/post-close state, missing handlers, pointer/touch/key and supported accessibility input, nested keyboard redirection, owner updates/later consumption, closing-command termination, disabled/inert/omitted calls, legacy coexistence and copied lifetime. Existing `test_choice.c` retains navigation/depth/scroll/drag/render compatibility proof. Run registered native tests only through the invisible wrapper: ```sh python scripts/test_local.py --build-dir build -- -R '^(menu_events|choice)$' ``` [Design checkpoint](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/MENU_COMMAND_EVENTS_SLICE.md) compares the per-command seam with the lossy aggregate-last alternative. Simple Menu/ContextMenu/Dropdown forwarding, controlled/vetoable commands, check/radio CHANGE payloads, lifecycle observers, binding exports and parity promotion remain deferred. Root owns module/CMake/generator/SDK and human/LLM API indexing integration. Compact-ID renderer regression: RADIO entry12's old left-icon wrapper (`12 ^ 0x9e3f5d2a91bca001`) collided with SUBMENU entry15's chevron (`15 ^ 0x9e3f5d2a91bca002`), both `0x9e3f5d2a91bca00d`. The paint-only wrapper now uses anonymous row-local layout identity; named icon resource IDs and all menu routing/public IDs stay unchanged. The ordinary unit fixture uses these exact compact IDs and verifies both radio and submenu raster glyph coverage/geometry without duplicate identities. This targeted fix does not imply full Menu renderer parity. --- ## MessageScroller exact offset and following-tail observers Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MESSAGE_EVENTS.md # MessageScroller exact offset and following-tail observers Include `cui/cui_message_events.h`. `cui_base_message_scroller_events` and `cui_message_scroller_events` append a borrowed `cui_message_scroller_handler` to the old arguments. Their result carries the exact old return in `control_result`, `valid`, independent `offset_changed`/`tail_changed`, delivered zero/one `offset_change_count`/`tail_change_count`, and `count_overflow` (always false). Offset payload `cui_message_offset_change` contains metadata and double `previous,value`. Tail payload `cui_message_tail_change` contains metadata and bool `previous,value`; tail means the model's following policy, not proximity, rendered visibility or receipt of a message. Exact double inequality determines offset change; the existing reducer's tail tolerance remains unchanged. Float scrollbar and semantic coordinates do not replace the double snapshot. Each wrapper snapshots before any legacy maintenance, including Styled width remeasure and Base previous-row-bound reconciliation/layout. It executes the old operation exactly once and freezes both payloads after completion. Offset callback runs first, then tail callback if each changed and its handler exists. Styled observers run after legacy row/jump-content callbacks, tracked-bound registration, paint and box closure. Base observers run after the complete old reducer. There is no nested Base observer, second layout call or new allocation/listener storage. `control_result.changed` includes row measurement and opacity animation; it does not gate these observers. Offset can change during reconciliation before the legacy reducer's local old-offset snapshot. Conversely, animation-only changed, wake scheduling, or total/window changes with stable offset/tail emit nothing. Tail can change while offset stays zero. Both payloads describe the same completed operation, independently of callback activity on unrelated application state. Metadata is CHANGE, UNKNOWN source, with genuine nonzero frame only. Aggregate layout/measurement/wheel/key/bar/jump effects do not establish one input cause, index or activation. Non-submission entry rejects before work. Ordinary admitted inert/layout-only frame-zero maintenance preserves legacy results and change flags but suppresses callbacks. Missing handlers also leave flags intact and counts zero. Invalid legacy operations emit nothing; unsupported nonfinite internal offsets do not generate fabricated previous values. Omission retains no handler. Explicit reset/splice/append/prepend/measure/remeasure/to-item/to-end/scroll/layout operations remain synchronous and result-only. Their changes before wrapper entry are the new baseline, without a delayed event on the next draw. Changes caused by maintenance inside the observed call are included with UNKNOWN origin. Repeated submissions observe each call independently; result reads never replay callbacks. Choose results or observers for application side effects. Payloads are pointer-free values: copy by assignment into caller storage and use the copies after callback, frame or context destruction. This does not extend active model lifetime. Handler/user are borrowed only through return. New observers may copy payloads and mutate unrelated application data, but cannot mutate/free active state, records, options/theme or input, recursively submit or destroy context. Existing legacy renderer/jump callback behavior and restrictions remain unchanged. State and collection must still agree and remain stable until `cui_end_frame` completes because tracked bounds write into live state then. Defer teardown accordingly. Later bounds reconciliation does not retain handlers. There is no data-received/read, renderer completion, network, GPU, capture/bubble, veto, context-destruction or foreign-language callback API. VirtualList's pending window contract is separate; MessageScroller does not gain a deferred finish. `tests/unit/test_message_events.c` compares legacy and observed Base/Styled results, row counts, consumed input and exact offsets through anchor/layout/width changes. It exercises double offsets beyond float precision, tail-only changes, frozen callback order, animation-only silence, passive/missing/invalid/omitted calls and copied payload lifetime, and runs existing message regression assertions. Native execution uses `python scripts/test_local.py --build-dir build -- -R message`. --- ## Multiline aggregate CHANGE observers Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MULTILINE_EVENTS.md # Multiline aggregate CHANGE observers Include `cui/cui_multiline_events.h` for `cui_base_textarea_events` and `cui_textarea_events`. Each mirrors its existing Textarea entrypoint, appends a `cui_component_text_handler`, and returns `cui_multiline_event_result`: ```c cui_multiline_event_result result = cui_textarea_events( ui, id, &theme, cui_string("Notes"), edit, &state, options, (cui_component_text_handler){on_change, app}); /* result.control is the existing cui_textarea_result. */ ``` This facade deliberately aggregates notification: **at most one CHANGE per submission**, after Base Textarea finalizes its event loop, semantics and scroll state, and before Styled Textarea performs its remaining layout and paint. Several text edits, newline insertion, indentation, paste or Undo/Redo can coalesce into one notification. It is not the per-event timing of [Input observers](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TEXT_INPUT_EVENTS.md). Existing Textarea entrypoints, options, mutation timing, aggregate results and rendering behavior remain unchanged. `change_count` counts actual callbacks, zero or one. A missing callback does not make the control readonly: edits still apply, with zero callback count. A callback receives the scalar committed `before` and `after` state, including primary selection and revision. Revision change is the criterion: typing then Undo in one submission can notify even if final bytes equal initial bytes. Selection, scrolling, preedit or external edits completed before submission do not themselves notify. Metadata has CHANGE kind, the target and actual frame sequence, UNKNOWN source, and HAS_FRAME only. There is no event index or activation: a batch can have many causes. Do not interpret default scalar index fields when HAS_INDEX is absent. There is no SUBMIT event. Legacy `pressed_enter`, `enter_secondary` and `enter_shift` remain in `result.control` with their existing aggregate semantics. IME START/UPDATE/CANCEL normally changes only preedit presentation and does not notify. A committed revision change on IME COMMIT notifies; a failed commit with no revision change does not. Disabled/readonly behavior remains the legacy behavior. Notifications describe committed edits, not successful layout or validation. If an edit succeeds and a later row-capacity/layout failure occurs, the observer still runs and `result.control` retains the legacy error. Initial validation/layout failure before mutation produces no CHANGE. The Base facade observes every return from the existing reducer, so an applied edit is not hidden by a subsequent error. The Styled facade preserves this count even if its later layout/painting fails. The event's committed text is borrowed only during the callback. Retain it with `cui_component_event_copy_utf8` and caller-owned bounded storage; copying the event struct alone does not retain text. Textarea has no password/masking option: its text payload is not redacted. Hosts handling sensitive documents should avoid retaining text and use scalar metadata as appropriate. Observers may set unrelated application flags. They must not mutate, rebind or destroy the context, edit, state, buffers, history/selection arrays, layout rows, composition storage, theme or other borrowed descriptors; recursive UI submission and painting are also unsupported. This is a caller precondition, not a runtime guard. To close or remove the control, set an application flag and omit it on a later frame; defer destruction until the frame and renderer have consumed borrowed resources. An observer cannot reject an already committed edit. These facades do not add multi-cursor selection notifications, REQUEST, COMMIT, SUBMIT, or language-binding observers. `tests/unit/test_textarea_events.c` checks old/new text, selection, revision/history, aggregate results, semantic identity/value and draw-command equivalence; multiple updates coalesce; IME preedit, success and capacity failure; absent observers; readonly/disabled and Enter behavior; bounded copies; deferred omission; committed edits followed by row-capacity failure; and the direct Base type-then-Undo case. Legacy Textarea and Editor tests remain required. Native test execution uses the private-display `scripts/test_local.py` wrapper. No browser/binding parity is claimed. ## Editor observers Include `cui/cui_editor_events.h` for `cui_base_editor_events` and `cui_editor_events`. They mirror the corresponding legacy signatures, append the same text handler, and return `cui_multiline_event_result`. Editor's committed text is borrowed and not redacted, with scalar primary-selection snapshots only. Base Editor notifies after the entire existing call, including completion, multi-cursor, nested Textarea and final search/cursor synchronization. Styled Editor notifies after its **whole call**, including main painting and completion popup pointer acceptance. This timing differs from Styled Textarea, which notifies at its Base seam before paint. The nested Textarea is never observed or replayed. Keyboard and pointer completion acceptance and simultaneous multi-cursor edits all coalesce into at most one final revision notification. Editor metadata uses UNKNOWN source, no index/activation, and HAS_FRAME only when the actual frame sequence is nonzero. Its callback count derives from committed revision change even when the legacy result contains an error; `control` remains exactly the original result. Existing popup paint and mutation timing is preserved: the observer does not force a new paint to show a just-accepted completion. A later frame follows the existing invalidation behavior. Initial validation failures with no revision change do not notify. No cause is inferred from consumed events. The same no-mutation/reentry/destruction preconditions apply to Editor and its completion items, search matcher, folds, multi-cursor anchors/history/selection storage, clipboard scratch and highlight resources. Defer teardown until the outer facade returns and renderer consumption finishes. Set unrelated flags in the callback to omit the editor in a later frame. `tests/unit/test_editor_events.c` checks legacy result/paint/semantic equivalence, aggregate text batches, keyboard and pointer completion, multi-cursor edits, IME success/failure, null observer editing, copy lifetime, deferred omission, row capacity errors after mutation and failures before mutation. It also checks the Base facade with type-then-Undo returning to the same bytes. Legacy Editor and Textarea suites remain required; no browser or foreign-binding coverage is implied. --- ## Optional Linux native accessibility, phase 1 Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NATIVE_ACCESSIBILITY.md # Optional Linux native accessibility, phase 1 This backend publishes completed CUI semantic snapshots through pinned AccessKit and executes targeted Focus/Click through Core's accessibility action queue. The automated Linux X11 test uses a real SDL3 window and independent libAT-SPI client over DBus. This is transport and action coverage, **not** full native accessibility, editable-text support, or an Orca/physical screen-reader claim. Windows/macOS adapters and Wayland screen extents are not implemented here. ## Build and use Ordinary builds keep `CUI_BUILD_ACCESSIBILITY=OFF` and do not inspect the cache, invoke Rust or fetch dependencies. Explicitly prebuild the pinned archive with Rust 1.85+/Cargo, then enable the optional Linux adapter: ```sh python3 scripts/build_accesskit.py cmake -S . -B build -G Ninja -DCUI_BUILD_ACCESSIBILITY=ON cmake --build build --parallel 6 ctest --test-dir build --output-on-failure -R accessibility cmake --install build --prefix /your/local/prefix ``` CMake imports the existing archive; it never invokes Cargo or downloads a missing dependency. Missing or mismatched archive, lock, ownership extension or private header fail configuration. The binary SHA is recorded in installed `share/cui/licenses/accesskit/accesskit-build.json`; it identifies the local artifact, rather than claiming a reproducible upstream binary. Run the pinned builder before configuring to establish its provenance. This is a host-built Linux package; cross compilation is rejected. Native runtime tests additionally require SDL3/Freetype/HarfBuzz, libAT-SPI, DBus/gdbus and Xvfb. CMake reports when those tests are omitted, while the portable snapshot/action tests remain available. The standalone harness also remains available via `cmake -S backends/accesskit -B build-accesskit -G Ninja`. It is a validation harness rather than the installation/package entry point. Use `--cache PATH` and `-DACCESSKIT_CACHE=PATH` together for another private cache. Nothing installs globally. The script verifies the archive, every cached source file and Cargo.lock, and uses `cargo build --release --locked`. The private ownership module and exact entry-point extension have separate hashes in `backends/accesskit/extension.json` and the cache's `cui-extension.json`. See [dependency metadata](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/third_party/accesskit/README.md) for licenses and binary-distribution notice requirements. Create one `cui_accessibility` per window. On the UI thread: ```c cui_accessibility *a = cui_accessibility_create((cui_accessibility_config){0}); /* Each frame, before begin_frame: */ cui_accessibility_drain(a, ui); /* poll host input, begin/build/end the ordinary CUI frame */ cui_accessibility_window window; if (cui_sdl3_accessibility_window(host, &window)) cui_accessibility_update(a, ui, window); /* after end_frame */ /* On close, before destroying host/callback user: */ cui_accessibility_destroy(a); ``` Publish **every completed frame**, including removal frames. `update` rejects Core errors and invalid UTF-8/NUL/nonfinite metadata atomically. Core errors are sticky: handle them and call `cui_clear_error` according to Core's existing contract. Never call update during a frame or race public operations with destroy. The SDL helper only returns portable metadata; it adds no Rust/native bridge linkage to the SDL library. Its borrowed title is copied by update. Other hosts supply equivalent title/focus/outer/inner metadata themselves. Window coordinates and semantic bounds must use the same logical units. X11 1x is tested; mixed-DPI and decoration behavior require additional platform validation. ## Ownership, generations and actions Defaults allocate two banks of up to 2048 semantic records and 65536 string bytes per bank, plus 128 requests. Callers can configure larger bounds before create. Creation returns null on size overflow/C allocation failure. `stats.native_active` reports observed native activation; successful creation alone does not prove a working desktop accessibility bus/client. Snapshot overflow preserves the previous tree/tokens and reports `CUI_A11Y_CAPACITY`; it never truncates. Names/descriptions/title are deep copied, with no retained Core pointer. Unchanged snapshots skip native tree allocations. Published changes currently use full bounded tree updates; record/relationship lookup is linear, so large trees should be profiled before increasing the default limit. AccessKit/Rust has its own allocation behavior; native allocator exhaustion can abort and is not covered by CUI's recoverable C allocation contract. A native token is never reused within a bridge. Removing/reintroducing an ID or changing its role generates a new token, so old queued requests cannot activate its replacement. Applications must change the CUI ID for a same-frame logical replacement with the same role; Core exposes no identity stronger than ID/role. Skipping removal snapshots would also erase this distinction. Public token and request helpers use the same bounded mailbox as native callbacks, useful for portable host adapters and tests. Foreign-thread AccessKit handlers only read the locked copied snapshot and enqueue Focus/Click tokens. They never call Core or SDL. The optional wake callback must be thread safe, must not reenter this backend/wait for the UI thread, and must not call Core/SDL. Main-thread drain revalidates token and Core capability, discards stale/disabled/modal-obscured requests, and preserves unqueued requests on Core backpressure. Invalid/stale requests never enter Core. Core queue capacity errors retain Core's normal observable/sticky error contract. Multiple Click requests remain individual Core events; the existing boolean interaction API may coalesce same-control activations within one frame. `destroy` closes the mailbox and disables wake synchronously. Pinned Unix adapter removal is asynchronous: the private Rust Arc ownership wrapper retains C storage until the last activation/action/deactivation handler drops, then releases it once on that thread. Callers may destroy Core/window/wake userdata after public destroy returns. No process-lifetime tombstone pool or dangling frame strings are used. ## Mapping and limits All current CUI roles map explicitly to AccessKit roles. Generic containers can be flattened by the platform. The tree includes parent/child order, names and copied descriptions, checked/selected/expanded/disabled/readonly/required/busy/invalid states, orientation, numeric range metadata, collection positions/table indices, scroll metadata, live-region policy, focus and window-relative semantic bounds. Static Label names use AccessKit's label-value convention. `controls` and `labelled_by` map to native-node references; missing targets are omitted and parent cycles are rejected. This is metadata mapping, not a claim that every property is exposed identically by AT-SPI. Core does not expose an OS modal marker or clipping metadata: the navigation tree retains behind-modal nodes and full semantic bounds; Core suppresses their actions. OS modal tree hiding/precise clipping need a later portable semantic extension. Only Core-supported Focus/Activate are advertised. Focus changes Core focus; OS window focus remains host metadata, and this bridge does not raise windows. Button, Checkbox, Switch, Radio, Link and eligible menu items use the ordinary activation path. Tab/Option/ Tree/table compound reducers have conservative Focus-only support; merely showing a role does not enable its domain action. There is no SetValue, editable text, selection/caret, document text ranges, scroll action, or increment/decrement bridge. Read-only scalar/static-label metadata does not imply native Value/Text editing. See [Core action contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/ACCESSIBILITY_ACTIONS.md). Pinned `accesskit_atspi_common` 0.20.0 exports `controls` as ControllerFor; its `relation_set` does not export LabelledBy. The tree stores labelled-by references, but an AT-SPI LabelledBy claim would be false. Installed libAT-SPI 2.62.1 also warns about AccessKit's cache signal signatures; direct query/actions pass after explicit cache refresh. Cache/screen-reader compatibility remains a limitation. Primary provenance: [accesskit-c pin](https://github.com/AccessKit/accesskit-c/tree/0824c4a1e3a4d13ce5582df20e394fba49485a15), [Unix adapter ownership](https://docs.rs/accesskit_unix/0.23.0/src/accesskit_unix/adapter.rs.html), [AT-SPI relationship mapping](https://docs.rs/accesskit_atspi_common/0.20.0/src/accesskit_atspi_common/node.rs.html), [SDL window bounds](https://wiki.libsdl.org/SDL3/SDL_GetWindowBordersSize). ## Validation Headless tests cover copied-string lifetimes, unchanged frames, UTF-8 rejection, atomic string/node capacity failure, configured larger capacity, generations, missing/stale/disabled/modal targets, invalid actions, threaded mailbox overflow, Core backpressure, exactly-once drain and boolean coalescing. Private counters check release exactly once after repeated create/destroy and async native teardown. The real native test queries roles, screen extents, ControllerFor target and checked state; requests Component Focus/Action Click and observes actual Core effects; checks disabled actions and removed/reintroduced nodes. It holds a real native action pending during destruction and verifies wake runs off the UI thread. The frame label is intentionally overwritten immediately after snapshot publication. ```sh cmake -S backends/accesskit -B build-accesskit-asan -G Ninja -DCUI_SANITIZE=ON cmake --build build-accesskit-asan ASAN_OPTIONS=detect_leaks=1 ctest --test-dir build-accesskit-asan --output-on-failure ASAN_OPTIONS=detect_leaks=0 backends/accesskit/run_native.sh ./build-accesskit-asan/test_accessibility_native ``` C Core/backend/SDK code is ASan/UBSan instrumented; the pinned Rust release library is not. Native leak detection is disabled for host libraries; C backend release counters remain checked. The runner isolates DBus/Xvfb and uses in-memory GSettings, never changing desktop accessibility settings. It starts the installed registry explicitly because service activation may require a systemd user manager. Installation includes the portable accessibility header, production adapter, private static AccessKit archive, CUI Core, AccessKit C/Rust notices and the aggregate inventory of all ninety pinned Linux dependency notices. Private test hooks and the upstream AccessKit header are not installed. A relocated installation supports either: ```cmake find_package(CUIAccessibility CONFIG REQUIRED) target_link_libraries(app PRIVATE CUI::cui_accessibility) ``` or `pkg-config --static --cflags --libs cui-accessibility`. CMake links Core, the imported Rust archive, Threads, dl and m transitively; pkg-config includes the static dependency flags. Set `CMAKE_PREFIX_PATH` or `PKG_CONFIG_LIBDIR` to the installation. Neither interface references the original private cache. `tests/packaging/test_accessibility_package.py --build build` installs into a temporary prefix, relocates it, compiles/runs strict C11 consumers through both interfaces, checks real Focus/Activate effects, all ninety notices, artifact SHA and absence of private test symbols. It also builds ordinary Core with a nonexistent cache while the option is OFF and checks missing/corrupt-cache configuration failures. The optional root CTest suite registers this proof. Full native runtime coverage still has the phase1 limits documented above. The reserved distribution check may remain stale until integration regenerates the global bundles. --- ## Aggregate NumberInput CHANGE observation Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NUMBER_EVENTS.md # Aggregate NumberInput CHANGE observation Include `cui/cui_number_events.h` and use `cui_base_number_input_events` or `cui_number_input_events` with the existing arguments plus a `cui_number_event_handler`. Both return the unchanged native `control` result and an actual `change_count` of zero or one. The callback is `void callback(void *user, const cui_number_change_event *event)`. The pointer-free payload contains shared `event` metadata and finite double `before`/`after` values. It observes the final committed numeric owner, not draft revision or intermediate steps. Exact numeric inequality is used: signed zeros compare equal, adjacent finite doubles and subnormals remain distinct, and changes that cancel within a call do not notify. Invalid/nonfinite entry owners are still rejected by the native reducer. No epsilon, float narrowing or extra formatting is introduced. ```c static void number_changed(void *user, const cui_number_change_event *event) { double *last_observed = user; *last_observed = event->after; } cui_number_event_result result = cui_number_input_events( ui, id, theme, cui_string("Quantity"), state, value, options, (cui_number_event_handler){number_changed, last_observed}); /* result.control retains changed/submitted/invalid/step_direction/error. */ ``` An absent callback accepts and ignores user data and still performs ordinary reduction. `step_by/step_user` remain the existing step-magnitude policy with the same invocation order; they are not observer conflicts or requested-value callbacks. Missing observers never make the control readonly. Delivery occurs after Base reduction's final bookkeeping/semantics/invalidation, before Styled painting. A numeric change already committed despite an edit error still notifies; neither `error` nor callback count promises successful rendering or rollback. In particular, failed clamp-draft normalization can preserve the parsed draft value rather than the entry owner. The original result is returned without suppressing its error. Enter without numeric change does not notify; `submitted` remains its legacy aggregate flag. This API adds no REQUEST, COMMIT, SUBMIT or per-event notification. Only ordinary active, enabled, editable submissions notify. Inert/layout-only, outside-frame, disabled and readonly calls do not notify. They still execute the legacy reducer once: draft synchronization/normalization and any legacy owner mutation remain compatible, so zero callbacks does not imply no model changes. External owner synchronization completed before entry is not a numeric change of this call. Draft-only edits, preedit and invalid drafts also do not establish one. Metadata is CHANGE at the NumberInput root ID, source UNKNOWN and HAS_FRAME only. The same nonzero `cui_frame_sequence` before/after reduction proves the current ordinary completion frame, excluding passive/protected phases. No input index, source or activation flag is inferred. This is not a physical-input audit log. Callback/user are borrowed only during this call; no registration is retained. The payload may be copied. Keep context, state, editor, composition resources, owner value and user storage alive until the outer call returns and applicable frame rendering consumes its borrowed data. No recursive submission, edit/state/ selection/composition mutation, rebind, destruction or exception unwinding through C during notification. Updating unrelated application state is allowed. The observer may assign a finite new owner value through its own captured pointer. The event remains the frozen native before/after snapshot and does not recursively notify. Current semantics and Styled paint retain the already-reduced draft; the next submission notices the owner mismatch and synchronizes normally without notification for that synchronization alone. No hidden post-callback draft rewrite or `last_value` adjustment is performed. Nonfinite observer assignments are outside the supported update contract and cause native validation failure next time. Unit coverage compares Base/Styled facades with legacy passive/disabled/readonly reduction, checks multi-step coalescing, Enter/blur normalization, finite precision, real edit-capacity failure after owner mutation, policy call counts, owner updates and ignored user data without a callback. Existing numeric tests remain unchanged. Bridge NumberInput still uses its existing queued LEGACY payload; this C API does not add typed bridge scalar events, bindings or full input-family parity. --- ## Numeric selection CHANGE observers Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NUMERIC_SELECTION_EVENTS.md # Numeric selection CHANGE observers Include `cui/cui_numeric_selection_events.h`. Pagination's additive Base and Styled `_events` entrypoints accept `{change, user}` and return the original aggregate bool as `control`, plus actual synchronous `change_count` (zero or one). A missing callback ignores user and preserves normal reduction. ```c static void page_changed(void *user, const cui_pagination_change_event *event) { size_t *last_page = user; /* Separate application storage, not the owner. */ *last_page = event->after; } /* During the ordinary active UI frame: */ /* cui_pagination_events(ui, id, theme, &page, total, false, false, * (cui_pagination_event_handler){page_changed, &last_observed_page}); */ ``` The event contains pointer-free shared `event` metadata and exact native `size_t before`, `after`, `total`. Pages are one-based, or zero when empty. Normalization is part of the aggregate change. Multiple operations coalesce; returning to the entry value produces no notification. Numbered-button mapping continues to use the legacy normalized entry window. Callbacks run after Base reduction/semantics and before Styled paint. Metadata has CHANGE, root target, UNKNOWN source and HAS_FRAME for the current active completion frame. It does not claim input index, activation count or physical origin. Disabled, inert and layout-only submissions retain legacy normalization and bool behavior but never notify: zero callbacks does not mean zero mutation. `control` is not a validation or paint-success result. Handler/user are borrowed for the outer call; no registration or replay occurs. Copy events for later use. Do not change the owner, recursively submit, mutate borrowed descriptors, destroy storage/context, or unwind foreign exceptions from the callback. Request teardown or owner updates in separate application state and perform them after the outer call returns. Styled paint rereads the owner; owner mutation during observation has no supported rendering contract. Stepper adds the same Base/Styled `_events` pattern with a distinct `cui_stepper_change_event`: exact `size_t before`, `after`, `count`. Indices are zero-based; an empty list normalizes to zero. Descriptors, titles and descriptions remain borrowed through the call. Selection does not rewrite explicit statuses; Styled paint still shows Current only on the selected item, retains Complete and Error, and shows an unselected ACTIVE descriptor as Pending. Counts above 100 or missing nonempty descriptor arrays retain legacy rejection. Disabled items cannot activate, while list-wide normalization still occurs when disabled or passive. Rating adds a distinct `cui_rating_change_event` containing native `float before` and `after`, `bool before_finite`, and effective defaulted/capped `unsigned maximum`. The legacy reducer normalizes NaN and infinities to zero; an eligible observation preserves that nonfinite `before` and sets `before_finite=false`. Do not compare NaN using ordinary equality or assume canonical NaN payload bits. The committed `after` is finite. Finite values compare exactly, with no epsilon; signed zeros compare equal. Whole/half-step rounding and range clamping can cause CHANGE even without input. Readonly suppresses callbacks while preserving normalization. Pointer half-star selection and keyboard/full-star activation retain their existing differences; Home still clears regardless of `clearable`, while Delete/Backspace clearing requires it. Rating is a float API, unlike NumberInput's double API. Failed later icon preparation does not undo a committed change. Legacy entrypoints remain unchanged. These facades do not expose per-event REQUEST, COMMIT or SUBMIT, and add no bridge notification tags or binding wrappers. The native `size_t` payload is not a guarantee about legacy bridge float transport. Verification uses actual reducers, unchanged legacy tests, and paired Base/Styled submissions comparing scalar owners, bools, semantics, focus, geometry, draw text, colors and Rating bitmap pixels. Tests include queue-rejected disabled accessibility actions, input coalescing/cancellation, nil handlers, passive normalization, and callback payload copies with teardown deferred until the outer call returns. Native test execution uses `scripts/test_local.py` with a private display; hardware GPU behavior is outside this portable slice. --- ## Repeatable human and agent onboarding tasks Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/ONBOARDING_BENCHMARK.md # Repeatable human and agent onboarding tasks This is a task protocol, not a measured usability result. Run the same tasks for a human and an agent against the same revision, extracted native bundle, machine and installed prerequisites. Start timing after prerequisite verification; record installation time separately. Keep the documentation available in both runs. | Task | Completion evidence | | --- | --- | | Build unchanged bundle outside repository | `make` exit status and bounded capture | | Change greeting in `app.c` | Capture shows new text; vendor object timestamps unchanged | | Add a second portable `.c` file and rename target | Build using `APP_SOURCES`/`TARGET`, capture from renamed executable | | Compose a mail row | Fixed avatar/trailing timestamp, growing text, constrained narrow-window content | | Repeat and reorder three rows | Stable record-key scopes; correct row activates after reordering | | Diagnose a missing icon and duplicate ID | Correct registry lookup, observed error and repaired submission | Record elapsed time, build attempts, compiler errors, invented API names, documentation pages opened, interventions, final test evidence and unresolved limitations for each task. Do not count a screenshot alone as interaction proof. For mail rows test long subjects and narrow widths; for identity test activation before and after reorder. Keep benchmark application experiments outside vendor sources. Automated Linux captures must run on invisible Xvfb; repository tests use `python scripts/test_local.py --build-dir build`. Defer GPU-only observations. Report raw observations before comparing human/agent outcomes. This protocol makes no claim that the tasks have been run or that onboarding is universally fast. The full catalog retains 78 entries and their recorded limitations. ## Automated observations for this milestone The native-bundle consumer test builds the unchanged two-file app outside the checkout, verifies UI-only incremental compilation, builds a source in a subdirectory with a renamed executable, and captures both that app and the mail fixture. The mail Core fixture drives Compose/Discard, selects and stars the second repeated row, verifies its reader text, and scrolls the list while the folder pane stays still. The exact four-argument sidebar content callback is compiled with warnings treated as errors. Text/JSON layout export is exercised through the native command line. These are automated correctness observations; human elapsed time, agent elapsed time and independent usability outcomes have not been measured. --- ## OTP CHANGE observation Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/OTP_EVENTS.md # OTP CHANGE observation Include `cui/cui_otp_events.h`. `cui_base_otp_events` and `cui_otp_events` add a synchronous `{change, user}` observer to the existing Base/Styled signatures. Their result contains the unchanged legacy `control` plus actual callback `change_count`, zero or one. A missing callback ignores user and reduces normally. ```c static void changed(void *user, const cui_otp_change_event *event) { size_t *accepted = user; /* Separate application state. */ *accepted += event->accepted_count; } /* Within the normal active frame: */ /* cui_otp_events(ui, id, theme, &state, options, * (cui_otp_event_handler){changed, &accepted_operations}); */ ``` CHANGE means accepted operations in this submission, including empty Backspace and changes that return to the entry text. It does not mean final text inequality. The payload snapshots entry/final UTF-8 byte and code-point counts, target cell length, accepted-operation and completion counts, and final completeness. `completion_count` is the old per-operation length-match count: it can exceed one, include deletion from overlength to target or empty Backspace at target zero, and coexist with a finally incomplete value. No SUBMIT, verification, validity, per-event completion callback or input-origin claim is added. Enter is unchanged. Programmatic setters alone do not cause these notifications. Observers run after the single real Base reduction and final semantics, before Styled paint. Earlier accepted changes still notify if later operations report capacity/session errors; the original error remains in `control`. Disabled, inert and layout-only calls retain old bookkeeping/reduction without notifying. Metadata is CHANGE at the root ID, UNKNOWN source, with only HAS_FRAME for the active completion frame. Counts do not establish an event index or activation. Text is final committed model bytes, borrowed only through the callback when `has_text=true`. Masked state sets `has_text=false` and empty `text`, and never exposes preedit. Scalar length information is retained; masking is not encryption or length secrecy. Do not log codes/preedit or automatically persist/forward them. Copying the event struct does not retain its text. To retain unmasked text, call `cui_component_event_copy_utf8` inside the callback into caller-owned storage, with an explicit maximum and capacity including NUL; check its status. Copy failure does not reject the edit. No silent truncation or allocation is added. The target is capped at 256 cells, but programmatic UTF-8 text can be arbitrarily long within the supplied buffer; there is no implied 256-byte text bound. Handler/user are borrowed only for this call; no registration/replay occurs. Do not mutate/rebind/destroy the model, state, composition/session, context or borrowed buffers; recursively submit; or unwind foreign exceptions during the callback. Changing unrelated application state or setting a deferred-work flag is allowed. Defer model changes, removal and teardown until outer submission and renderer consumption complete: drawing may borrow model/preedit bytes. Tests use actual queued text, keys and composition events, with paired legacy/new semantics, focus, text-input rectangles, draw commands and consumption checks. They cover accepted no-ops, net-zero changes, target zero, overlength deletion, multiple completions/final incomplete text, stale duplicate commit, redaction, explicit copies, passive/disabled behavior, bounded invalid buffers, and accepted progress followed by errors. Native execution uses the private-display wrapper. The old APIs, bridge LEGACY notifications and Python/Node/Go/Rust wrappers remain unchanged; this slice adds no typed binding completion transport. --- ## Install local alpha binding artifacts Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PACKAGING.md # Install local alpha binding artifacts Current artifact examples use prepared alpha.2 versions (`0.1.0-alpha.3`, Python `0.1.0a3`). Metadata preparation is not publication or a final source freeze; see [RELEASING.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/RELEASING.md). Existing alpha.1 tags/assets stay immutable. The packages expose the [tested binding subset](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_COMPONENTS.md), not full upstream feature parity. Commands below build and consume local files; no registry publication or public Go tag is assumed. npm is `private: true` and Cargo has `publish = false`. Linux x86_64 is validated; registry ownership, public release versions, other platforms and native runtime bundling remain release work. Run artifact build commands from the CUI repository root. The artifact producer scripts require Python 3, CMake 3.20+, a C11 compiler and build tools. Node builds also require Node >=18 and Node-API headers; Go requires Go 1.23+ with cgo, and Rust requires Cargo/Rust. Builds default to Release with strict warnings. Use `CUI_PACKAGE_BUILD_TYPE=Debug` explicitly for diagnostic builds. **Portable is the default:** an App computes layout and processes input but opens no window. Build with `CUI_PACKAGE_NATIVE=1`, then select the SDL backend in the application for a native window. Keep portable and native artifacts in separate output directories; their versions and filenames currently coincide. Native builds need SDL3 >=3.2, FreeType and HarfBuzz development packages. ## Python: wheel, virtualenv and native counter ```sh CUI_PACKAGE_NATIVE=1 python scripts/package_bindings.py python --output /tmp/cui-python-native python -m venv /tmp/cui-python-consumer /tmp/cui-python-consumer/bin/python -m pip install --no-deps /tmp/cui-python-native/*.whl ``` Save this as `/tmp/cui-python-consumer/counter.py`. It creates a real native UI; the callback updates mounted label state. Closing the window ends `app.run()`. ```python import os from cui_bridge import App, button, column, label count = 0 status = label("Clicks: 0") def increment(event): global count count += 1 status.label(f"Clicks: {count}") click = button("increment").label("Click me").on_click(increment) with App(backend="sdl", title="CUI Counter", font_path=os.environ["CUI_FONT"]) as app: app.mount(column().children(status, click)) if os.environ.get("CUI_EXAMPLE_SMOKE") == "1": app.step() x, y, w, h = app.bounds(click) app.queue_pointer("down", x + w / 2, y + h / 2) app.queue_pointer("up", x + w / 2, y + h / 2) app.step() app.dispatch() assert count == 1 app.step() else: app.run() ``` Choose an existing font covering your application's text, then run: ```sh CUI_FONT=/path/to/font.ttf /tmp/cui-python-consumer/bin/python /tmp/cui-python-consumer/counter.py ``` For portable layout/input only, omit `CUI_PACKAGE_NATIVE=1` when building and use `App()` instead of the SDL options. The platform wheel includes its compiled bridge, source roots, pinned dependency manifest and licenses. It is not a pure Python wheel or a manylinux claim. No checkout/PYTHONPATH or separate library path is needed. Explicit `library=` and `CUI_BRIDGE_LIBRARY` overrides retain precedence; a broken override fails rather than hiding the error with a default library. ## JavaScript: prebuilt tarball and native counter ```sh CUI_PACKAGE_NATIVE=1 python scripts/package_bindings.py node --prebuilt --output /tmp/cui-node-native mkdir -p /tmp/cui-node-consumer cd /tmp/cui-node-consumer npm init -y CUI_PACKAGE_NATIVE=1 npm install /tmp/cui-node-native/cui-native-0.1.0-alpha.3.tgz ``` Save this as `/tmp/cui-node-consumer/counter.cjs`: ```javascript const {App, button, column, label} = require('@cui/native'); let count = 0; const status = label('Clicks: 0'); const click = button('increment').label('Click me').on_click(() => { status.label(`Clicks: ${++count}`); }); const app = new App({backend: 'sdl', title: 'CUI Counter', fontPath: process.env.CUI_FONT}); app.mount(column().children(status, click)); if (process.env.CUI_EXAMPLE_SMOKE === '1') { app.step(); const {x, y, width, height} = click.bounds(); app.pointer('down', x + width / 2, y + height / 2); app.pointer('up', x + width / 2, y + height / 2); app.step(); if (count !== 1) throw new Error('counter callback failed'); app.step(); app.dispose(); } else { app.start(); } ``` ```sh CUI_FONT=/path/to/font.ttf node /tmp/cui-node-consumer/counter.cjs ``` For portable behavior build without `CUI_PACKAGE_NATIVE=1` and use `new App()`. `--prebuilt` carries a hashed Node-API 8 addon and bridge; the consumer needs Node >=18 and system runtime libraries, without Python or a C compiler. Omit `--prebuilt` for a source tarball whose install hook requires Python 3, CMake, a C11 compiler, build tools and Node headers. Install scripts must be enabled. `CUI_PACKAGE_BUILD_FROM_SOURCE=1` explicitly rebuilds bundled source. TypeScript declarations are inside the package and validated using strict TypeScript 5.8.3. `CUI_NODE_ADDON` remains an explicit override; missing installed binaries fail without a checkout fallback. ## Go: local module proxy and executable Build a portable artifact at the repository root: ```sh python scripts/package_bindings.py go --output /tmp/cui-go-artifacts mkdir -p /tmp/cui-go-consumer cp tests/packaging/go_smoke.go /tmp/cui-go-consumer/main.go cd /tmp/cui-go-consumer go mod init example.local/cui-counter go mod edit -require=github.com/mattmezza/cui/bindings/go@v0.1.0-alpha.3 GOPROXY=file:///tmp/cui-go-artifacts GOSUMDB=off go mod tidy GOPROXY=file:///tmp/cui-go-artifacts GOSUMDB=off go build -o counter . ./counter ``` This example renders a portable frame, sends a click and asserts the callback. The canonical module path describes this repository; these commands use a local proxy ZIP, not an unpublished registry/tag. The default artifact includes a tracked source SDK and separate C translation units. cgo compiles and statically links CUI at `go build`; the executable needs no checkout, CMake, compiler or extracted CUI library cache at runtime. Native system libraries remain required. To validate native rendering, build the consumer with `go build -tags cui_native`. This build requires SDL3 >=3.2, FreeType and HarfBuzz development packages through pkg-config. Run the smoke example with `CUI_PACKAGE_SMOKE_BACKEND=sdl CUI_PACKAGE_SMOKE_FONT=/path/to/font.ttf`. For an interactive application, see the [Go workspace UI](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/GO_BUILDERS.md). The portable default opens no window and reports a clear error if native options are requested without the native build tag. `--source-only` remains an alias for the default source module. For optional embedded shared-library packaging, use `--prebuilt` and build the consumer with `-tags cui_dynamic`. That mode extracts its hashed bridge into a locked, atomic private cache, validating SDK/backend/ABI/OS/architecture receipts. Dynamic source fallback exists only under this explicit tag; it may require a runtime compiler if the artifact has no prebuilt library. Explicit `Library` and `CUI_BRIDGE_LIBRARY` overrides retain precedence in both modes. A process keeps one selected bridge, so switching between static and dynamic paths requires a new process. Go resolves this public repository directly; it needs no Go registry account. A repository commit or `@main` becomes fetchable when those files are published. The versioned `v0.1.0-alpha.3` tag used above remains a local artifact version; no command here assumes that public tag has been created. ## Rust: local crate and statically linked executable At the repository root: ```sh python scripts/package_bindings.py rust --output /tmp/cui-rust-artifacts mkdir -p /tmp/cui-rust-consumer/vendor cp tests/packaging/rust_smoke.rs /tmp/cui-rust-main.rs tar -xzf /tmp/cui-rust-artifacts/cui-builders-0.1.0-alpha.3.crate -C /tmp/cui-rust-consumer/vendor cd /tmp/cui-rust-consumer cargo init --name cui-counter cp /tmp/cui-rust-main.rs src/main.rs cat >> Cargo.toml <<'TOML' cui-builders = { path = "vendor/cui-builders-0.1.0-alpha.3" } TOML cargo build --offline ./target/debug/cui-counter ``` Cargo compiles the bundled SDK and statically links CUI during the developer build. The copied executable needs no CUI checkout, CMake or compiler at runtime. The example asserts portable geometry and a callback. For native rendering, add `features = ["native"]` to the dependency entry, then run it with `CUI_PACKAGE_SMOKE_BACKEND=sdl CUI_PACKAGE_SMOKE_FONT=/path/to/font.ttf`. Native system libraries are still dynamically required. The existing `CUI_BRIDGE_LIB_DIR` shared-library override remains available. See the [Rust workspace UI](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/RUST_BUILDERS.md) for a complete interactive application. ## Headless checks and runtime requirements Automated native checks must use a dedicated invisible Xvfb session, never the maintainer desktop. These runners create it automatically: ```sh python scripts/test_binding_packages.py --artifacts /tmp/cui-native-artifacts --native --require-prebuilt --font /path/to/font.ttf python scripts/test_compiled_binding_packages.py --go-artifacts /tmp/cui-go-native --rust-artifacts /tmp/cui-rust-artifacts --native --font /path/to/font.ttf ``` The first directory must contain both the native wheel and prebuilt npm tarball; build both there using the earlier commands. The Go directory must contain a native Go artifact. Rust's consumer selects its native feature. For the standalone counter examples, `CUI_EXAMPLE_SMOKE=1` sends and checks a synthetic click and exits; wrap their invocation in `xvfb-run -a env -u WAYLAND_DISPLAY`. The installed artifact tests use clean temporary consumers without checkout or library-path overrides, exercise real frames/callbacks, and block compiler tools at runtime. Python native validation also checks captured Button pixels. The text smoke includes `✓`; fonts must cover submitted text. This host validates `/usr/share/fonts/Adwaita/AdwaitaMono-Regular.ttf`; plain NotoSans lacks that glyph here. Missing glyph errors remain visible. Full workspace examples and supported options are in [Python/JavaScript/TypeScript builders](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BINDING_BUILDERS.md), [Go builders](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/GO_BUILDERS.md), and [Rust builders](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/RUST_BUILDERS.md). SDL builds require system SDL3 >=3.2, FreeType, HarfBuzz and their development headers/pkg-config metadata. These system libraries are **not bundled or pinned** by this alpha packaging. Their transitive runtime libraries and an explicit font must exist on the target host. Therefore SDL artifacts are source-complete but are not self-contained native runtime distributions. `_native/build-info.json` (Python) and `native/build-info.json` (npm) record the actual built shared-library runtime dependency names, development versions and source revision. Source file hashes are recorded in `SOURCE_FILES.sha256`, alongside the pinned third-party manifest and license texts. Portable builds need the host's standard C/math runtime; native builds add the precise dependencies in that file. Linux x86_64 is locally validated. macOS/Windows, manylinux repair, dependency runtime bundling, cross compilation and registry publication remain unvalidated. C/CMake warnings stay enabled and errors remain fatal. Artifact builders default to Release; `CUI_PACKAGE_BUILD_TYPE=Debug` explicitly selects a diagnostic build. Vendored source versions/licenses remain in `third_party/dependencies.json`. The configured SDL fetch pin remains in the bundled source, but packaging does not enable network fetching or silently replace system development dependencies. ## Source receipts and release work Artifacts include tracked source only, file hashes, pinned dependency manifests and license texts. The npm source snapshot intentionally omits `.gitignore` files before hashing because `npm pack` excludes them; these files do not participate in consumer builds. Python retains these canonical tracked files. The installed package validator verifies every source manifest hash against actual archive contents and rejects missing, changed, unlisted or unsafe source entries before installation. The source file inventory excludes its own `SOURCE_FILES.sha256` and `bindings/go/sdk/source/SOURCE_FILES.sha256` and `bindings/rust/sdk/source/SOURCE_FILES.sha256` from recursive hashing, matching the producer; all other archived source files must be listed. Use `python scripts/test_binding_packages.py --artifacts DIR --verify-only` to run only these offline archive checks, without installing packages, building code or opening a display. Revision receipts include dirty-source information so a revision is not mistaken for an exact clean snapshot. Go and Rust use minimal SDK snapshots: after canonical changes run `python scripts/generate_go_sdk.py`, then `python scripts/generate_go_sdk.py --check` to validate freshness/provenance. No packaging command publishes. Public tag/registry release, Linux runtime bundling, manylinux compatibility and cross-platform binaries are pending. Authoritative packaging references: [Python packaging flow](https://packaging.python.org/en/latest/flow/), [npm pack](https://docs.npmjs.com/cli/v12/commands/npm-pack/), [npm lifecycle scripts](https://docs.npmjs.com/misc/scripts/), [Cargo native build scripts](https://doc.rust-lang.org/cargo/reference/build-scripts.html), [Go module ZIP rules](https://go.dev/ref/mod#zip-files), and [Go embedded files](https://pkg.go.dev/embed). --- ## Password engine prerequisite, Stage 1 Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PASSWORD_ENGINE_STAGE1.md # Password engine prerequisite, Stage 1 This batch adds pure U+2022 scalar masking/offset helpers and hard presentation preparation to `cui_edit_apply_checked`. It supplies no password Input widget, secure semantics, clipboard policy, browser/native secure bridge or reveal UI. Those remain coordinated Stage 2 work. The source mask character/scalar behavior comes from upstream kit `87d10ae5e1299d1be18670a37570c5402f952e34`, [masked display](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/crates/base/src/input/base/element.rs#L2548). `cui_edit_mask_text` emits three UTF-8 bytes per Unicode scalar, including combining marks and each scalar of a ZWJ/flag sequence. It is not grapheme counting. Capacity includes NUL; whole-source UTF8, checked scalar multiplication and known source/destination/output aliases precede writes. Failure preserves destination and output. Mask/unmask offset helpers require original scalar boundaries or three-byte bullet boundaries; outputs are atomic and disjoint from the source. Storage remains caller-owned, and helper outputs borrow caller bytes. Ordinary edit movement/grapheme rules are unchanged by these pure mappings. A checked request may provide `cui_edit_presentation`: synchronous `prepare`, user pointer/exact byte extent, optional descriptor extent and zero to three exact caller workspaces. All declared spans must be accurately sized, disjoint from each other/model/session/original request payload. Unused array entries are zero; non-NULL user requires nonzero extent. Invalid configuration is rejected before callback. Allocated/private callback resources are caller-owned too, but need no span declaration when freshly allocated disjoint storage; they must never alias model storage. Direct caller-buffer mutation, undeclared aliases, retained candidate pointers, external side effects and cross-thread access violate the borrowing contract and cannot be globally protected in C. Preparation receives complete real candidate text (after opt-in normalization), not bullets. It returns only OK, CAPACITY or appended PRESENTATION; other codes become INVALID_ARGUMENT. Use CAPACITY for allocator/fixed-budget failure and PRESENTATION for an installed geometry factory failing to create a representation. No factory or frontend allocator is called by the engine itself. The callback is responsible for cleaning partial resources before returning a failure. Same-model mutators/void destroy/cache-writing getters are guarded; attempted mutation causes INVALID_ARGUMENT and preserves logical state. Pure getters remain available. The gate runs before acceptance predicates and model mutation. Resource failure is `rejected=false` and does not invoke acceptance or invalid-old healing. Successful preparation is followed by the original candidate predicate, and by the previous-value predicate only when candidate fails. Empty acceptance bypass remains; hard preparation still applies to an actual edit resulting in empty text. An unchanged no-op range has no candidate/stage. No callback replay occurs during commit. Zero presentation preserves the legacy path; hard presentation currently rejects multiline models explicitly, while ordinary multiline APIs stay unchanged. Replacement prepares its normalized full candidate before cursor/history/document writes. IME UPDATE prepares the full prospective composed value, and COMMIT prepares once before document commit, with original UTF8 endpoint validation and normalization mapping unchanged. Failed preparation restores reused prior view bytes and frees only unbound engine grow storage. Preedit/document/session remain unchanged. With NULL preparation, START retains its legacy bypass. With opt-in preparation, START now stages the exact prefix/suffix view around an empty preedit before mutating the session. Failed preparation preserves the prior session and selection. CANCEL publishes the retained committed view without another allocation. The styled Input lifecycle is described in [Password Input](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PASSWORD_INPUT_STAGE2.md). Undo/Redo prepare the target recorded full value before saving history state or changing index/selection. They bypass acceptance/normalization as before. A hard budget may block replay with CAPACITY without discarding its history entry. Returned `presentation_prepared` means prepare returned OK, even if a later predicate/reentry failure rejected the operation. `presentation_applied` means the checked operation adopted that candidate. Consume/publish or discard caller staging before another request. No completion callback runs inside the engine; publication, cache release and other frontend effects lie outside engine rollback. All borrowed presentation fields are removed/restored when the checked call returns. Do not promise unchanged external callback state or entire-allocation identity: rollback preserves logical document/history/selection/coalescing/session ownership and prior view defined bytes/NUL, while internal scratch and unused tails are unspecified. `tests/unit/test_password_engine.c` covers independently enumerated scalar maps, alias/capacity/output rollback, prepare→predicate ordering and invalid-old healing, normalized candidate, unsupported callback codes, same-model destroy, fixed-budget and injected preparation/allocator failures, exact replay/IME prepare counts, typing grouping across failure, prior fixed/growing view ownership, three declared workspaces/descriptor, and a rejected 4500-byte preedit requiring staged grow allocation. Factory-failure coverage is a callback spy returning PRESENTATION, not an actual native font/backend password validation. Frontend forced-factory lifetime/pixel/secure-host tests remain Stage 2 requirements. Integrator registers `test_password_engine` linked only to `cui`, including WASI, and regenerates distribution. No global build files or generated headers were modified by this worker. --- ## Single-line masked Input Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PASSWORD_INPUT_STAGE2.md # Single-line masked Input This implements the pinned `87d10ae5e1299d1be18670a37570c5402f952e34` Input password slice, together with the checked engine Stage 1. It does not complete Input parity: regex, mask formatting, and other content types remain separate. Multiline masking/password purpose and inline token content are explicitly unsupported; invalid options return INVALID_ARGUMENT before reduction. Ordinary multiline Input/Editor/Textarea host input remains available. ```c cui_input_options options = { .masked = true, .content_type = CUI_TEXT_INPUT_PURPOSE_PASSWORD, .normalization = CUI_EDIT_NORMALIZE_SINGLE_LINE_CRLF, }; cui_input_result result = cui_input_ex(ui, id, theme, label, edit, state, options); ``` Zero options preserve ordinary Input behavior. Masking and purpose are independent: masked alone paints bullets and denies Copy/Cut, but keeps the Textbox accessibility role. PASSWORD/NEW_PASSWORD purpose marks protected accessibility state even when revealed. Reveal (`masked=false`) deliberately paints the actual value and allows the established clipboard callback. Masked Copy/Cut are denied before calling that callback; Paste still follows editability, normalization and acceptance. Word motion/selection/delete uses whole-value endpoints while masked; double/triple click selects all. Scalar/grapheme movement retains the existing engine policy. The mask is one U+2022 per Unicode scalar, including combining marks, matching the source. Selection, caret, pointer hit testing, horizontal scroll and IME underlines map original UTF8 byte endpoints to/from three-byte bullet endpoints. The geometry factory and text draw commands receive only bullet text in masked mode. Entering masked mode releases previous plaintext geometry sessions and their text copies. Painting failures never fall back to plaintext. Public placeholder/label strings remain the application's responsibility; never put a secret in either. ## Hard resource staging The styled control retains three display/geometry slots: safe committed value, current visible preedit, and unused candidate stage. Its initial/current seed is prepared with CUI_EDIT_REQUEST_PRESENT before reducing events. For replacement, normalized IME UPDATE/COMMIT, Cut/delete and Undo/Redo, the engine prepares the prospective whole value before document/history/selection writes and before the acceptance predicate. Preparation failure invokes no predicate and leaves logical model/session state unchanged. Acceptance rejection discards the prepared stage; it does not publish it or replay the predicate. Empty values still require a safe empty presentation. Undo/Redo prepares its historical target without predicate or normalization replay. Default slots lazily grow to actual mask bytes plus NUL, bounded by the model's caller-chosen document capacity. Three display slots, geometry copies and host sessions remain owned by the UI resource. Idle frames reuse them. After changing a font registry or measurement policy, call `cui_text_metrics_changed(ui)` outside the frame to invalidate retained geometry; ordinary control size changes also trigger preparation. An optional `cui_input_mask_allocator` controls display-buffer allocation only; geometry text copies and factory sessions keep their existing ownership. Both callbacks must be present or absent; successful allocation must return fresh disjoint storage. Its user/callbacks must remain alive until context destruction/resource collection. For allocation-free display storage, supply `cui_input_mask_storage` with three disjoint buffers and their capacities including NUL. The smallest capacity is the hard per-candidate budget. Buffers and their descriptor remain caller-owned and must stay unchanged/alive through resource release. Accurate descriptor/workspace extents are declared to the checked engine; known model/session/payload/workspace aliases reject before preparation. Rebinding these resources drops their previous owned sessions. Cancel composition and reset the Input state before destroying/replacing its model; the reset state forces initial resource preparation even if an allocator reuses the same model address. Reset the host proxy when replacing its bound model; a retained session's numeric model binding must never be reused across model lifetimes. IME retains the existing one-primary-selection constraint; no multi-cursor IME support is claimed. Retained resource callbacks never dereference a destroyed model. If the optional visual factory exists, it must successfully prepare immutable bullet geometry; failure returns PRESENTATION before committing the edit. Without one, measured bullet geometry is the legacy fallback. Factory limits remain host limits. There is no secret-safe rollback promise for direct application writes to model buffers or raw engine edits outside this checked control. Completion is caller-owned and outside engine rollback. Base exposes presentation/prepared/applied completion so a custom frontend can implement the same three-slot publication; Base alone does not paint a mask for it. Engine PRESENT is nonmutating and ignores editability. NULL/inactive composition prepares committed text; an inactive previously-bound session must belong to this model. Active composition must have a valid materialized composed view, matching model revision/selection/binding and disjoint buffers; stale views reject before callbacks. No predicate, normalization, session start/cancel, history or selection mutation occurs. Successful preparation reports prepared/applied=true even though the logical value stays unchanged. Known same-model mutation during preparation fails the outer request. Caller buffer writes and unrelated callback side effects remain outside that guard. With a hard presentation callback, START prepares its prospective empty-preedit view (the current selected range is replaced by empty text) before mutating the session or coalescing state. It invokes no acceptance/normalization and requires an empty START payload. Null presentation preserves the old START bypass exactly. Failure preserves the prior session and safe committed view; success publishes matching prefix/suffix bullets immediately. CANCEL needs no allocation because the committed slot remains intact. UPDATE rejection preserves prior visible preedit. A rejected or resource-failed host COMMIT first preserves engine logical state, then Base cancels the session because the host IME has ended. Mode/purpose changes, readonly/disabled and focus loss cancel composition. Following typing/shortcuts remain available. Ordinary zero configuration is unchanged. ## Finalized host configuration Core owns portable type/purpose enums, `cui_set_text_input_config` and `cui_get_text_input_config`. Register against an already-submitted textbox during the frame. The getter is available only after end_frame and validates the actual eligible focused owner, current modal scope, readonly/disabled and no-focus state. Failure leaves output unchanged. It borrows no strings/models/platform pointers. Missing explicit registration yields ordinary TEXT/UNSPECIFIED for eligible textboxes, including existing Editor/Textarea/Numeric/OTP and text children. Finalized `multiline` selects ordinary textarea behavior. Explicit secure types or purposes reject multiline atomically. Generation changes on owner/config/explicit versus implicit/multiline/removal transitions; UINT64_MAX exhaustion fails closed until context recreation. Host reset must discard old proxy/preedit when it changes. An application replacing its Core context must explicitly reset/dispose the bridge. SDL poll consumes the finalized state, stops input for absent/ineligible focus and restarts on generation changes, cancelling the old tracked IME session and dropping text/editing events already queued for that superseded host configuration. It uses SDL_StartTextInputWithProperties, TEXT_PASSWORD_HIDDEN/VISIBLE and disabled AUTOCORRECT for secure purposes, plus MULTILINE for ordinary multiline text. These are verified against repository SDL pin [`7f3ae3d57459e59943a4ecfefc8f6277ec6bf540` keyboard header](https://github.com/libsdl-org/SDL/blob/7f3ae3d57459e59943a4ecfefc8f6277ec6bf540/include/SDL3/SDL_keyboard.h). They exist since SDL3.2; SDL explicitly does not promise every input type on every platform. NEW_PASSWORD cannot be distinguished from PASSWORD through this SDL keyboard type. Physical OS keyboard suggestions/IME privacy are not proven by injected events or Xvfb. SDL's global queue is not a per-window multicast service. The optional AccessKit bridge maps password purpose to PASSWORD_INPUT and observes secret/protected changes. It remains phase 1: no editable text/value support or full screen-reader claim. CUI semantic value is zero for secret Inputs. ## Browser module and proof `web/secure_input.js` is a reusable ES module. Pass parent, UTF8 `text`, `composition(kind, bytes, anchorByte, cursorByte, owner)`, `key(event,owner)`, `focusLost(owner)` and `changed()` callbacks. Call `sync` after finalized Core frames with `{owner,type,purpose,generation,multiline,label}` and logical caret rectangle. Use opaque stable owner/generation values without lossy conversions. The module never seeds the committed value into DOM. Hidden passwords use a password input, revealed passwords use text input, and ordinary multiline uses textarea. Purpose selects current-password/new-password autocomplete. It disables spelling/correction, converts DOM UTF16 scalar endpoints to UTF8, suppresses the composition-end duplicate input, and clears transient value/preedit on blur, generation rebind/reset/dispose. Composing shortcuts yield to the browser IME. Native DOM selection represents the range the browser exposes; no claim of every platform's internal IME clause range. The module provides no async clipboard implementation or cross-platform virtual keyboard guarantee. The website Input preview exposes hidden, revealed, and new-password modes through this bridge. Its finalized owner and generation preserve all 64 bits across the WASM host boundary. The standalone fixture uses actual CUI Core/styled Input compiled to WASM, with real Chromium CDP imeSetComposition/insertText and actual canvas font measurement and painting of Core draw commands. It checks identical pixels for distinct equal-scalar-count passwords, selected Unicode START prefix/suffix, bullet draws, unchanged preedit document, exactly-once commit/Undo, fixed-capacity host rejection followed by ordinary typing, cancel, reveal/purpose, readonly, blur, and generation-switched input/textarea. Run: ```sh uv run tests/web/test_secure_input.py --output build/secure-proof --chromium /path/to/chrome ``` Headless tests: test_password_present, test_password_start, test_password_input, test_secure_focus, test_secure_focus_generation and optional test_password_accessibility. Native font proof: test_password_native (actual NotoSans bullets, plaintext cache teardown, factory failure before writes); SDL proof: test_password_sdl3 (real SDL property calls and queued Unicode editing/commit, Xvfb). These tests are registered in CMake; portable tests also run under WASI. Generated distribution headers include these APIs. --- ## Measured performance Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PERFORMANCE.md # Measured performance Development host: Intel Core Ultra 5 235U (14 logical CPUs), Arch Linux x86_64 kernel7.2.8, GCC16.2.1, default unoptimized CMake build. `./build/cui_bench`:500 frames composing100 boxes+text at800×600, Clay culls outside viewport;28000 visible draw commands total. CPU `clock()` measurement:98.079ms total /0.196ms per composed frame in the initial run. This is CPU layout/draw-list generation, not end-to-end GPU frame time, and excludes renderer/text shaping and OS scheduling. Reproduce with `make bench`; numbers are not a comparison to other frameworks. SDL_Renderer has bounded persistent glyph textures (256 LRU entries,4MiB coverage budget), text tint reuse tested. SDL_GPU has a1024×1024 grayscale atlas with4096 cached masks and32768 per-frame quad entries; uploads only after newly cached glyph masks. Atlas exhaustion returns failure instead of claiming successful output. GPU batching/regression thresholds and workload-specific measurement remain pending. ## Hosted check scheduling Portable CI runs at most two CTest processes at once and sets `CMAKE_BUILD_PARALLEL_LEVEL=2` for nested consumer builds. Each test uses its own process and temporary consumer directories; reference fixtures remain read-only. Native CI and local test scheduling are unchanged. On Linux, continue using `python scripts/test_local.py --build-dir build`, which isolates the display. The baseline Windows Debug job in [run 41249695765](https://github.com/mattmezza/cui/actions/runs/41249695765) spent 165.88 seconds on `agent_skill_contract` and 98.43 seconds on `binding_package_source_manifest`. Bounded overlap targets this serial cost; these timings are a baseline, not measured savings from the scheduling change. Hosted duration, memory use and any contention regressions still need comparison. ## Generated output timestamps The SDK, amalgamation and agent-skill generators compare generated bytes with existing files before writing. Identical generation preserves file modification times, avoiding timestamp-only invalidation of C/C++ consumers, Go wrapper translation units and bundled SDK sources. This is not a build cache: generation and freshness checks still compute their outputs, and changed/missing files are written normally. SDK provenance is still recalculated; a changed revision or source-diff receipt changes its bytes and therefore its timestamp. Previously, all SDK wrappers/sources and all distribution headers were rewritten even when identical. Running the canonical sequence after a documentation-only change could therefore mark both native header consumers and foreign SDK consumers dirty independently. Skill resources were also always rewritten, although that alone does not establish a native compile dependency. No rebuild count or elapsed-time saving is claimed without a measured build comparison. Run the small offline entrypoint regression with `python tests/test_generator_writes.py`. It uses temporary mini-repositories and checks fixed nanosecond timestamps, output repair, changed input, read-only `--check` failures and existing stale-file policy. It performs no compilation, dependency installation or canonical generation. SDK obsolete files/wrappers still require explicit review; amalgamation still leaves unrelated files alone. Use the normal SDK → amalgamation → skill sequence and freshness checks when updating actual generated resources. --- ## Picker applied observers Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PICKER_EVENTS.md # Picker applied observers Include `cui/cui_picker_events.h` for additive applied date-selection observers: `cui_calendar_reduce_events`, `cui_base_calendar_events`, and `cui_calendar_events`. Each mirrors its legacy operation, appends `cui_date_selection_handler`, and returns `cui_calendar_event_result` with the exact legacy `control` and `change_count`. ```c static void selected_date(void *user, const cui_date_selection_change *event) { app_state *app = user; app->last_selection = event->value; /* Pointer-free copy. */ } cui_calendar_event_result result = cui_calendar_events( ui, calendar_id, &theme, &calendar, &selection, options, (cui_date_selection_handler){selected_date, app}); ``` This slice does not add TimeField, navigation, popup lifecycle or controlled-request observers. A CHANGE reports an already-applied date selection and cannot reject it. The existing disabled-date predicate remains an enablement policy, not a notification or a newly rejectable transaction. ## Delivery and comparison Each facade invokes its corresponding legacy operation **once** and compares selected start/end at the outer return. Reduce-only does not submit semantics; Base does; Styled completes painting before the observer. No nested observer or reduction replay occurs. Custom popup hosts may use reduce-only and submit later, preserving their own modal/close ordering. There is no submit-only observer. At most one callback runs per operation. Multiple changes coalesce, and returning to the initial selection produces no CHANGE. `change_count` counts actual callback invocations; a missing handler still permits editing and yields zero count. Its unused user pointer is ignored. Reading `control` never dispatches again. Comparison uses `cui_date_compare` for each endpoint, exactly as the legacy Calendar change calculation does. It compares date fields rather than struct bytes or formatted strings. Zero/end-unset dates remain part of the legacy selection representation; the facade adds no validity check, selection normalization or range ownership rule. Range first selection starts/restarts the range, and range completion can reorder endpoints. Same-date activation can set `control.activated` without a CHANGE. Displayed month, cursor movement, DAYS/YEARS/MONTHS chooser state, year page and range-in-progress are distinct presentation state. Navigation may set the legacy `navigated` flag without changing selected dates. Repairing invalid month/cursor presentation also does not produce selection CHANGE. External assignments completed before entry are not component-applied changes. The copied payload contains previous/final `cui_date_selection`, CHANGE kind and the calendar ID. Metadata is UNKNOWN source, HAS_FRAME with the actual nonzero active frame, no event index, activation, cause or host timestamp. Aggregate flags are not evidence from which these missing facts can be reconstructed. ## Passive work and resource ownership Required context/state/selection pointers, Styled theme and nonzero ID are checked before calling legacy code; failed admission has no maintenance, callbacks or state writes. Otherwise existing passive maintenance remains intact. Notifications are suppressed outside active painted submission, under layout-only ancestry or when Calendar is disabled. Inert/modal routing is still Core's existing behavior; this API adds no routing or propagation policy and does not claim every reducer branch uniformly checks input consumption. Observer/user are borrowed through the call. Keep selection, state, theme, locale strings, options and disabled-policy userdata alive and unchanged. Existing policy calls can occur repeatedly during scanning and painting; there is no one-call-per- action guarantee. The facade does not copy/retain policy userdata. Observers must not mutate, free or rebind active resources, destroy context, or recursively submit UI. They may set unrelated flags; apply omission/removal after outer return and defer teardown through frame/renderer consumption. Payload fields themselves are pointer-free and remain safe when copied after later frames or context destruction. `tests/unit/test_picker_events.c` compares old/new selections, state, policy call counts, focus, legacy result, semantics and draw commands for all three entrypoints. It covers multiple/net-zero changes, same-date activation, keyboard navigation, reversed range completion, year/month chooser silence, disabled-day bounds/policy, passive presentation repair, disabled/inert/layout-only silence, missing observer, copy lifetime, deferred omission and atomic pointer/ID admission. Callback-time checks distinguish reduce-only semantics from Base/Styled completion. Legacy `picker` and `picker_base_only` suites remain required. Tests use the private native display wrapper. No browser, host accessibility or foreign binding proof is implied. ## DatePicker selected dates The same header provides `cui_base_date_picker_events` and `cui_date_picker_events`, mirroring the old arguments plus date handler. Base returns `cui_calendar_event_result`; Styled returns `cui_picker_event_result` with its exact old bool in `changed` and zero/one actual `change_count`. Base requires both trigger and calendar IDs nonzero; Styled requires its trigger ID and theme. Required pointers/IDs are checked atomically before legacy code. Each wraps the complete original operation once, with no nested Calendar observer. The event target is the **outer trigger ID**, even though Base also takes a separate calendar ID. The observer runs after all original popup dismissal, focus restoration, trigger formatting, layout and paint work (or the original early return). Opening, closing, navigating and activating the same selected date do not alone notify. A first range selection may notify while the popup stays open; completing a range can notify after it closes. Only selected start/end date comparisons decide CHANGE. A late Styled failure can return false even after Base has changed dates: for example, first range selection followed by invalid popup viewport placement. The facade preserves that bool and still delivers the applied date CHANGE after close/focus restoration. Do not treat `changed` as a callback count or successful render signal, and do not gate applied notification on that bool. There is no invented error or close reason in the payload. Global disabled or Calendar-disabled options suppress observers while keeping old trigger/overlay maintenance. Active painted/frame, UNKNOWN/no-index evidence, missing-handler editing, copied payload, borrowed policy/locale data and deferred teardown rules match Calendar above. DatePicker overlay state retains its existing lifetime and the standalone trigger has no date observer API. DatePicker tests pair legacy/facade results, state, focus, locale/policy calls, semantics and draw commands. They cover Italian locale labels, same-date close, range completion, invalid viewport after mutation, close/focus at callback time, null handler, multiple Base inputs with one callback, passive/disabled/inert/layout silence, payload copying after destruction, deferred omission and atomic calendar-ID admission. These remain native source proofs, not foreign or browser coverage. ## ColorPicker applied RGBA `cui_base_color_picker_events` and `cui_color_picker_events` mirror the respective legacy signatures and append `cui_color_handler`. Each returns `cui_picker_event_result`, preserving the exact legacy bool in `changed` and counting zero/one actual callbacks. The typed `cui_color_change` contains metadata and previous/final `cui_color` RGBA bytes. All fields are pointer-free and copyable. Each whole legacy operation runs once, including final HSV/drag/last_color state, semantics and (Styled) painting, before notification. Comparison explicitly checks r/g/b/a fields; it does not compare padding, formatted text or HSV. Several changes coalesce and net-zero RGBA means no callback. A latent hue change while black or achromatic need not change RGBA and is not an applied color event. External color assignment before entry resynchronizes HSV without a component CHANGE. A palette selection preserves the old alpha when alpha editing is off; the payload reports that actual final RGBA, not the palette entry's unused alpha. Missing handler does not inhibit edits. The unused user pointer is ignored. Required context/state/color pointers, nonzero ID and Styled theme are checked before legacy code. All other legacy validation remains unchanged. Delivery requires active painted submission, a proven nonzero frame, enabled and non-readonly options. Passive maintenance still runs, including HSV synchronization and readonly/disabled drag cleanup. Metadata has CHANGE and outer picker ID, UNKNOWN source, HAS_FRAME only, no index/activation/cause. There is no rejection, BEGIN/COMMIT/CANCEL or owner-controlled color contract added here. Keep palette/color/state/theme and callback userdata alive through the call. Do not mutate/free/rebind active resources or recursively submit UI in the observer; set unrelated flags and defer omission/teardown until return and frame/render consumption. No payload points into the palette or retains userdata. Color tests pair Base and Styled legacy/facade contexts for real palette clicks, channel keys and saturation/value-plane pointer drags, comparing RGBA, HSV/capture, semantics, results and draw commands. They verify alpha-off preservation, net-zero updates, latent HSV silence, external RGBA resynchronization, absent-observer editing, readonly/disabled cleanup, inert/layout-only silence, copied payload after context destruction and deferred omission. Together with the original Picker and Base-only suites these are native source proofs; foreign/browser parity is not implied. The existing time field remains a separate future slice. --- ## Platform evidence Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PLATFORM_MATRIX.md # Platform evidence | Target | Status | Evidence and limits | |---|---|---| | Linux Xorg | tested partial | Native SDL_Renderer OpenGL, independent Sokol GLCORE and SDL_GPU Vulkan on Intel Graphics; actual frames/readbacks, pointer/key model and clipboard tests. SDL composition/candidate-rectangle forwarding has injected service tests; real OS IME/candidate-window acceptance and native screen readers remain unverified. | | Linux headless | tested partial | GCC C11/software renderer, behavioral suites, ASan/UBSan, SDL dummy services. | | Linux Wayland | untested | SDL supports host integration; no compositor smoke run yet. Xorg is not Wayland evidence. | | Windows | tested portable subset | Published67d86ed4: hosted MSVC19.51.36260.0 passes145/145 portable checks on [CI run38488091130](https://github.com/mattmezza/cui/actions/runs/38488091130). Native adapters are disabled; native GUI/Direct3D, OS IME, accessibility and app packaging are unverified. | | macOS | tested portable subset | Published67d86ed4: hosted Apple Clang21.0.0.21000101 passes145/145 portable checks on [CI run38488091130](https://github.com/mattmezza/cui/actions/runs/38488091130). Native adapters are disabled; native GUI/Metal, OS IME, accessibility and app packaging are unverified. | | Browser WASM | tested partial | Actual Chromium runs CUI WebAssembly with Canvas/input host, including pointer/keyboard, scalar input, popup focus/Escape, themes and 390px bounds. See [browser gallery](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/WEB_GALLERY.md). Native text shaping/OS accessibility remain separate. | | Android | untested | No wrapper/device validation. | | iOS | untested | No wrapper/simulator/device validation/signing. | | WASM/WASI | tested headless WASI subset | Zig0.16/Wasmtime49 portable behavioral/embedding suites compile and run; current source/counts are recorded in validation logs; see [WASI.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/WASI.md). | Optional unavailable integrations are explicit. Compilation will be recorded separately from runtime tests. SDL_GPU SPIR-V shader support currently confines that adapter to Vulkan-capable devices; D3D12/Metal formats are pending. Sokol GLCORE is tested on Linux Xorg; its other backends and platforms are pending. Linux X11 also has [continuous external resize evidence](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/LINUX_LIVE_RESIZE.md) under private Xvfb/software rendering: intermediate captures follow window size, responsive sidebar/card changes and retained application state while a resize burst is ongoing. This does not establish physical window-manager dragging or Wayland behavior. Linux resize support is a separate acceptance scope from the Cocoa/Windows callback scheduling contract. The optional pinned Unicode regex archive is currently validated on Linux native and WASI only. Portable Core/Base/Components need neither that archive nor Rust. Developing on Linux does not prevent macOS support: hosted macOS runners can compile/test the native integration once implemented. Full platform acceptance also requires actual macOS window/render/input/accessibility and hardware/session testing, which can use a remotely accessible Mac rather than the maintainer's laptop. Linux hosted GCC and Clang passed their configured native/sanitizer checks on CI run38225532353 plus Xvfb gallery smoke and Sokol pixel/cache tests. The CI GL driver reported **llvmpipe**, a software driver; this is API/readback coverage and is separate from the actual Intel/Mesa hardware evidence on the development Xorg host. Saved [previous CI summary](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/validation/ci-01865d5.txt) and [latest published-source job metadata](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/validation/ci-3ef6c49.json) record exact source and outcomes. Native macOS build/bundle and headless adapter CI are now authored; they have not yet been observed running for this change. See [the Mac workflow](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MACOS.md) and [Linux cross compilation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MACOS_CROSS.md). Cocoa/Retina/Metal, IME and accessibility acceptance remain separate. --- ## Current-frame Chart and Plot paint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PLOT_CHART_CURRENT_FRAME.md # Current-frame Chart and Plot paint This scoped contract uses Core prepaint rather than retained geometry. It addresses upstream 0.7.1 PlotElement's layout/prepaint split and visibility gate at pinned commit `87d10ae5e1299d1be18670a37570c5402f952e34`; it does not establish full Chart/Plot parity. Set `interaction_mode = CUI_PLOT_INTERACTION_CURRENT_FRAME` on a styled Chart. Core resolves bounds, clipping, pointer position, passive barriers and modal scope at `cui_end_frame`. The Chart resolves its datum against that snapshot, steps its appearance/hover/pointer motion, paints the bitmap and local decorations, then paints the default tooltip in a deferred stream. A stationary pointer therefore uses the new geometry after scroll, resize or layout movement. Unknown pointers supply no live datum. Source appearance gates by linear elapsed time even when the quartic float paint progress has already rounded to one. Exit presentation is retained until its transition settles; reduced/instant motion completes directly. `AUTO` and `LEGACY` preserve existing Chart input behavior, including applications that call `cui_chart_update_hover` with their own coordinates. There is no existing option that unambiguously distinguishes those applications from host pointer routing, so AUTO does not guess from whether Core knows a pointer. Host-driven gallery/application stories should opt into CURRENT_FRAME explicitly. Layout `tooltip_content` and `tooltip_measure` are supported on the legacy path; CURRENT_FRAME rejects them before registering paint. Pure title, label, value, color and number formatters remain supported during paint and must not submit UI. Static axes/legends and custom Radar/Sankey label layout remain composition work. For PlotElement, CURRENT_FRAME ignores its legacy bounds/pointer/hover inputs and uses Core. New `paint_marks` and `paint_tooltip` callbacks receive a const snapshot, a callback-local writer, copied theme values, retained hover values and borrowed user data. They return false to discard their emitted stream. Emit marks with `deferred=false` and tooltip commands with `deferred=true`; the latter clip to the viewport rather than the plot. Apply `hover->progress` to custom paint opacity. The writer also applies ancestor opacity. `paint_command_budget` bounds the combined custom commands (1..4096 with callbacks); the component reserves bitmap and clip overhead separately. CURRENT_FRAME rejects the old layout marks/children/tooltip callbacks and touch input. Existing explicit geometry, touch/long-press state and layout callbacks keep their legacy behavior under AUTO/LEGACY. AUTO selects Core only for new paint callbacks with zero host bounds and no legacy callbacks. Primary activation retains the view's existing release routing and uses the last successfully painted bounds; this is not a new per-mark hit or gesture system. Use the pure `cui_plot_motion_follow_at` with `info->frame_time` to step caller-owned mark springs. It preserves state/output on invalid input and reports whether another frame is needed. A paint callback requests that frame with `cui_prepaint_request_frame(writer)`. It must not call layout, semantics, focus, input mutation or `cui_invalidate`. The existing UI motion helper wraps the same pure step and retains its composition-time invalidation behavior. Motion policy projection and legacy zero/Chart defaults are unchanged. Reduced motion is copied from Core at composition; set it before composing the owner. Driver state, data arrays, pixels, callback user data and pointer-containing options must stay live through end-frame and renderer consumption. Chart copies its name into owner storage before deferred work. Writer text commands copy text; images borrow pixel storage through consumption. The component prepares a local state and publishes it only after successful emission. Callback side effects and mutations to borrowed pixel buffers are outside draw-output rollback. Old callback borrowing contracts remain unchanged. No OS long-press, native screen-reader certification, GPU mesh equivalence or implicit pan/zoom is established by this slice. ## Validation and integration `tests/unit/test_plot_chart_prepaint.c` covers current geometry with stationary pointer and a routed wheel, unknown pointer, passive inert overlay/removal, modal suppression, manual input compatibility, source motion rounding/completion and quiescence, Bar/Pie/Candlestick/Radar hover paint, pure invalid-step atomicity and custom budget exhaustion preserving driver state. Existing Chart tests check the shared legacy motion/update path. `tests/web/test_plot_chart_prepaint.py` compiles the actual pinned-Zig WASM sources with a standalone probe. It uses real mouse/wheel/resize events, frame/phase signals and actual Chromium canvas pixels for Chart geometry/occlusion and Plot local plus deferred paint. It uses no fixed wall-clock sleeps. This proves that fixture, not an exhaustive platform matrix or all gallery stories. Integrator: register the new unit executable/test linked to `cui`; regenerate Chart/PlotView/Motion distribution headers after merging. There are no new production source modules. Browser invocation: ``` TMPDIR=/home/matteo/.cache/cui-validation/tmp-storage uv run --script tests/web/test_plot_chart_prepaint.py --chromium /home/matteo/.cache/ms-playwright/chromium_headless_shell-1208/chrome-headless-shell-linux64/chrome-headless-shell ``` --- ## Owner Plot and Chart motion Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PLOT_CHART_OWNER_MOTION.md # Owner Plot and Chart motion `cui_plot_motion_from_theme` projects a standalone `cui_theme_motion_tokens` value into a copied `cui_plot_motion_policy`. The source projection uses the fast duration for enter/exit and pointer response, the respective enter/exit Bezier curves, source spring damping 1/travel with epsilon 0.1, and a distinct one-second quartic-out appearance. Move/control springs, move easing and rem distances do not drive Plot motion. This matches pinned 0.7.1 `87d10ae5e1299d1be18670a37570c5402f952e34`, `crates/component/src/theme/mod.rs::plot_motion`. ```c cui_theme_motion_tokens tokens = cui_theme_motion_default(); cui_plot_motion_policy motion; if (cui_plot_motion_from_theme(&tokens, &motion) == CUI_PLOT_OK) { chart_options.custom_motion = true; chart_options.motion = motion; plot_options.custom_motion = true; plot_options.motion = motion; } ``` Policies contain values, including Bezier control points; they do not borrow Theme storage or contain self-referential callback userdata. Edit a copied policy for one owner and keep each owner's Chart/Plot state separate. Zero/default `custom_motion=false` preserves the existing Chart one-second appearance/120ms hover and Base Plot explicit zero-duration policies. `cui_chart_theme` continues to project colors only; it does not silently install motion. PlotElement opt-in replaces its legacy enter/exit/appear policies. Appearance still requires its existing explicit identity/generation/frame/scope contract. Chart opt-in consumes enter/exit, appearance and pointer policy internally for line/area, bar/candlestick and pie channels. Positive legacy Chart `appear_duration` overrides policy appearance duration; positive `hover_duration` overrides enter/exit durations and pointer response. Zero legacy durations leave the explicit policy unchanged, so explicit policy duration 0/response 0 means instant. `disable_appear` and owner/Core reduced motion win. Manual reveal remains caller supplied. Changing a policy retimes the existing appearance; changing `appear_key` explicitly restarts it. Same-frame explicit render followed by a changed policy is re-evaluated rather than reusing stale motion. Custom marks decide which datum coordinates to move. In a Plot marks callback, call `cui_plot_motion_follow` with the owner, a zero-initialized caller-owned pointer state, `options.motion.pointer`, the target coordinate and `hover->entering`. Use the returned coordinate when painting. This consumes Core time/reduced motion, requests redraw while moving and resets when the owner changes. Use independent states per coordinate/channel. The helper invalidates Core while moving; the host advances frames using `cui_needs_redraw`, including requests made by marks callbacks. It does not infer arbitrary host mark positions or replace the existing live-pointer/current-bounds host seam. The low-level transition adapter borrows the explicitly supplied transition **only for synchronous stepping**. Do not retain an adapter. Opt-in Plot `on_appear` receives a sampler valid only during that callback. Published Plot state retains time/progress/flags and clears that temporary sampler's pointers. For later stagger sampling, use `cui_plot_motion_appear_stagger(&copied_policy.appear, &copied_state.appearance, ...)`; both values may safely be copied to other addresses. Legacy caller-supplied borrowed samplers retain their prior lifetime contract. Validation rejects invalid enums, nonfinite/out-of-range timing and spring parameters before opt-in widget mutation. Factory, sample, stagger and follow failures preserve their outputs/state. Timing/delay is bounded to 3600 seconds in magnitude; response to 3600, damping to 100, epsilon to 65536. Negative delays are supported. Bezier overshoot is sampled as supplied; Chart reveal/hover and Plot hover opacity clamp to 0..1 for bounded rendering. Undamped springs may keep moving; positive damping settles. Appearance sampling does not rewrite caller data. Host data/callback/bitmap lifetimes remain unchanged. The new native regression demonstrates two owners with different appearance/fade/pointer policies, actual Plot mark composition, line/bar/pie channel independence and settling, reversal, explicit instant/reduced overrides, legacy duration precedence, same-frame policy changes, invalid rollback and copied-state later sampling after original storage is overwritten. The standalone WASM browser probe paints real Chart bitmaps and Plot marks, drives actual mouse input and proves different reveal/pointer motion plus reduced completion. It owns fixed host bounds. No automatic current-frame prepaint/occlusion, OS long-press or native screen-reader parity is claimed. ## Integrator registration Register `src/components/cui_plot_motion.c` in the styled library and web source lists; add `tests/unit/test_plot_chart_owner_motion.c` as a strict target linked to `cui`. In `scripts/amalgamate.py`, register `cui_plot_motion` with this component source and include it as an implementation dependency of Chart/PlotView and the aggregate Components header, alongside existing Plot and Theme dependencies. Regenerate distribution headers. Standalone probe `tests/web/test_plot_chart_owner_motion.py` builds its own scoped WASM fixture and requires pinned Zig 0.16.0/Playwright 1.58.0. No CMake/web/distribution registration was edited by this worker. Validation on base `137e1c5`: strict native build passed without warnings; CTest 112/113 passed, with the sole distribution check reporting stale PlotView/Chart headers (root regeneration). The new behavior target was registered locally using an external CMake include. ASAN/UBSAN with leak detection and GCC fake-stack/use-after-return mode passed; Clang was unavailable. Standalone pinned Zig/WASM Chromium1208 canvas/mouse proof passed. Logs are `/home/matteo/.cache/cui-validation/owner-motion-next23-{handoff-build,commit-ctest,commit-asan,opacity-browser}.log`. --- ## Plot viewport interaction Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PLOT_INTERACTIONS.md # Plot viewport interaction Plot navigation is opt-in. Existing numerical scale functions and `cui_plot_view` retain their previous behavior. Retain a `cui_plot_viewport` beside your application model; it owns the current and initial X/Y scales. No operating-system types, allocation, animation clock, or bitmap is needed by the viewport model. Initialize once, reduce input before projecting data, then bind the submitted surface. For example, inside a frame with a stable `plot_id`: ```c /* Retain viewport across frames, initialize once. */ cui_plot_viewport viewport; cui_plot_viewport_init(&viewport, (cui_plot_scale){CUI_PLOT_LINEAR, 0, 100, 28, 628, false}, (cui_plot_scale){CUI_PLOT_LINEAR, -1.2, 1.2, 142, 12, false}); ``` ```c cui_plot_viewport_options navigation = cui_plot_viewport_defaults(); navigation.disabled = disabled; navigation.x_limit = (cui_plot_viewport_limit){ .bounded = true, .minimum = -100, .maximum = 200, .min_span = 10, .max_span = 300}; cui_plot_viewport_reduce(ui, plot_id, &viewport, navigation); /* Project your data with viewport.x / viewport.y, build retained geometry or * pixels, and update axes from those same scales before submitting the view. */ cui_plot_view(ui, plot_id, &theme, &view); cui_plot_viewport_bind(ui, plot_id, &viewport, navigation); ``` The default options returned by `cui_plot_viewport_defaults` enable both axes for pan and zoom. Zero-initialized options disable navigation. `pan_x`, `pan_y`, `zoom_x`, and `zoom_y` select relevant axes independently. Changing the surface size requires updating the current scale ranges before reduction; reset restores initial domains while preserving those current pixel ranges. The reducer supports: - Shift plus primary mouse drag. Core capture keeps dragging outside the original surface; release or cancellation stops it and suppresses activation. - Ctrl plus scroll, anchored at the pointer. Precise deltas use logical pixels; legacy wheel steps use 32 pixels. Relative factor is `exp(dy * .002)`, with the exponent bounded to ±20. A host normally negates DOM `deltaY` so upward wheel movement zooms in. - Core touch gestures: one contact pans, two contacts pan and pinch. Pinch scale is relative to the preceding event. Pan runs before zoom at the new contact center, preserving the data under the old center at the moved center. - Disabled or modal-blocked surfaces reject navigation. Plain mouse drag and plain wheel do not change the viewport. Call reduction once per surface per frame. It registers a transient nonmodal focus scope using the surface ID to query Core's original clipped, topmost hit for scroll input. Do not separately register another focus scope with that same ID. Binding preserves unrelated semantic details and enables gesture routing and the grab/grabbing cursors only for the opted-in enabled surface. Supply the same `disabled` state to the view and navigation options. `cui_plot_viewport_transform` is also available for application commands. Both axes update transactionally: invalid scales, invalid limits, nonfinite arguments, or numeric overflow leave the viewport unchanged. Logarithmic scales transform in log10 space; reversed pixel ranges are supported. Domain bounds and span limits are expressed in transformed units, so logarithmic bounds are exponents. Zero span limits are unconstrained. A bound narrower than `min_span` is invalid. Span limits clamp zoom and domain bounds clamp translation; at a boundary the pointer anchor may move because satisfying the configured bounds takes priority. There is no inertia, rotation, animation, kinetic scrolling, or automatic data clipping. Applications still clip/project and render their own data. The browser gallery enables navigation and uses the resulting X/Y scales for the line, area, step, radial, natural, rounded-bar, and dot examples. Its reset button restores both domains. The demo constrains X to −100..200 with span 10..300 and Y to −5..5 with span .1..10 to remain within the software geometry budget. These are gallery policies, not limits imposed by the public model. Browser hosts must preserve input modifiers, send cancellation on unexpected pointer capture loss, and prevent browser Ctrl-wheel zoom only for a claimed plot surface. The gallery's Plot-only wheel branch leaves ordinary page wheel scrolling unchanged, denies modal/disabled claims, and queues a precise Ctrl-scroll event for authoritative Core dispatch. Touch remains in the shared Core contact/gesture path; opted-in surfaces keep page-pan fallback from stealing their gestures. Native callers use the same reducer with adapter input; this change does not add a new native-device validation claim. `tests/unit/test_plot.c` checks exact two-axis anchors, pan/pinch composition, reset, span/domain limits, logarithmic reversed ranges, transactional overflow, disabled and zero-option behavior, actual Core contact dispatch, mouse capture cancellation, plain-wheel preservation, and modal rejection. `tests/web/test_plot_interactions.py` uses real Chromium mouse input and CDP touch contacts. It verifies exact projected mouse/touch deltas and wheel anchors, two-contact pinch, capture loss, cancellation and next tap, disabled behavior, and changes to painted data for all seven gallery shapes. Configuration inputs and read-only domain/pixel observations are allowed; component actions do not invoke exported model reducers. Chromium automation is not physical iOS, Android, pen, or native touch-device coverage. Validation of this change: warning-enabled native build; 93/94 existing CTest checks passed, with the sole failure being the root-owned stale generated distribution. Plot and styled Plot passed under ASAN/UBSAN (2/2). The strict new browser suite passed 17/17, and the existing touch suite passed 42/42 while rendering all 78 stories. The two public API examples above compile in real C11 contexts with `-Wall -Wextra -Wpedantic -Werror`. Run the browser regression after building the gallery: ```sh uv run tests/web/test_plot_interactions.py --directory build/web ``` --- ## RadioGroup Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/RADIO_GROUP.md # RadioGroup `cui_radio_group` supplies a bounded collection of up to 64 radio options. Each item has a stable, unique, nonzero `cui_id`, a label and an optional disabled flag. The application owns one selected ID (`0` means no selection) and persistent `cui_radio_group_state`. Existing `cui_radio` and `cui_radio_ex` remain compatible. ```c #include typedef struct { cui_id selected; cui_radio_group_state radio; } settings; static void accept_delivery(void *user, cui_id requested) { settings *model = user; model->selected = requested; } void delivery_settings(cui_context *ui, const cui_theme *theme, settings *model) { cui_radio_group_item items[] = { {cui_id_from(ui, "standard"), cui_string("Standard"), false}, {cui_id_from(ui, "priority"), cui_string("Priority"), false}, {cui_id_from(ui, "express"), cui_string("Express unavailable"), true}}; cui_radio_group(ui, cui_id_from(ui, "delivery"), theme, items, 3, &model->selected, &model->radio, (cui_radio_group_options){.name = cui_string("Delivery options"), .vertical = true, .on_change = accept_delivery, .change_user = model}); } ``` With a callback, each validated request invokes it once; the group does not write the selected model. Accept by updating the selected ID synchronously, or reject by leaving it unchanged. Without a callback, the group updates the selected ID. Activating the already selected option produces no callback. Requests are resolved before any option is painted, so accepted and rejected state produce coherent checked snapshots and selected marks in the same frame. Multiple queued navigation events advance in order. A callback must not change the item array or destroy its model during the call. Labels/items are borrowed for the synchronous frame build; retain ordinary Core text lifetimes through rendering as required by the host. Arrow keys move focus and request selection, skipping disabled items and wrapping. Home and End choose the first and last enabled option. Enter/Space activate the focused option. One enabled item is in the Tab sequence: the focused item while focus is within the group, otherwise the selected enabled item or first enabled item. `skip_tab` removes all group options from that sequence while pointer focus and explicit keyboard focus remain available. Disabled groups have no tab stop and reject activation. A removed or newly disabled focused item moves focus to an enabled fallback, without inventing a selection callback. An empty/all-disabled group clears its own focus. External focus is retained. Selection IDs are stable across reorder. A removed selection stays caller-owned and paints no selected option; a disabled selected option remains checked but cannot activate. The application decides whether to clear or replace those model values. This preserves controlled callback semantics during collection changes. Invalid inputs (duplicate/zero IDs, more than 64 items, invalid sizes or gaps) return `valid=false` before registering the collection. No heap allocation is performed. The collection emits RADIOGROUP semantics with orientation/name/required/invalid; children emit RADIO with parent, checked, disabled, position and set size. These are portable snapshots, not a native OS accessibility bridge. Shared cursor and interaction queries can be applied to stable item IDs after submission. The component supports four legacy control sizes and all 14 design sizes, including theme density. It uses the existing selection mark renderer and the same indicator/font/theme colors as the standalone radio. The separate base API registers/reduces behavior without styled layout; a custom renderer must submit boxes with the same IDs. Do not register another interactive radio with the same ID after calling the base API. The reference's richer child composition, tooltip builder, spring mark animation and unrestricted style refinement are not provided by this initial group API. Full Radio-family source parity is not claimed. The headless test asserts same-frame selection paint, semantic set relationships, callback rejection/acceptance, selected no-op, keyboard wrap/disabled skipping, queued navigation, one tab stop, touch drag/cancel suppression, focus cleanup, bounded validation and all 14 design sizes at two densities. The browser suite uses actual mouse, keyboard and CDP touch events on the gallery's visible options. Chromium touch emulation is not evidence from a physical mobile device. --- ## Checked accessor callers Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/RELEASE_ACCESSORS.md # Checked accessor callers Dock and table components check model getter results before reading output values. Visibility and render callbacks can change the model between traversal steps; a failed getter skips the unavailable item or reports an error where traversal is required to complete. Dock lifecycle capture builds its next snapshot in temporary storage. Allocation failure returns `CUI_DOCK_CAPACITY`; invalidated traversal returns `CUI_DOCK_INVALID`. Both preserve the previously pending snapshot and clear the capture guard. Callback edits to the model itself are not rolled back. Capture sets the existing dispatch guard while evaluating callbacks to prevent reentrant capture or dispatch from publishing incomplete data. `tests/unit/test_release_accessors.c` uses explicit checks that remain active in optimized builds. It covers unchanged outputs on failed getters, visibility callbacks removing panels, lifecycle snapshot preservation after callback edits and allocation failure, and table header/label callbacks shrinking bound data. On GNU-compatible ELF linkers, define `CUI_TEST_ALLOCATOR` and link with `-Wl,--wrap=malloc` to enable the allocation failure case. Other platforms can run the remaining cases without this definition. This is focused traversal hardening, not a guarantee that arbitrary mutation of all borrowed application data during callbacks is supported. --- ## Responsive containers Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/RESPONSIVE_LAYOUT.md # Responsive containers Use `cui/cui_responsive.h` to make layout decisions from a container's current logical width. Named mobile-first breakpoints resemble familiar utility-class systems: BASE, SM (640), MD (768), LG (1024), XL (1280), and 2XL (1536). This header-only utility needs no backend, allocation, or additional library. Like Tailwind's `md:` and `lg:` variants, `at_least(query, MD/LG)` applies a policy at that width and above. BASE is the unprefixed/mobile policy. Unlike a global browser viewport query, each query uses the logical width you pass: the window, a sidebar, or the remaining main-content area. C layout properties remain normal designated initializers; no class strings or generated styles are needed. ```c #include "cui/cui_responsive.h" /* Product-specific tokens. Keep them ordered; units are logical pixels. */ const cui_breakpoints app_breakpoints = { .sm = 560, .md = 720, .lg = 1000, .xl = 1280, .xxl = 1536 }; cui_responsive container = cui_responsive_query(available_width, &app_breakpoints); bool persistent_nav = cui_responsive_at_least(container, CUI_BREAKPOINT_LG); /* Selector order: query, breakpoint, base value, expanded value. */ float padding = cui_responsive_value(container, CUI_BREAKPOINT_MD, 12, 24); cui_begin_box(ui, 100, (cui_box){.width = -1, .row = persistent_nav, .gap = 12}); if (persistent_nav || app.drawer_open) submit_navigation(ui, &app); submit_main(ui, &app, padding); cui_end_box(ui); ``` Pass NULL for standard thresholds. `at_least` includes the threshold itself. Thresholds must be finite, nonnegative, and nondecreasing; equal thresholds skip intermediate classes. Widths must be finite and nonnegative. Invalid input returns `valid=false`, width zero, and BASE; **every** `at_least` predicate then returns false, including BASE. Check `valid` before submitting a container. `value` chooses its base argument for invalid queries. It does not validate the two caller-provided values or change their units. For content constraints, `cui_responsive_fits(query, first_min, second_min, gap)` answers whether two panes can sit side by side. Query the main area's width after subtracting sidebar and spacing, rather than reusing the window breakpoint: ```c cui_responsive main = cui_responsive_query(main_inner_width, NULL); bool row = cui_responsive_fits(main, 260, 260, 12); cui_begin_box(ui, 200, (cui_box){.width = -1, .row = row, .gap = 12}); submit_summary(ui); submit_activity(ui); cui_end_box(ui); ``` `fits` rejects negative/nonfinite minima and gaps. Its comparisons avoid overflow when adding large finite dimensions. Breakpoints select policy; normal CUI GROW (`-1`), explicit dimensions, padding, rows and columns perform layout. Recompute queries each frame, including when only a nested container changes width. Width queries do not read a window, multiply by display density, or schedule work. The `examples/responsive_dashboard` fixture keeps one `dashboard_app` state while resizing: navigation stays beside content at LG, becomes a Menu disclosure below LG, and the cards stack when their minimum widths no longer fit. The disclosure occupies layout space above the main content, so it cannot overlap active content beneath it. Hidden navigation is omitted from submission, including its input and semantics. Closing it keeps page/account state. Applications that want an overlay drawer should additionally use the existing modal/overlay scope APIs. This helper supplies width policies, not CSS media-query or browser-layout parity. The example and tests cover live container resizing, boundary crossings, navigation/account callbacks, state preservation, and clicks at removed targets. ## Build and run Portable assertions, including repeated resizing without a window: ```sh cmake -S . -B build -G Ninja -DCUI_BUILD_NATIVE=OFF cmake --build build --target test_responsive test_responsive_dashboard python scripts/test_local.py --build-dir build -R '^responsive(_dashboard)?$' ``` Interactive native example (requires the existing SDL3, FreeType and HarfBuzz adapters). Run from the repository root or supply an absolute `--font` path: ```sh cmake -S . -B build-native -G Ninja -DCUI_REQUIRE_NATIVE=ON -DCUI_BUILD_RESPONSIVE_DASHBOARD=ON cmake --build build-native --target cui_responsive_dashboard ./build-native/cui_responsive_dashboard --font third_party/inter/Inter-Regular.otf ``` Resize the window through 360, 800 and 1400 logical units, open/close Menu, choose Reports, and sign in. Page/account/disclosure state survives resizing. The callback runner owns native event dispatch, including redraw during resize; the application submits one frame using the current logical container dimensions. On macOS the target follows the existing bundle configuration and locates its bundled Inter font. `--frames N --capture PATH.bmp` provides a finite smoke run; automated runs must use an isolated display rather than the desktop session. The WASI harness also registers the responsive policy and dashboard interaction suites. With the pinned Zig/wasmtime tools: ```sh uv run scripts/test_wasi.py --suite responsive --suite responsive_dashboard ``` Omit `--suite` to exercise all portable suites. WASI validates portable layout and interactions; it does not emulate a browser or native resize event loop. --- ## Rust CUI builders Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/RUST_BUILDERS.md # Rust CUI builders For installable local wheel, npm, Go module and Rust crate artifacts, see the [packaging guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PACKAGING.md). Linux alpha packages are tested outside the checkout; registry publication and other platform packages remain pending. The `cui-builders` crate is a native Rust authoring layer over `libcui_bridge`. Its `Kind` enum follows the public bridge kind list in [`cui_bridge.h`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_bridge.h), including the legacy native components delivered through Settings. The independent kind81 controlled route uses `App::slider_model`, not a new generic Kind variant. This is the current bridge scope, not full parity with all 78 CUI manifest entries. Its node handles are app-scoped; calls reject handles from another app, and the C bridge rejects removed nodes. The `App` contains an `Rc` marker and cannot be sent or shared across threads. C strings are checked for interior NUL and the bridge's 4096-byte limit before FFI. Rust callbacks execute during `dispatch()` after `step()` returns from C; no Rust closure is passed into native frames. Build from the repository root with CMake, Ninja, Rust 1.85.1 or newer (validated with 1.85.1 and 1.99). The crate uses no external dependencies: ```sh cmake -S bindings/bridge -B build-bridge -G Ninja cmake --build build-bridge --target cui_bridge test_bridge_core CUI_BRIDGE_LIB_DIR="$PWD/build-bridge" cargo test --manifest-path bindings/rust/Cargo.toml -- --test-threads=1 ``` Matching bundled-source builds pass Cargo's positive `NUM_JOBS` count to the child CMake build. Use `CARGO_BUILD_JOBS=1` or Cargo `-j1` to keep both phases serial; missing/invalid standalone NUM_JOBS falls back to1. Setting only CMAKE_BUILD_PARALLEL_LEVEL does not replace this explicit Cargo-selected count. `CUI_BRIDGE_LIB_DIR` selects an existing dynamic library and skips that CMake source build. The offline build-script fixture uses fake CMake/pkg-config and never builds an SDK or opens a window: ```sh python bindings/rust/tests/test_build_parallelism.py ``` Serialize all calls across all apps, including apps created on separate threads: the current core uses a process-global Clay context. The crate tests enforce this contract with a process mutex. `build.rs` adds `CUI_BRIDGE_LIB_DIR` to the native linker path and Linux runtime path; use an absolute path. On other platforms, place the shared library on the platform dynamic library search path. The crate checks the bridge ABI version and `cui_bridge_options` size at creation. The C library itself needs its pinned SDL3 dependencies as configured by CMake. Native SDL rendering needs a TTF file. Run the example only on a display you intend to use: ```sh CUI_BRIDGE_LIB_DIR="$PWD/build-bridge" CUI_TEST_FONT=/path/to/font.ttf cargo run --manifest-path bindings/rust/Cargo.toml --example save_changes ``` The example authors a column, label, row and Button in Rust. A click changes shared Rust state; the label is updated after event dispatch. For a finite SDL smoke under an invisible Xvfb, set `CUI_TEST_FONT` and run `bindings/rust/scripts/test_sdl_smoke.sh`; it fails closed if Xvfb is unavailable. For automated native CTest checks, use `python scripts/test_local.py --build-dir build` from a configured top-level build. It provides an invisible Xvfb on Linux; never use `DISPLAY=:0` or the maintainer's Wayland session. GPU hardware checks remain deferred under Xvfb. `App::headless` is suitable for deterministic bounds and host input fixtures. Queue pointer or keyboard events, call `step`, then `dispatch` (or `frame` for both). `on_change_event` receives each frame's copied checked, numeric, UTF-8 text, and selected Item snapshot. `queue_text` feeds the focused editable node; `editable_text` reads its current text. Button callbacks receive no `App` borrow; update an `Rc>` or queue a message and apply UI mutations after dispatch. `Size` covers inherit, XS through 9XL. `gap_px` is logical pixels; `gap_units` multiplies by four. Grouped `Item` handles in RadioGroup, Tabs, Select, and ComboBox can be selected with `select`; `selected` returns `None` before a choice. `detail_text` sets Alert body text, Select placeholder, or DropdownButton menu label; `open` controls disclosure state. `dropdown_part_bounds` locates split action and menu targets for host input. Surfaces expose `open`/`is_open`, `on_close_event`, and typed `surface_result()`; Popover, Tooltip, and HoverCard require a live anchor via `anchor`. Hover transitions arrive through `on_change_event`. `visual_size` sets explicit dimensions for Avatar, EmptyView, GroupBox, Skeleton, and Spinner. `total`, `step_status`, and `numeric_part_bounds` expose native pagination, rating, and step interactions. `scroll_extent` sets Scrollable content dimensions and `scroll` queues a host wheel fixture; offset changes arrive through `on_change_event`. StatusBar, Toolbar, and TitleBar use Item children; StatusBar Item `step_status` chooses left (0), center (1), or right (2). Icon `text` is a catalog name; an unknown name fails the frame. Message `text` is body and `detail_text` is header. Attachment uses `text` title, `detail_text` description, `value` progress 0..1, and typed `attachment_status`; this bridge component is a metadata chip. `image_rgba` copies RGBA8 pixels into the bridge (maximum 16 MiB, 2048 pixels per dimension), so the caller can release its buffer after the call. Tree uses flat preorder Item children; Item `step_status` is depth 0..63, `checked` controls expansion, and `select` chooses the active Item. TimeField uses a portable `Time { hour, minute, second }` in 24-hour format; edits deliver HH:MM:SS text snapshots. ColorPicker uses packed `0xRRGGBBAA` values; `color_part_bounds` exposes hue, plane, and alpha hit targets (parts 1–3), and change events carry copied `#RRGGBBAA` text. Calendar and DatePicker use a portable `Date { year, month, day }`; `calendar_day_bounds` finds a rendered day. The current native mode is English single-date selection. OtpInput uses `total` for 1–256 cells, `text` for its current value, and queued host text for one cell at a time; changes carry copied text snapshots. Form uses Item fields; each Item may contain native controls. A disabled Form suppresses its controls. The bridge currently has no built-in Form validation or nested Form support. InputGroup owns editable text and Item button addons; Item `step_status` selects inline start/end or block start/end positions (0–3). Notification is a retained in-app card: `text` title, `detail_text` message, `open` visibility. Its close callback fires when the closing animation finishes; there is no OS delivery. FocusTrap accepts child nodes and uses `open` to enable a native modal focus scope that blocks outside pointer actions. MessageScroller uses Item messages (`text` body, `detail_text` sender, `step_status` incoming 0/outgoing 1) and `value` for its scroll offset. Carousel accepts Item slides and uses `select`/`selected`; native wheel, drag, and keyboard navigation emit selected Item snapshots. Resizable accepts Item panels with pixel widths in `value`; `resizable_handle_bounds` locates a draggable divider and change events carry new sizes. TextView owns Markdown, HTML, or plain source in `text`; `text_view_format` selects its parser. `text_view_select` uses rendered UTF-8 byte offsets, and `text_view_selection` copies plain selected text. Native pointer selection delivers a copied text snapshot through `on_change_event`. Editor owns a multiline UTF-8 buffer; `text` supplies initial source, `detail_text` sets the language name, `editable_text` reads the current document, and queued host text generates copied change snapshots. The bridge currently supports up to 4096 bytes and 512 lines, without completion, syntax callbacks, search, or clipboard APIs. Chart accepts up to 64 caller-supplied label/value pairs through `chart_data`; the bridge copies them. `chart_kind` selects line, area, bar, or pie rendering, and `chart_datum` reads one retained pair. This native chart is a basic raster/hover view, with no streaming data API. Table is compositional: Table children are Item rows and each row contains Item text cells. The first row is the header. This bridge Table has no sorting, selection, or virtualization. DataTable accepts copied UTF-8 headers and row-major cells (up to 16 columns and 32 rows) through `data_table`; its bounds helpers locate cells and headers for host input. `data_table_state` reports selected one-based row/column and requested sort column/direction. Sort is a request: re-supply rows in the desired order. Change callbacks expose the raw native `checked_raw` field as well as its Boolean convenience form; DataTable CHANGE callbacks include a copied JSON text snapshot with reason, row, column, sortColumn, and sortDirection; `data_table_state` reads current state. Plot accepts up to 256 copied finite `PlotPoint { x, y }` values through `plot_points` and supports readback via `plot_point`. The current native Plot draws themed dots without axes, paths, or hit-testing. Command accepts up to 64 Item actions; each Item uses `text` as label and `detail_text` as one filter keyword. Command owns the query through `text`/`editable_text`; `command_item_bounds` locates a filtered action for pointer input. Native selection produces CHANGE events and confirmation produces an Item CLICK callback. There are no grouped or custom result rows. VirtualList accepts up to 64 keyed Item rows, renders a fixed 32-pixel vertical viewport with overscan, and exposes its scroll offset through `value`/`current_value`. `virtual_list_item_bounds` succeeds only for currently rendered rows. Native wheel and key scrolling emit offset CHANGE events; there is no unbounded data source callback. Sidebar accepts Item navigation actions; `open` controls disclosure, `selected` reads the active Item, and native activation emits a selected CHANGE plus Item CLICK. DataTable also supports typed row, column, or cell `data_table_selection_mode`; cell selection snapshots preserve columns beyond the first in copied event JSON. RootView is a sole root node that composes regular child widgets and accepts `root_padding` from 0 to 256 logical pixels. `App::theme_presets` lists native preset names; `set_theme_preset` changes the theme for one app and `theme_preset` returns `None` before an explicit selection. SDL apps also expose `clipboard_set` and `clipboard_get` on the owner thread outside a frame. Clipboard text is UTF-8 and limited to 64 KiB; headless apps return backend unavailable. Speech is a host-reported lifecycle view: `speech_start`, partial or final `speech_report`, `speech_finish`, and copied `speech_transcript`. It does not capture microphone audio or run recognition; CHANGE callbacks copy lifecycle and transcript snapshots. Questionnaire composes Item questions and nested Item choices. `questionnaire_question` configures required and multiple selection before the first frame, which freezes the schema; `questionnaire_next` enforces required answers, `questionnaire_previous` navigates back, and state/choice getters read current progress. Its CHANGE callbacks contain copied JSON snapshots of choices, navigation, completion, and repeated `questionnaire_submit` actions. Dock composes Item panels with optional child content; `dock_activate`, `dock_move_split`, `dock_active`, `dock_panel_bounds`, and `dock_serialize` expose the native panel model. Dock panel schema freezes after the first frame. `DockAxis` selects horizontal or vertical splits; serialized layout is copied UTF-8. Settings composes Item pages, nested Item groups, and Switch/Checkbox/Input/NumberInput fields. `settings_query` filters pages (up to 256 bytes), `settings_page`/`settings_set_page` control navigation, `settings_field_bounds` locates visible fields, and `settings_reset_page` restores first-frame defaults with copied field events. The page/group schema freezes after the first frame; Input and NumberInput titles use `detail_text`. All fallible setters return the bridge status as `Error(code)`. ## Composed workspace example `bindings/rust/examples/workspace.rs` authors a navigable Account/Preferences workspace entirely in Rust. Account has an editable name and a DatePicker initialized to an older birthday; Preferences has a notifications Checkbox. The Save Button callback records shared Rust state; after dispatch, the loop changes the status label and opens a Dialog. `--headless` drives native bounds and pointer input, edits the name, switches tabs, toggles the Checkbox, and verifies the Dialog without opening a window: ```sh CUI_BRIDGE_LIB_DIR="$PWD/build-bridge" cargo run --manifest-path bindings/rust/Cargo.toml --example workspace -- --headless ``` For a desktop SDL session, set an explicit font and omit `--headless`: ```sh CUI_BRIDGE_LIB_DIR="$PWD/build-bridge" CUI_TEST_FONT=/path/to/font.ttf cargo run --manifest-path bindings/rust/Cargo.toml --example workspace ``` A finite SDL smoke must use an invisible display on Linux. From the repository root with `xvfb-run` available: ```sh CUI_BRIDGE_LIB_DIR="$PWD/build-bridge" CUI_TEST_FONT=/path/to/font.ttf CUI_RUST_SMOKE_FRAMES=3 env -u DISPLAY -u WAYLAND_DISPLAY xvfb-run -a env CUI_TEST_VIRTUAL_DISPLAY=1 cargo run --manifest-path bindings/rust/Cargo.toml --example workspace ``` The SDL workspace also accepts `CUI_FONT_FALLBACK=/path/to/another.ttf`, which calls `App::font_fallbacks` with an explicit fallback font path. The smoke path rejects a missing virtual-display marker. It exercises SDL construction and rendering for three frames; the deterministic `--headless` path verifies interaction. For a Rust SDL clipboard round trip under an invisible Linux display, use an explicit font and the virtual-display marker: ```sh CUI_BRIDGE_LIB_DIR="$PWD/build-bridge" CUI_TEST_FONT=/path/to/font.ttf env -u DISPLAY -u WAYLAND_DISPLAY xvfb-run -a env CUI_TEST_VIRTUAL_DISPLAY=1 cargo run --manifest-path bindings/rust/Cargo.toml --example clipboard_smoke ``` ## Hidden native windows `App::sdl_with_window_options(width, height, title, font, WindowOptions { initially_hidden: true })` requests hidden creation before the first frame. `App::sdl` remains visible; `WindowOptions::default()` also stays visible. Use `app.set_window_visible(true)` and `app.window_visible()` (Results) on the owning UI thread, outside Core stepping; `run_with` after-frame callbacks may use them. Headless visibility queries return unavailable. This is an additive Rust API and independent C window-options record, preserving the old C options ABI. Rebuild with matching native exports for the new methods. See the [shared contract and Linux proof](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BINDING_BUILDERS.md#native-window-visibility). ## Bounded typed root shadows See [typed root shadow authoring](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_SHADOWS.md) for the six-kind implementation, owned values, canonical CSS/preset factories and explicit clear/reset behavior. Focused portable runtime tests cover this subset; integration remains pending. This does not expose compound parts or portals. For bounded semantic ROOT/MAIN/indicator/track/thumb authoring, read [typed part shadows](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_PART_SHADOWS.md). Slider has no thumb; owner topology, whole-group naming and separate reset are explicit parts of that contract. ## Controlled Single/Range Slider The unreleased [controlled Rust subset](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/RUST_SLIDER_MODEL.md) supplies owned f64 Single/Range requests, u64 identities and explicit issued-receipt acceptance. It uses a restricted borrowed `SliderRequestContext`, preserving legacy callback signatures and scalar Slider autoacceptance. Its complete windowless authored UI is `bindings/rust/examples/slider_model.rs`. Linux dynamic current/old/provider, UI and matching bundled-static source checks passed on1.99.1; MSRV1.85.1 validation remains a required follow-up. Direct C custom style/motion and native numeric AT are not exposed by this subset. --- ## Scrollbar appearance and idle hiding Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SCROLLBAR_APPEARANCE.md # Scrollbar appearance and idle hiding Set `theme.scrollbar` once for all themed scrolling owners, or pass a borrowed `scrollbar_style` override in the relevant options. An override replaces the shared skin; it is read only during the widget call/frame and is never retained. Surface begin copies its skin and palette until the paired footer/end calls. ```c theme.scrollbar = (cui_scrollbar_style){ .visibility = CUI_SCROLLBAR_AUTO_HIDE, .thickness = 8, .min_thumb = 24, .thumb_radius = 4, .no_track = true, .idle_seconds = 1, .fade_seconds = .15f, }; ``` `INHERIT` is the zero-initialized compatibility policy: existing bars remain available, and owners that previously had no bars remain barless. `VISIBLE` adds bars to overflowing formerly barless viewports. `HIDDEN` omits their paint, pointer/keyboard bar semantics and drag handling. It preserves the content's scroll owner and wheel, touch and existing keyboard behavior. A legacy explicit `hide_scrollbars` option still wins over the skin. Positive finite thickness/minimum values override the owner's defaults. Thickness is capped at half the smaller viewport dimension. Thumb minimum is capped at track length. Thumb and track radii are independent, with zero choosing square corners. Existing Tabs retain their legacy rounded bar under a zero skin. `custom_thumb_color` and `custom_track_color` allow RGBA overrides, including transparent colors; otherwise the owner's palette supplies colors. `no_track` removes the painted track without removing its visible thumb's hit region. Existing gutter bars keep their gutter during auto-hide, avoiding reflow as opacity changes. HIDDEN releases their gutter. Newly added bars are overlays and never reserve a gutter. Overlay corners use the horizontal bar's hit region where both axes meet. Bars are bounded by the owner's clip and stay fixed as content translates. ## Owners and axes | Owner | Actual axes | INHERIT availability | Style route | | --- | --- | --- | --- | | Scrollable | Caller-selected horizontal/vertical | Existing gutter bars | `cui_scroll_options`, theme | | Sidebar body | Vertical | Existing gutter bar | Sidebar options, theme | | DataTable / virtualized table | Horizontal/vertical, preserving pinned columns | Existing `scrollbars` option | Table options, theme | | VirtualList | Horizontal/vertical according to its model | Existing gutter bars | Its nested scroll options, theme | | MessageScroller / conversation | Vertical | Existing `scrollbar` option | Message scroller options, theme | | Tabs and Dock tab strip | Active horizontal or vertical tab axis | Existing `scrollbar` option | Tabs options, theme; Dock forwards theme | | Textarea and Editor | Vertical; horizontal when no-wrap | No bars | Textarea options, theme | | Tree | Vertical | No bars | Tree options, theme | | List, ListMulti, searchable/choice/combobox popup lists | Vertical when windowed | No bars | List/popup options, theme | | MenuTree, nested Menu, ContextMenu, split/dropdown and overflow menus | Vertical per overflowing popup level | No bars | Menu options, theme | | Dialog, AlertDialog, Sheet, Popover body | Vertical | No bars | Surface options, theme | | Command palette | Vertical | Existing Scrollable bar | Theme through common Scrollable | | Settings body | Vertical | Existing Scrollable bar | Theme through common Scrollable | | TextView body | Vertical when explicitly scrollable | Existing Scrollable bar | TextView options, theme | | TextView wide table | Horizontal | No bars | TextView options, theme | | AttachmentGroup | Horizontal | No bars | Explicit `scrollbar_style` and optional `scrollbar_theme` | | Finite Carousel | Its configured horizontal or vertical axis | No bars | Carousel options, theme | AttachmentGroup's existing API has no theme argument. Its optional borrowed `scrollbar_theme` supplies the application palette and shared policy; absent that pointer it uses the light palette and the inherited no-bar policy. Explicit skin colors work without a palette pointer. Lists and menus preserve discrete row windows. Bar movement changes the window, not the selected value or action. Their active keyboard row is kept in the new window so the existing next-frame reveal does not undo bar movement. Menu rows use their actual varying heights. Finite Carousel bar movement uses the model's nearest slide and normal change callback; it does not create a second scroll model. Looping Carousel has no finite beginning/end, and intentionally has no bar even with VISIBLE/AUTO_HIDE. A raw `cui_table_begin` composition, resizable/dock content callbacks and plain boxes do not create scroll models; use Scrollable inside them. Single-line Input caret reveal is not a general panel scroll owner. Plot domain pan/zoom is a separate interaction model and is unchanged by this skin. No unsupported horizontal axis is invented for Tree, Surface or row lists. ## Auto-hide and lifetime The portable timer uses `cui_frame_time`, one context resource per auto-hide bar, and no OS clock or per-frame allocation. Initial submission, a scroll value change, owner hover entry/movement and owner/bar scroll or keyboard activity refresh the idle deadline. Bar hover, capture, drag, direct owner/bar focus and an applicable named focus scope keep it visible. Arbitrary focused descendants of an ordinary box do not hold an overlay visible indefinitely. Default idle/fade durations are 1/.15 seconds. Positive finite durations are capped at 60/5 seconds. The helper requests redraw only before the idle/fade deadline. The final zero-opacity frame requests no further redraw. A held bar requires no timer frames; releasing it starts a fresh finite idle period. `no_fade`, skin reduced motion, component reduced motion where exposed, and context reduced motion remove fading while retaining the idle deadline. Hosts must honor ordinary `cui_needs_redraw` invalidations and advance frame time. Visible/hidden/inherited common bars allocate no timer. Formerly barless overlay owners use one bounded context drag resource while opted in. Surface additionally uses one bounded stack of 64 paired submissions, allowing nested inactive and active skins without retaining caller state past frame completion. An inherited Surface with no prior opt-in stack allocates nothing. Capacity exhaustion uses the existing context capacity error; Surface refuses begin before opening its composition if its stack cannot be obtained. Never pair footer/end with a failed begin. Resource cleanup follows the existing complete-frame omission rule. The new `cui_resource_find` is an in-frame lookup of an existing resource. It never allocates and reports no error for missing/invalid input. A successful lookup marks the resource used this frame. Returned memory remains owned by the context and follows the existing renderer-completion/next-begin lifetime. The split overlay helpers reduce before content layout and paint afterward. Paint receives final offsets explicitly, so wheel correction and discrete row quantization use the actual model position. Its local viewport coordinates must cancel any ancestor content translation; built-in callers do this. Invalid nonfinite geometry/offsets leave caller offsets unchanged. These helpers add bar interaction, not wheel/touch ownership or automatic wrapping. ## Validation Headless tests cover shared colors/radii/thickness/minimums, hidden hit regions and wheel movement, finite fade completion/no perpetual redraw, reduced motion, capture retention, list/menu window movement without selection callbacks, both tab axes, tree and editor bars, fixed Surface footers, Surface allocation failure and inherited zero allocation, finite Carousel selection, and wide TextView table geometry. Existing interaction suites retain legacy INHERIT coverage. `tests/web/test_scrollbar_appearance.py` drives the actual WASM gallery and CDP touch contacts. It checks common families, hidden semantic ownership and real wheel/touch scrolling, plus idle/capture behavior. The gallery controls apply one shared policy to the current example and respect light/dark palettes. This does not claim OS-native scrollbar rendering, infinite-range scrollbar support, or new scrolling behavior for components without a scroll model. --- ## Final-offset scroll observers Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SCROLL_EVENTS.md # Final-offset scroll observers Include `cui/cui_scroll_events.h`. Drawing-free `cui_base_scrollable_events` / `cui_base_scrollable_finish_events` and Styled `cui_scrollable_begin_events` / `cui_scrollable_end_events` observe one final offset per pair. Legacy Scrollable APIs, public state/options layouts and reduction timing are unchanged. Scrollbar overlays, virtual widgets and MessageScroller have no new observer facade. See the [checkpoint](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SCROLL_EVENTS_SLICE.md). ```c static void scrolled(void *user, const cui_scroll_change *change) { cui_scroll_offset *last = user; *last = change->value; /* Copyable values; not a request to accept/reject. */ } /* During one frame; state/options/last belong to the application. */ cui_scroll_event_scope scope = {0}; bool begin_changed = cui_base_scrollable_events(ui, owner, &state, options, &scope); (void)begin_changed; /* False can mean valid no-change; still finish. */ /* Compose the owner's same-ID layout and children here, as with the legacy Base * reducer. Children may defer wheel input back to this owner. */ cui_scroll_event_result result = cui_base_scrollable_finish_events( ui, owner, &state, options, &scope, (cui_scroll_handler){scrolled, &last}); /* Base does not update your viewport translation or paint. Use final state.x/y * for that work as in your existing custom layout. */ ``` Base begin returns the exact old `cui_base_scrollable` bool, including offset normalization, and does not mean successful submission. A nonnull context/state/ token, nonzero owner, zero-initialized inactive token and active ordinary or passive submission admit the pair. Invalid arguments, outside-frame/protected phases or an already-active token reject before reducer work. After an admitted begin, finish once after children even if begin returned false. Calling finish on an unadmitted token is harmless and returns `valid=false`; do not read private token fields to decide application control flow. Reuse a consumed token or zero-initialize new caller storage; never copy a live token or share it between owners. Finish calls the existing wheel-only finish once, then freezes entry/final offsets, consumes the token and optionally notifies. `valid` reports pairing and finite final-state admission, not frame/layout success. `changed` compares the whole pair, not only the finish delta. `change_count` counts actual callbacks (zero or one); `count_overflow` is always false for this bounded aggregate. Reading a result never replays dispatch. Missing handler still performs all old reduction and reports changes with count zero. Net-zero offset sequences, drag-state-only changes and unchanged offsets are silent, even if individual input operations occurred. This is an applied final-offset notification, not a user gesture or controlled value request. It includes clamping from range shrink, disabled axes, negative entry values and nonfinite entry repair. The new payload has `has_previous=false` and zero `previous` when either entry coordinate was nonfinite; otherwise both previous coordinates are preserved exactly. Finite final values are copied into `value`. An external assignment before begin becomes the baseline, not its own event. Do not mutate active state between the pair to manufacture an event. Disabled ordinary submission can normalize state and dispatch CHANGE. Inert or layout-only scopes preserve the existing reducer's maintenance/layout behavior, and can return `valid=true, changed=true`, but callbacks are suppressed because the public frame sequence is zero. This does not introduce user requests under inert ancestry. No callback means neither rollback nor absence of maintenance. Metadata uses CHANGE and the public owner target. The only evidence flag is HAS_FRAME with the genuine matching nonzero frame sequence. Source is UNKNOWN; there is no HAS_SOURCE, event index or activation snapshot. Several inputs or normalization can contribute, so guessing a final wheel/key cause would be false. Payload is pointer-free and safe to copy beyond frame/context lifetime; it does not keep the owner or context alive. Same context, owner, state address, effective options, frame and ancestry must surround the pair. Runtime checks reject identity mismatch, token reuse, outside submission, differing nonzero frame identities, and zero/nonzero scope transitions before finish effects. With both sequences zero the existing public API cannot prove same-frame identity: crossing frames/scopes is unsupported caller misuse without a guaranteed diagnostic. Same effective options/style lifetime is a caller obligation, not a runtime descriptor-equality check. Keep each nested token separate. A wrong pair is not automatically repaired or cancelled; an admitted layout must still follow its legacy balancing obligations. Nonfinite final state from forbidden caller mutation returns invalid after token consumption; no callback is invented. Handler and user data are borrowed only through finish. They are never stored in the scope or context. Callback may update unrelated application state, but must not recursively submit this control/frame, mutate active input/scroll state/options, destroy the context or free active resources. Defer teardown until existing frame obligations complete. No lifetime guard or general event routing is added. The focused tests compare old/new state, semantics, consumption and begin bool; cover multiple wheel events, net-zero changes, omitted observer, normalization, nonfinite repair, inert/layout-only maintenance, invalid/mismatched/repeated pairs, nonzero wrong-frame rejection, overlapping owner tokens, real child-deferred wheel routing, scrollbar keyboard/drag, and copied payload lifetime. Existing Scrollable, virtual widget and MessageScroller tests remain separate regression evidence. No completion callback, virtual-window rerender, precision conversion, bridge producer or foreign-language handler is introduced. Bindings retain their existing manual notification allowlists. This slice is not full-family or 78-family parity. ## Styled composition ```c cui_scroll_event_scope scope = {0}; if (cui_scrollable_begin_events(ui, owner, theme, &state, options, &scope)) { /* Compose ordinary child content here. */ cui_scroll_event_result result = cui_scrollable_end_events( ui, owner, theme, &state, options, &scope, (cui_scroll_handler){scrolled, &last}); (void)result; } ``` Styled begin's bool is successful composition admission, not Base's changed bool. False means no new boxes/pair were opened and no end is required. True always requires end, including unchanged, disabled, inert and layout-only submissions. Do not condition end on offset change. Use the same effective options/theme/state and ancestry across the pair; Styled's legacy previous-frame auto-measure resolution still runs at its original begin/end points. Styled end executes the existing mutable `end_ex` once: child-deferred wheel reduction, current viewport translation, scrollbar paint and owner box closure. Only afterward does it freeze final offsets, consume the token and invoke the observer. It never calls the Base event finalizer, so there is no repeated finish or double notification. Counts/normalization/metadata/passive suppression and callback mutation/lifetime rules are the same as Base. `valid` describes admitted pairing and finite final state, not transactional painting success; existing layout errors are retained and do not undo already-required balancing. The token now distinguishes Base and Styled pairs. Cross-layer finalization is rejected before reducer or box effects: Base finish cannot consume a Styled pair, and Styled end cannot close boxes for a Base pair. Correct finalization is still required after a rejected attempt. The added private layer bit extends the **unreleased** scope layout; rebuild consumers rather than mixing old objects. No legacy public layout changed. Styled tests compare legacy/new draw command geometry/colors, child/sibling bounds, semantics, consumed input and final state; exercise deferred child routing, net-zero and missing observers, disabled/passive normalization, cross-layer/owner/ repeated-token rejection, keyboard and scrollbar drag, and copied payload lifetime. The bounded strict Release and ASan/UBSan harnesses also run the Base event and legacy scroll/virtual/message tests. Sanitizer proof reuses prebuilt instrumented Core/software archives; it does not claim a fresh full-project sanitizer rebuild. --- ## Native SDK contextual text build Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SDK_TEXT_PARITY.md # Native SDK contextual text build Native Go and Rust SDK builds now enable the same `CUI_TEXT_BIDI` implementation as the default canonical native text target. The generated minimal SDK builds `cui_bidi` from `src/text/cui_bidi.c` and pinned SheenBidi unity objects, then links it into `cui_text`. The generator copies the pinned dependency manifest, complete SheenBidi headers/sources/license and local patch pin. Portable SDK builds retain their previous dependency scope; native mode enables this additional analyzer. Go native mode defines `CUI_TEXT_BIDI`, supplies the private SheenBidi header paths, and compiles text, analyzer and SheenBidi in separate generated translation units. `SB_CONFIG_UNITY` belongs only to the vendor unit. That unit applies the exact four existing canonical vendor warning exceptions with a diagnostic push/pop: unused parameter/value/function and implicit fallthrough. CUI source warnings remain errors. Rust native packaging enables bidi in both staged SDK and canonical fallback builds; its static archive link order includes `cui_bidi` after `cui_text`. Before this change the SDK native build compiled only the legacy FreeType/HarfBuzz path. `cui_font_text_geometry_line` returned `UNAVAILABLE`, mixed-paragraph layouts were unavailable, and contextual colored drawing returned false without emission. This was a packaging build gap, not a separately documented native feature limit. Ordinary button smoke tests did not exercise it. The public text API still permits explicitly disabled bidi builds, with their documented legacy behavior. Run the comparison with host development packages for SDL3 >=3.2, FreeType, HarfBuzz, CMake/Ninja and a C11 compiler: ```sh python tests/packaging/test_sdk_text.py \ --build-dir /tmp/cui-sdk-text \ --build-type Release \ --font /usr/share/fonts/noto/NotoSans-Regular.ttf \ --rtl-font /usr/share/fonts/noto/NotoSansHebrew-Regular.ttf \ --bindings ``` CI can substitute equivalent explicit font paths. Choose a primary face covering Latin but lacking Hebrew and a fallback covering Hebrew, so the fixture actually requires a second face. All three implementations receive the same files; the script records their SHA256 values and combined text source fingerprints. It checks freshly generated SDKs before building and compares canonical, Go SDK and Rust SDK results. Font names, exact metrics or raster values are not hardcoded; results must agree within this host. The current fixture specifically exercises Latin/Hebrew, not all Unicode scripts or every font. The fixture asserts contextual paragraph-relative byte identity, invalid UTF-8 boundary rejection without output mutation, caret/hit/selection geometry, four Hebrew selection clusters, actual odd-level RTL and fallback runs, nonzero shaped glyphs and two colored glyph groups with real coverage pixels. Missing bidi cannot silently pass: contextual status must be OK and colored emission must succeed. `--bindings` additionally copies Go/Rust modules into private consumers, builds native mode, and runs real SDL frames and click callbacks with mixed Latin/Hebrew button text and an explicit fallback. Only the repository invisible Xvfb runner launches those consumers; the C font fixture itself opens no display or window. No package publication or desktop-session fallback occurs. Validation covers native build fidelity for these text facilities. It does not claim complete Editor behavior, full native accessibility, all renderer/platform parity, or self-contained font/system-library distribution. Root integration must regenerate SDK receipts after canonical Text/SheenBidi/Dock patches and rebuild published artifacts; copying an old prebuilt bridge retains its old capabilities. --- ## SDL system appearance observation Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SDL_SYSTEM_APPEARANCE.md # SDL system appearance observation `cui_sdl3_appearance` returns a copied, portable `cui_platform_appearance` on the main thread. Creation queries the real SDL system theme and starts revision at 1. `cui_sdl3_poll` consumes system-theme notifications, re-queries SDL, increments the revision (saturating at UINT64_MAX), and requests Core redraw. Idle polling keeps the revision stable. Notifications contain no theme payload; repeated notifications may produce the same appearance with a new revision. Poll retains its usual continue/quit return contract. No callback or UI pointer is retained. `CUI_APPEARANCE_SYSTEM_THEME` indicates API/notification availability, including when the answer is `CUI_SYSTEM_APPEARANCE_UNKNOWN`. Unknown does not mean light: the application must choose its own fallback or retain its last known choice. There is no reduced-motion or high-contrast OS detection in this seam. Those preferences remain explicit application inputs. The adapter has no Theme link and does not change an application's explicit light/dark choice. SDL has a process-global event queue. The backend which polls a notification consumes it; this is not per-window multicast. Applications with several SDL backends should designate an event owner and distribute its copied appearance snapshot to other windows. Revisions are local to each backend instance and reset on recreation; do not compare them across instances or after saturation. A native Theme application can map the observation explicitly: ```c /* After normal cui_sdl3_poll(host, ui), on the main thread. */ cui_platform_appearance appearance; if (cui_sdl3_appearance(host, &appearance) && appearance.revision != last_observation_revision) { last_observation_revision = appearance.revision; if (appearance.appearance != CUI_SYSTEM_APPEARANCE_UNKNOWN) preferences.dark = appearance.appearance == CUI_SYSTEM_APPEARANCE_DARK; /* Application revision also accounts for explicit preference changes. */ if (preferences.revision != UINT64_MAX) preferences.revision++; cui_theme_host_update(&resolved, ®istry, selection, preferences, 16); } ``` Initialize the caller's revision sentinel to zero for first resolution; define an explicit unknown fallback in `preferences.dark`. `selection.mode` may remain `CUI_THEME_FORCE_LIGHT`/`CUI_THEME_FORCE_DARK`: observation updates the system preference input but does not overwrite that selection. Registry/Theme headers and linkage are only needed by the application using this example. Provenance: repository SDL fetch pin `7f3ae3d57459e59943a4ecfefc8f6277ec6bf540`, [SDL video source](https://github.com/libsdl-org/SDL/blob/7f3ae3d57459e59943a4ecfefc8f6277ec6bf540/src/video/SDL_video.c) updates system state before sending the notification; [pinned event definitions](https://github.com/libsdl-org/SDL/blob/7f3ae3d57459e59943a4ecfefc8f6277ec6bf540/include/SDL3/SDL_events.h) provide a common event without appearance data. [Official API documentation](https://wiki.libsdl.org/SDL3/SDL_GetSystemTheme) requires main-thread use and SDL 3.2.0 or newer. Validation uses installed SDL 3.4.18. Driver/desktop support varies; this does not claim every OS discovers a known theme, or validate a physical desktop preference change. `tests/integration/test_sdl3_appearance.c` uses actual SDL dummy/software drivers, compares the initial observation with `SDL_GetSystemTheme`, queues two real SDL notifications, and checks monotonic revision/redraw, idle stability, null-output atomicity and destruction/recreation. It does not fabricate light/dark data. Integrator: register this test linked to `cui_sdl3` and SDL3; default builds remain unaffected when SDL is disabled. Generated distribution remains integrator-owned. ## Compiled native consumer `examples/system_theme/main.c` is a complete application, defaulting to Follow System with a light fallback for an initially unknown appearance. Later unknown observations retain the last known preference. Two custom named themes are loaded through the actual ThemeSet importer into owned bounded registry entries. Sidebar, content, palette status and three real buttons expose Follow System, Always Light and Always Dark. Notifications update the system preference while retaining an explicit mode choice; selecting Follow System later uses the newest observation. Application state must stay at a stable address because its registry borrows inline entry storage. State transitions reject stale generations, invalid enums and revision overflow without applying partial changes. The static scene blocks on `SDL_WaitEvent(NULL)` when Core needs no redraw. SDL leaves the notification queued for the adapter to dispatch; there is no periodic polling spin. A finite `--frames` mode deliberately renders consecutive frames for reproducible smoke/capture and does not wait. An application adding timed animations must replace indefinite waiting with its earliest animation deadline. No reduced-motion/high-contrast OS values are manufactured. Example manual build from the configured native tree (root owns target registration): ```sh cc -std=c11 -Wall -Wextra -Wpedantic -Werror -Iinclude \ $(pkg-config --cflags sdl3) examples/system_theme/main.c \ build/libcui_sdl3.a build/libcui.a build/libcui_text.a build/libcui.a \ build/libcui_bidi.a $(pkg-config --libs sdl3 harfbuzz freetype2) -lm \ -o build/system_theme build/system_theme --font /usr/share/fonts/noto/NotoSans-Regular.ttf xvfb-run -a build/system_theme --font /usr/share/fonts/noto/NotoSans-Regular.ttf \ --frames 3 --capture build/system-theme.bmp ``` `tests/integration/test_system_theme_app.c` compiles the same original example state/frame functions with its native entry point disabled. It tests actual Core button activation, palette changes, unknown/stale/invalid observations, explicit modes and bounded revision failure. Link it only to `cui`; the headless translation excludes SDL headers and native entry-point code, so it remains portable and can run under WASI. Native Xvfb smoke verifies the compiled renderer and actual font capture; a physical desktop preference event remains outside this validation. The adapter's queued SDL notification test covers the notification path. At the adapter revision saturation boundary, the example still accepts a changed appearance with the same UINT64_MAX observation revision. Identical saturated observations remain idle. The separate application preference revision is checked before every transition; if that sequence itself reaches UINT64_MAX, further changes reject atomically and the native entry point exits with its update error. Repeated equal appearances at saturation cannot reveal distinct OS notifications. --- ## RadioGroup selection notifications Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SELECTION_EVENTS.md # RadioGroup selection notifications `cui_selection_events.h` and `cui_radio_group.h` add synchronous Base/Styled RadioGroup CHANGE observers. [Select observers](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SELECT_EVENTS.md) have their own guide; [Combobox observers](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMBOBOX_EVENTS.md) preserve their own reducer-phase ordering. No bridge/binding selection allowlist or uniform family coverage is implied. ```c #include static void selection_changed(void *user, const cui_selection_change *change) { cui_id *last_seen = user; *last_seen = change->value; } /* Inside an active frame; items, selected and focus_state are app-owned. */ static cui_radio_group_event_result choices(cui_context *ui, const cui_theme *theme, const cui_radio_group_item *items, size_t count, cui_id *selected, cui_radio_group_state *focus_state, cui_id *last_seen) { return cui_radio_group_events(ui, 10, theme, items, count, selected, focus_state, (cui_radio_group_options){.vertical = true}, (cui_selection_handler){selection_changed, last_seen}); } ``` `cui_base_radio_group_events` has the legacy Base arguments followed by a `cui_selection_handler`; it draws nothing. `cui_radio_group_events` similarly appends the handler to the Styled arguments. Return `.legacy` retains the original `valid/requested/changed/tab_stop` meanings. `.events` reports preflight `valid`, active `submitted`, observer invocation `change_count`, and `count_overflow`. Missing observer preserves normal value mutation and reports zero callbacks. Counts saturate at `SIZE_MAX`; dispatch continues. Disabled controls can submit but emit no notifications; inert/layout-only submissions emit none. Selection remains caller-owned through `cui_id *selected`. Without old `options.on_change`, eligible input writes that value. With it, the old synchronous callback still requests an item and may accept, reject or assign another value. Its `change_user` remains independent of the observer user. The observer runs immediately after that old operation only when the actual value changed. Rejection without change, already-selected activation, focus-only changes, and external assignments emit no CHANGE. No new callback can veto the operation. Later eligible events read current owner state; this is not the immutable entry-value policy of controlled Check. The pointer-free `cui_selection_change` copies `previous`, actual post-operation `value`, attempted `item`, reason ACTIVATION or NAVIGATION, and `cui_component_event_metadata event`. Metadata kind is CHANGE and `event.target` is the public RadioGroup ID. RadioGroup preserves legacy semantic registration after reduction, so Core accepted activation snapshots are unavailable before the old callback. This facade deliberately omits HAS_ACTIVATION for every path. It freezes only genuine frame/index/source facts from the triggering event before callback consumption; pointer-up, keyboard and accessibility event types establish their respective source, without copying/inventing pointer coordinates, touch details or an accessibility activation snapshot. Navigation likewise has no activation snapshot. [Shared metadata](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMPONENT_EVENTS.md) documents presence flags and context-local identities. Dispatch follows the existing reducer event order, then existing semantics/paint. A payload captures the transition before the observer runs. Observer writes to the owner affect later input and painting, but do not recursively synthesize notifications. Legacy `.changed` retains its existing operation comparisons; it is neither a count nor proof that the final value differs from frame entry. Do not perform the same side effect through both callback and result inspection. Handler, user and payload are borrowed only during synchronous submission; copying the pointer-free payload preserves it beyond frame/context lifetime. Keep caller arrays, active state, users and render resources alive for their existing submission/render boundaries. Callback changes to copied options/handler descriptors affect later invocations. Consuming later input changes later eligibility. Schedule removal/teardown in application state and perform it after submission/frame completion: context destruction, freeing active state/resources, and recursive same-frame submission during callbacks remain unsupported. No runtime destruction guard, queue, scheduler or routing change is added. `tests/unit/test_selection_events.c` exercises real Base and Styled reducers, owner rejection/acceptance/redirection, per-event navigation transitions, missing observers, accessibility source/index facts frozen before legacy consumption, omitted activation evidence, compound identity, consuming later input, disabled/passive suppression and copy lifetime. Legacy RadioGroup suites remain compatibility checks. Native tests use an invisible display: ```sh python scripts/test_local.py --build-dir build -- -R 'selection_events|radio_group' ``` Module registration, generated API indexes/distributions and bindings are integrator-owned. Typed RadioGroup requests, Select/Combobox notifications, query-edit events, same-item confirmation events, popup lifecycle and multi-selection remain outside this slice. --- ## Select selection notifications Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SELECT_EVENTS.md # Select selection notifications `cui_select_events` adds a synchronous post-mutation CHANGE observer to single-selection Styled Select. Existing `cui_select`, List, Menu, Combobox and multi-select APIs retain their behavior. Shared payloads come from [selection events](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SELECTION_EVENTS.md); this is not uniform coverage of selection families or a bridge/binding typed-selection allowlist. ```c #include static void changed(void *user, const cui_selection_change *change) { cui_id *last_observed = user; *last_observed = change->value; } /* During active composition; owner keeps selected and popup between frames. */ static cui_select_event_result account_select(cui_context *ui, const cui_theme *theme, const cui_choice_item *items, size_t count, cui_id *selected, cui_choice_popup *popup, cui_id *last_observed) { return cui_select_events(ui, 2, theme, cui_string("Account"), cui_string("Choose"), items, count, selected, popup, (cui_choice_popup_options){.viewport = {0, 0, 640, 480}}, (cui_selection_handler){changed, last_observed}); } ``` Initialize the popup once with `cui_choice_popup_init` and a stable nonzero popup ID. Existing item ID, popup state, viewport, theme and caller-array lifetime requirements apply. `cui_select_events` appends a `cui_selection_handler` to the existing Select arguments. It returns `cui_select_event_result`: `.legacy_changed` is the original final selection comparison, and `.events` contains preflight `valid`, active `submitted`, `change_count` of actual observer calls, and `count_overflow`. Missing observer preserves ordinary writes and reports zero. Counts saturate at `SIZE_MAX`; callbacks continue. Disabled controls may submit but emit no CHANGE; inert/layout-only ancestry emits none. Later rendering errors remain possible after successful preflight. Select directly mutates `*selected`; this callback notifies an applied transition and cannot reject it. Every actual option-selection transition emits once, synchronously at its existing list reducer point. The payload copies previous and actual new selection, attempted `item`, ACTIVATION reason and common metadata. No label or borrowed query text is included. Zero/invalid selection remains caller-owned; filtering/reordering does not convert IDs to indices. Same-item activation can close the popup without CHANGE. Focus navigation/typeahead, trigger open/close, outside dismissal and external model assignments do not emit selection CHANGE. The list processes its complete eligible input batch before Select closes its popup. A→B→A emits two notifications, while `.legacy_changed` remains false. Do not treat that bool as an event count or generate another callback from it. Observer owner writes affect later events and final painting/result in the existing pointer-owned model; they do not recursively synthesize notifications. Consuming later input changes its eligibility. Popup closing still occurs after the list pass, rather than immediately after the first callback. `event.target` is the Select trigger ID. Genuine accepted activation evidence is copied only if Core already makes it available; `event.activation.target` then stays the actual child ID. The existing list normally registers option semantics after reduction, so HAS_ACTIVATION is absent at this seam. Preserve that registration timing. The fallback copies only actual frame/index and source proven by the triggering pointer-up, keyboard or accessibility event type. It does not invent a pointer position, touch snapshot, accessibility activation snapshot or an accepted activation merely from source. Presence flags, not zero-filled storage, establish evidence. See [shared metadata](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMPONENT_EVENTS.md). Handler/user/payload are borrowed synchronously. Pointer-free payload copies survive later frames and context destruction. Keep active item arrays, popup/selected storage, users and rendering resources alive for their existing boundaries; changing copied options/handler affects a later call. Schedule removal/teardown for after submission/frame completion. Context destruction, freeing active state/resources and recursive same-frame submission during callbacks remain unsupported; no runtime destruction guard or new queue is added. `tests/unit/test_select_events.c` uses real Select input to verify pointer/touch/key transitions, accessibility focus without selection and unsupported option activation, multiple changes returning to entry, same-item close, missing handler, owner updates, consumed later input, disabled/inert/omitted submission, legacy coexistence, copied payload lifetime and truthful evidence absence. Existing `test_choice.c` remains the regression suite for list callbacks, popup focus/close, scrolling and custom render slots. Native tests must use the private display wrapper: ```sh python scripts/test_local.py --build-dir build -- -R '^(select_events|choice)$' ``` [Private plumbing checkpoint](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SELECT_EVENTS_SLICE.md) explains the reducer seam. No new public List observer, Base Select, controlled selection request, confirmation/lifecycle event is implemented by this Select facade. [Combobox observers](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMBOBOX_EVENTS.md) have a separate ordering contract. Accessibility boundary: current Core permits FOCUS for OPTION but its ACTIVATE role allowlist excludes OPTION. Select therefore supports accessibility focus followed by explicit keyboard navigation/selection, not a newly enabled accessibility option-activation path. Accessibility focus alone also leaves the retained list active cursor unchanged; the tested fallback explicitly navigates before Enter rather than claiming focused-option confirmation. Tests assert these boundaries without changing Core or claiming positive activation coverage. --- ## Settings applied events Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SETTINGS_EVENTS.md # Settings applied events Include `cui/cui_settings_events.h`. `cui_settings_events` preserves the existing Styled Settings operation and adds navigation and built-in value observers. `on_navigation` reports applied page/group selection, not an owner-rejectable request. Missing observers permit all legacy work and ignore user. Legacy Base filter/reset helper and field callback contracts stay unchanged. ```c static void navigation_changed(void *user, const cui_settings_navigation_change *change) { bool *save_navigation = user; /* unrelated application flag */ *save_navigation = true; /* Copy *change to retain its pointer-free page/group and metadata values. */ } /* During UI submission with existing caller-owned pages/state/options: */ /* cui_settings_events(ui, id, theme, pages, count, &state, options, (cui_settings_handler){.on_navigation = navigation_changed, .user = &save_navigation}); */ ``` The payload contains `previous_page`, `previous_group`, `page`, `group` using source indices; `CUI_SETTINGS_NO_GROUP` selects the page as a whole. Filtering does not renumber indices. Reordering caller arrays changes their meaning. Notifications run immediately after the existing navigation writes, pending-group scroll policy and invalidation, before content/filter-scroll resolution and paint. A group callback can see pending scroll true even when content clears it later. A same-pair activation can still restore pending scrolling without emitting CHANGE. Defaults, query reconciliation, search/filter repair, scrolling, resizing, reset and field callbacks never become navigation events. `result` is the exact legacy aggregate `cui_settings_result`, including filter selection repair. `navigation_count` counts actual observer calls, saturating at SIZE_MAX with `count_overflow`. Real A→B→A navigation emits both transitions even when the final pair equals entry; the legacy selection flag is preserved. Sidebar processes items in traversal order, each scanning its own inputs in order. Across items callback input indices therefore need not increase. This facade does not reorder dispatch into global input order or replay reducers. Metadata targets the Settings compound. The private navigation descriptor matches each existing Sidebar callback to its next actual same-trigger activation; accepted snapshot evidence is frozen before writes when available. Copied `activation.target` retains the original derived page/group navigation ID. If no accepted snapshot is available, only actual frame/index/type facts are attached. An unexpected callback/ activation mismatch has proven frame only, UNKNOWN source and no index/activation. Presence flags are authoritative. No early semantic registration, consume, extra reduction or invented activation is used. Passive/layout-only/inert submissions produce no observation while retaining legacy maintenance and rendering behavior. Sidebar TREEITEM accessibility ACTIVATE is not currently supported by Core; this facade adds no accessibility routing or promise beyond existing Sidebar behavior. New admission requires nonnull context/theme/state, a nonzero compound ID, and a page array when count is nonzero. Old validation/filter behavior then applies. Handler/user/payload pointer are borrowed synchronously. Do not mutate/rebind/free active page/group/item arrays, values/editors/states, dropdown workspace, labels, callback resources, input or context, or recursively submit UI in the observer. Unrelated application flags may change; defer removal/omission/teardown until outer return plus renderer consumption. Legacy custom search/render/change/reset callbacks keep their timing and must preserve resources needed by the remaining old operation. Navigation and built-in scalar/text changes, including explicit resets, are typed here. Search and viewport observers remain outside this facade. C bridge and Python/JS/TS/Go/Rust still use their existing Settings callback/polling paths; no per-navigation foreign callback or synchronous request is implied. Focused C tests do not establish browser or binding parity. ## Built-in scalar fields Set `on_boolean`, `on_number` and/or `on_choice` in `cui_settings_handler` for the corresponding `cui_settings_bool_change`, `cui_settings_number_change` and `cui_settings_choice_change`. They share the borrowed handler user pointer. Each payload identifies `page`, `group`, `item` source indices and the derived `field_id` (`cui_settings_part_id(root, page, group, item, 24)`). Metadata target remains the Settings compound. Payloads are pointer-free and copyable by value. Boolean covers built-in Switch and Checkbox; Number carries actual doubles; choice carries owner choice IDs for both Menu-backed dropdown and legacy Select. Custom render overrides bypass these observers even when host rendering edits an owner. Scalar adapters do not invent requests, COMMIT or per-input events. Text and RESET observations have the separate contracts below. Capture occurs immediately before one existing built-in adapter. The adapter runs once, records the existing first edit error, and invokes the old item `on_change` at its original point. Only then does the typed observer compare/read the actual final owner. A legacy callback restoring entry value produces no typed CHANGE; redirecting it reports the redirected value. Callback count does not replay effects. Two nested edits ending at entry produce no aggregate CHANGE. Existing Switch may coalesce several activations into one flip; the facade preserves that behavior. Each adapter emits at most one typed callback in existing content order. Scalars are **aggregate notifications**, unlike per-navigation transitions. `boolean_count`, `number_count`, `choice_count` independently count actual calls, saturating at SIZE_MAX and setting shared `count_overflow`. Missing typed handlers preserve all old writes/callbacks. Disabled fields and passive/layout-only/inert submissions retain legacy maintenance, including Number bounds/last-value writes and old callbacks, but emit no new typed scalar EDIT notification. Enabled real final owner changes can be notified even with a nested edit error; errors and invalid flags are preserved, never used as an artificial change gate. Scalar EDIT metadata has a proven nonzero active frame, UNKNOWN source and no input index/activation. A whole adapter and its legacy callback may combine inputs or apply bounds without input, so a unique causal event cannot honestly be inferred. An enabled bounds adjustment is an applied change, not proof of user interaction. Number equality treats both NaNs as unchanged and signed zeros as equal. Payload `previous_finite` and `value_finite` describe the actual numeric values, not their acceptance by Number. Settings initially validates finite owners, but old callbacks can redirect a valid edit to infinity/NaN or change a later field after validation. These facts remain visible; the observer does not clamp again, repair the owner, resynchronize the draft or rewrite `number_state.last_value` after the callback. Settings' existing extra bounds/last-value pass stays before old `on_change`; therefore the callback's final owner can intentionally differ from draft/last_value until later old synchronization. Invalid nonfinite owners may fail the next filter. Old callbacks must leave observed scalar owner pointers readable through typed notification. The new observer cannot mutate active owners or other active model resources; use unrelated flags and defer teardown. Entry is captured at each field, not at Settings-call entry, so earlier host changes are not independently reported. Reset-button effects are described separately below. This extends the new C structs and requires rebuilding consumers with this header; existing legacy Settings options/state/result layouts and function remain unchanged. Built-in Input EDIT observations use `handler.on_text` and `result.text_count`. They compare committed revisions immediately around the old adapter and its old `on_change` callback, then report once at most. Two inputs in one adapter remain one notification; callback redirects and byte-net-zero edits still notify when the revision differs. IME preedit, selection and unchanged revisions stay silent. An earlier successful edit is observable even if a later input reports an error. Missing observers preserve editing. Disabled, passive and inert submissions do not notify. Custom renderers remain outside the built-in observer contract. `cui_settings_text_change` includes before/after revision and byte counts, field ID and source page/group/item indices. `text` is final committed UTF-8 borrowed only for the callback; no previous text is copied internally. Use `cui_component_event_copy_utf8(event->text, limit, storage, capacity, &owned)` and check for `CUI_COMPONENT_EVENT_COPY_OK` to retain it. Settings supplies no secure or masked Input configuration, so this payload is actual committed text without implicit redaction. Metadata is proven active frame plus UNKNOWN cause, without an invented input index, activation or submit. The editor and its storage must remain live and unchanged by observers until the outer call and renderer finish. Bool, number, choice and text payloads now expose `reason`, currently EDIT. The explicit reset helper reports RESET as described below. These **unreleased event structs** changed size: rebuild all C consumers. Legacy Settings options/state/results and entrypoints are unchanged. `cui_settings_reset_page_events(root, page_index, page, query, handler)` is the explicit programmatic reset facade. `reset` is the exact old helper result; `boolean_count`, `number_count`, `choice_count` and `text_count` count actual typed callbacks. Root must be nonzero; page must be supplied; `page_index` is your real source page index. Metadata has SOURCE_PROGRAMMATIC only, without input index, frame or activation. Payload target is root; field IDs use the original item index. Each matching built-in is reset once, its old `on_change` runs at its old time, then the observer compares the final owner/revision. Disabled fields are included. Same-value defaults still run old callbacks but produce no typed callback unless that callback changes the final value. Number equality and finite flags match EDIT. Text compares revision even if final bytes equal entry; UTF-8 is borrowed. No draft, Number bounds or `last_value` synchronization is added by the helper. Custom `reset` wins, returns legacy success, does not call old `on_change`, and has no typed observation, even if the item has scalar pointers. Custom rendering alone does not disable a built-in reset. Missing defaults and unmatched items are silent. A failed text replacement preserves its old failure/no-callback behavior and later items still run. A malformed later group returns `reset=false` after prior effects; counts and notifications remain, with no rollback. Missing handlers preserve all old work. The old helper remains available unchanged. The Styled reset button uses this same reset operation once, at its original place before field submission. RESET callbacks therefore precede any ensuing EDIT callbacks. For example, a Number default of 20 with maximum 10 reports RESET to 20, then the old adapter bounds pass reports EDIT to 10; no bounds or draft work moves. Reset success and old callback ordering remain unchanged, including same-value callbacks and custom-reset omission. Counts in `cui_settings_event_result` include both reasons and saturate independently. UI reset metadata is frozen before the first reset write. Exactly one matching activation with a genuine accepted snapshot retains its source/index/activation; `activation.target` stays the reset button ID while metadata target is Settings. Multiple matching activations, or unavailable snapshot evidence, get only the proven frame with UNKNOWN cause. The old Button aggregate remains one reset; input is never replayed. Passive/layout-only/inert calls preserve legacy work but do not notify. Disabled **fields** remain eligible for an explicit enabled reset action. No reset activation/lifecycle/COMMIT event or rejection semantics is introduced. --- ## Named shadow presets Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SHADOW_PRESETS.md # Named shadow presets `cui_shadow_preset_layers` copies the pinned public Styled DROP presets into caller storage. `cui_set_shadow_preset` applies the same list to the open box and replaces its entire mixed DROP/INSET list. `CUI_SHADOW_NONE` clears both kinds. A zero/default style has no implicit shadow. ```c cui_begin_box(ui, card_id, card_box); if (!cui_set_shadow_preset(ui, CUI_SHADOW_MD, card_radii)) { /* Handle rejected layout state or invalid radii. */ } /* Card content. */ cui_end_box(ui); ``` The factory needs capacity for the selected list, at most `CUI_SHADOW_PRESET_MAX` (two). It writes the count and exactly the selected layer span; unused elements remain untouched. Unknown enums, insufficient capacity, capacity multiplication overflow, NULL required pointers, and count-output overlap with the written layer span reject before writing either output. NONE accepts a NULL layer buffer with capacity zero and writes only count zero. The caller supplies valid, suitably aligned storage. The factory retains no pointers and allocates no memory. ```c cui_drop_shadow layers[CUI_SHADOW_PRESET_MAX]; size_t count; if (cui_shadow_preset_layers(CUI_SHADOW_SM, layers, CUI_SHADOW_PRESET_MAX, &count)) { cui_box_shadow mixed[CUI_SHADOW_PRESET_MAX]; for (size_t i = 0; i < count; ++i) mixed[i] = (cui_box_shadow){.layer = layers[i], .kind = CUI_BOX_SHADOW_DROP}; cui_set_box_shadows(ui, mixed, count, card_radii); } ``` Both existing setters copy their lists; caller stack storage may be reused after a successful setter. The render commands retain their existing value ownership and renderer lifetime contracts. NONE follows the existing zero-count setter: radii do not affect empty paint. An invalid preset leaves an already assigned list unchanged. `cui_box_shadow_init(offset_x, offset_y, color, &out)` reproduces the explicit source constructor: DROP, zero sigma, zero spread, and the supplied offsets/color. It accepts finite offsets in [-4096,4096] and leaves output unchanged on rejection. Callers can then set bounded sigma/spread or choose INSET through the existing mixed-list API. This is an explicit constructor, not a default style layer. | Preset | Ordered (offset_y, sigma, spread, black alpha byte) | | --- | --- | | NONE | empty | | 2XS | (1, 0, 0, 13) | | XS | (1, 2, 0, 13) | | SM | (1, 3, 0, 26), (1, 2, -1, 26) | | MD | (4, 6, -1, 26), (2, 4, -2, 26) | | LG | (10, 15, -3, 26), (4, 6, -4, 26) | | XL | (20, 25, -5, 26), (8, 10, -6, 26) | | 2XL | (25, 50, -12, 64) | Offsets on x are zero, RGB is black, all layers are DROP, and all distances are logical pixels. The sigma values are the source public macro values, without the component-private CSS blur halving. CUI rounds source Hsla alphas .05/.1/.25 to nearest 8-bit bytes 13/26/64. Canvas global-alpha composition has renderer-specific byte rounding; browser probes compare two-layer paint with independent opaque Canvas images and bound the one-layer difference from ideal arithmetic. Native software assertions retain exact quantized pixels. It therefore does not claim floating Hsla or native upstream shader pixel identity. Ancestor opacity uses the existing Core command alpha conversion; interaction-disabled semantics alone do not remove the assigned decoration. Source: pinned upstream-component0.7.1 `87d10ae5e1299d1be18670a37570c5402f952e34`, dependency `upstream-pre-macros0.3.8/src/styles.rs:384–490`; explicit constructor `upstream-pre0.3.8/src/style.rs:349–393`. Source fixture records the exact macro file hash. These are public named presets; private popover, toast, and raised-tab consumers are separate appearance work. The focused native test checks all ordered source tuples, constructor bounds, output transactions, mixed-list replacement, software pixels below a translucent surface, ancestor opacity, and unchanged decoration under disabled semantics. The standalone browser fixture exercises all eight presets with the actual pure-C WASM raster and Canvas at DPR1/2, including literal one/two-layer composition and opacity. Existing renderer capability, budgets, mask culling, cache preparation, and DROP/INSET rendering contracts remain applicable. This convenience slice does not certify the full shadow family, native upstream antialiasing/color identity, or the appearances of unrelated component owners. --- ## Sidebar ancestral clipping Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SIDEBAR_CLIPPING.md # Sidebar ancestral clipping Scrolled sidebar SVG icons could overlap the fixed header/footer even though the body viewport already clipped ordinary rows and text. The pinned Clay renderer paints absolute descendants as separate floating roots. Its synthetic scissor command has `userData == NULL` and the bounds of only the nearest clipping ancestor (often a menu row). The body scissor belongs to another root and is no longer active when that icon is painted. Intersecting the renderer's current clip stack alone therefore cannot recover the missing body constraint. Core draw conversion now resolves that synthetic command through the pinned Clay floating-root metadata and its existing derived command ID. It intersects the nearest clip bounds with all clipping ancestors recorded in the CUI node chain. Ordinary scissor commands receive the same intersection. Clip push/pop structure, draw order and icon bitmap geometry remain unchanged; a completely hidden descendant receives a zero-area clip. No backend, Sidebar layout, public API or vendored Clay changes are required. Explicit detached portals retain their escape behavior: their CUI parent chain ends at the portal root, so descendants inherit clips inside the portal but do not inherit the original sidebar/body clip. Absolute children remain attached and inherit the full chain. This follows the same ancestry already used for CUI hit bounds, bringing icon paint clipping into agreement with hit testing. ## Regression evidence `test_sidebar` renders actual registered folder SVG bitmaps through a real Sidebar with fixed header/footer, ten menu rows and an expanded nested folder. It samples nonzero source alpha at destination pixel centers under the emitted clip stack and rejects any visible icon pixel outside the body viewport. It also checks visible text bounds and clicks hidden rows above/below the viewport. Expanded and icon-collapsed sidebars are tested at two scroll positions. The final test fails against the original `ddd0ae3` Core at the assertion that a visible folder pixel lies within the viewport's vertical extent, and passes with the conversion fix. A rect-only regression would miss this separate-root case. `test_core` independently checks an absolute child nested under an oversized clipping row: its effective clip must equal the outer viewport intersection. The same scene opens a detached portal and an absolute child inside it outside the original viewport, and verifies that its own clip remains visible. The browser regression builds the actual WASM gallery and tracks the Files folder bitmap's nonzero alpha through its emitted clip stack while scrolling in expanded/collapsed modes. It checks top/bottom leakage without treating the fixed header toggle or footer settings icon as body content: ```sh python3 scripts/build_web.py --output build/web uv run tests/web/test_sidebar_clipping.py --directory build/web --chromium /path/to/chrome ``` Validation on this branch: strict-warning native build; 93/94 CTests pass (the only failure is the expected stale generated `dist/cui.h`, owned by the integrator); ASAN/UBSAN Core and Sidebar tests pass; the browser regression passes against pinned Zig 0.16.0 output and Chromium. The integrator must regenerate the distribution header before publication. The test requires Playwright 1.58.0 and an installed Chromium fixture; it does not install a browser. The metadata lookup intentionally targets the pinned Clay implementation already used privately by Core. A Clay version update must retain or revise the synthetic-scissor lookup and rerun these paint-stack/pixel and detached-portal regressions. This fix does not change viewport sizing, virtualization estimates, row layout, portal focus behavior, or scrolling policy. --- ## Sidebar row activation events Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SIDEBAR_EVENTS.md # Sidebar row activation events This additive C slice provides Base and Styled **row activation notifications** and typed item expansion and collapse requests. Header/footer actions remain later slices. Legacy Sidebar callbacks, results, layouts and retained cache lifetimes are unchanged; no component parity or binding coverage is promoted. ```c #include static void opened(void *user, const cui_sidebar_activation *event) { cui_id *last_item = user; *last_item = event->item; /* Application-owned output, not active item storage. */ } static void render_menu(cui_context *ui, const cui_theme *theme, const cui_sidebar_menu_item *items, size_t count, cui_id *last_item) { cui_sidebar_menu_event_result result = cui_sidebar_menu_events( ui, 100, theme, items, count, false, (cui_sidebar_item_handler){.on_activate = opened, .user = last_item}); (void)result; } ``` Call the render helper during normal frame composition. The existing `cui_sidebar.h` also exposes the new declarations. The Base entrypoint is `cui_base_sidebar_item_events(ui, item, collapsed, level, handler)` and returns `cui_sidebar_item_event_result`, containing the unchanged legacy `control` result. The Styled menu returns `cui_sidebar_menu_event_result`, not one row's open state. `valid` means argument/tree validation succeeded. Styled `submitted` is the old menu submission bool, including inert/layout-only composition; neither flag implies an activation. `activation_count`, `request_count` and `change_count` count actual typed observer calls, zero for each missing observer. Saturating counts expose `count_overflow`. Each `cui_sidebar_activation` contains pointer-free common metadata, actual `item` ID and nesting `level`. Its kind is ACTIVATE, including repeated invocations of the same row. Base metadata targets the row; Styled metadata targets the public menu ID. A copied activation snapshot, when available, retains its original row target. Do not sort by event index: Styled reduces/paints in item traversal order, so input indices can decrease across rows. Every actual row invocation notifies; there is no aggregate-last reconstruction or after-frame dispatch. Evidence is frozen at the existing row branch **before** expansion or legacy callbacks. Existing expansion write/request and `on_expand` run first, then existing `on_activate`, then the typed observer synchronously, before final semantics/paint. There is no second reduction, early semantic registration, acceptance decision or observer veto. Legacy owner redirection of uncontrolled state is preserved. A missing old activation callback does not prevent typed notification; a missing typed handler does not prevent normal legacy mutation. Caret-only expansion is not row activation. Defaults/initialization, disabled rows, inert/layout-only work and omitted children do not generate activation notifications. Real pointer, touch and keyboard paths use genuine accepted snapshots when available. The existing Core has a tested accessibility-focus/Enter transition where legacy row activation exists but a copied accepted snapshot is unavailable. The fallback carries only genuine local frame/index and explicit input source; HAS_ACTIVATION remains absent. Presence flags alone establish evidence; empty snapshot fields prove nothing. TREEITEM accessibility **ACTIVATE is unsupported** and rejected at queue ingress. Accessibility FOCUS followed by keyboard activation is tested separately; this does not establish accessibility activation parity. No Core allowlist or routing changes. Existing callback input mutation remains existing behavior. In particular, consuming later ordinary mouse input does not cancel its cached activation at this seam; explicit `cui_cancel_event_activation` does. Tests preserve both outcomes. The new observer does not reinterpret consumption as a notification veto. ## Expansion ownership and order Set `on_expand_request` and/or `on_expand_change` on `cui_sidebar_item_handler`. Both receive `const cui_sidebar_expansion_event *` containing copied metadata, actual item ID/level and `previous`/`value` booleans. These handler and result fields extend an **unreleased branch API**: rebuild consumers together with the library. Zero and designated initializers remain source compatible; legacy Sidebar public layouts are unchanged. With `item.expanded != NULL`, the existing operation remains a controlled request. The legacy `on_expand` runs first, followed by typed REQUEST with the frozen previous owner value and requested next value. The component never assigns owner storage. The typed request handler may synchronously assign **that explicit expanded bool**; rejection simply leaves it unchanged. Each later input rereads actual owner state. Repeated rejected toggles therefore request the same next value; accepted toggles alternate. Even if the legacy callback already accepts, the typed event remains a request, not a confirmed CHANGE. A click-to-open attempt already at open does not invoke either old or typed expansion callbacks. With `expanded == NULL`, the existing state write and old callback happen once. Typed CHANGE reports the actual final `state.open`, only if it differs from the frozen previous state. Legacy redirection back to the previous value emits no CHANGE, even though the old `expansion_changed` attempt flag remains true. Initialization, owner-only programmatic changes and maintenance do not notify. The typed CHANGE observer cannot mutate active state. For a row that expands, order is old expansion → typed expansion → old activation → typed activation. Caret-only expansion invokes no row activation observer. Metadata is frozen before old callbacks, even if they cancel the current input afterward. Base expansion target is the item ID and Styled target is the menu ID; copied activation.target remains the actual row or caret Button. Caret accessibility ACTIVATE is genuinely supported and tested separately from unsupported TREEITEM activation. Existing `disable_caret`, collapsed/omitted and passive policies remain; a disabled row does not implicitly disable its separate caret in the legacy API. ## Collapse toggle requests `cui_base_sidebar_toggle_events(ui, id, options, handler)` and `cui_sidebar_toggle_button_events(ui, id, theme, options, handler)` return `cui_sidebar_toggle_event_result`. Its `activated` is the unchanged legacy toggle bool; `valid` records argument validation. `request_count` counts actual typed calls and `count_overflow` reports saturation. A valid inert/layout-only submission has no activation or request count. A missing handler still permits normal legacy work. Use a separate `cui_sidebar_collapse_handler` with `on_request`/`user`. The callback receives `cui_sidebar_collapse_request { event, previous, value }` with REQUEST metadata targeting the public toggle ID. For example: ```c static void collapse_requested(void *user, const cui_sidebar_collapse_request *request) { bool *owner_collapsed = user; *owner_collapsed = request->value; /* Optional acceptance of the request. */ } ``` The reducer starts a local bool at the entry `options.collapsed`, then flips that local bool for each existing activation. With entry false and three inputs, requests are `(false,true)`, `(true,false)`, `(false,true)`. The old `on_change` runs before the typed request for each activation. Both callbacks may assign an external owner collapsed bool, but **neither assignment redirects the active local flip sequence**. The caller supplies an updated owner value in a later submission. These are requests, not notifications of confirmed owner changes; no collapse CHANGE is emitted. Genuine metadata is captured before the old callback. The original semantics `expanded = !options.collapsed` and the Styled icon/paint also retain the entry snapshot for that submission, even after an owner accepts or rejects. The toggle has already claimed its same-ID mouse activations before callbacks; late explicit cancellation does not clear those claimed slots. Consuming an accessibility action still clears it, preserving existing Core behavior. No silent semantic/visual resynchronization, second reduction or aggregate reconstruction is introduced. The narrow permitted typed mutation is assignment of the external collapsed owner bool; active options/input/item storage and context teardown remain unsupported. Handler/payload copies have the same lifetime rules below. Tests compare old/new local value sequences, aggregate bool and Styled command geometry/colors; prove legacy-then-typed ordering despite divergent owner writes, entry-snapshot semantics, repeated requests, pointer/touch/keyboard/genuine Button accessibility, missing handlers, disabled/inert/layout-only work, invalid arguments, frozen current evidence after legacy consumption of accessibility activations, and copied metadata after context destruction. Header/footer observers are documented below. Handler, user and payload pointers are borrowed only during submission. Copying the pointer-free payload preserves it through later frames, omission and context teardown; IDs do not retain live rows. Typed observers may update unrelated application outputs, but, apart from the controlled expansion/collapse REQUEST assignments above, must not mutate active item arrays/labels/child state/input storage, recurse into UI composition, remove active storage or destroy the context. Context destruction during dispatch remains unsupported; there is no fake teardown guard. Defer structural changes and resource teardown until outer submission and renderer consumption finish. `tests/unit/test_sidebar_events.c` proves repeated/net-zero Base activations, legacy expansion/activation/typed order, old/new results and callback counts, pointer, touch, keyboard, rejected accessibility activation, focus+keyboard, missing handlers, legacy state redirection, caret exclusion, disabled/passive/omitted paths, nested levels, traversal with decreasing indices, preserved consume/cancel behavior and copied lifetime. Expansion tests cover controlled rejection/new-handler acceptance/legacy acceptance, repeated requests, actual changes and redirected net-zero suppression, precise callback order, frozen evidence after legacy cancellation, missing observers, passive work, genuine caret accessibility/touch and Styled forwarding. Styled legacy/new paint command types/bounds/colors are compared; this is scoped geometry/paint evidence, not full renderer parity. Existing Sidebar and Settings tests and strict C++17 header compilation also pass. Native CTest runs only through `python scripts/test_local.py --build-dir ` (private Xvfb). Bridge Sidebar has separate retained state and queued generic notifications. No Python/JS/TS/Go/Rust API automatically gains these immediate per-item notifications or synchronous expansion requests. SDK/module/export wiring is integrator work. ## Header and footer actions `cui_sidebar_header_events` and `cui_sidebar_footer_events` take the existing section options plus `cui_component_activation_handler` and return `cui_component_action_result`. There is no Base section counterpart. ```c cui_component_action_result result = cui_sidebar_header_events( ui, header_id, theme, header_options, (cui_component_activation_handler){on_header_action, app}); ``` Each actual activation freezes ACTIVATE metadata before the existing `options.on_activate`, then calls the typed observer. Repeated invocations notify separately. `activation_count` counts observer calls; a missing observer reports zero while legacy callbacks and content still run. A typed-only handler works without a legacy callback. `submitted` reports successful section composition, including inert/layout-only submissions; it does not imply an action. These GROUP surfaces set `pointer_activatable`: existing Core routing supports pointer/touch and accessibility ACTIVATE. The earlier pointer-only checkpoint wording was incomplete. No keyboard routing or new focusability is introduced. Legacy accessibility consumption can suppress later actions; already frozen current evidence remains intact. Handler/user/payload borrowing and unsupported active-context destruction follow the same lifetime rules above. No retained handler, queued foreign callback, or binding export is added. Focused tests cover both surfaces, repeated mouse activation, touch, genuine accessibility activation and consumption, old-before-new ordering, typed-only and legacy-only paths, omitted handlers, inert/layout-only work, invalid arguments, and copied payload lifetime. Existing Sidebar and Settings regressions remain part of the bounded verification. --- ## Simple Menu command notifications Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SIMPLE_MENU_EVENTS.md # Simple Menu command notifications `cui_menu_events` adds synchronous per-command notifications to Styled Simple Menu. It takes the same arguments as `cui_menu`, followed by a `cui_menu_command_handler`, and returns `cui_menu_command_result` from [MenuTree events](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MENU_EVENTS.md). Existing List options/layout, Select and Combobox observers, legacy Menu behavior and the 78-family manifest remain unchanged. This is not a DropdownButton facade or a binding API. ```c static void activated(void *user, const cui_menu_command *event) { cui_id *last = user; *last = event->command; } cui_menu_command_result result = cui_menu_events( ui, trigger, &theme, cui_string("Commands"), items, count, &action, &popup, options, (cui_menu_command_handler){activated, &last_command}); ``` Submit either the legacy or new Menu entry point once per frame. Opening the trigger emits no leaf command. Each accepted flat-list activation writes the caller's action and active cursor, runs existing List activation then confirmation hooks, and finally notifies the command observer. The command ID and input metadata are frozen before those callbacks. This private seam does not expose new public List callback fields. Command notifications are ACTIVATE, including repeated same-ID activation: A→A→B reports three commands even when the initial action was A. The full flat-list pass completes before Menu closes and restores focus. This differs from MenuTree's closing-command early return; forwarding does not transfer that policy. Owner updates during a callback can affect later reduction; consuming later events suppresses their subsequent handling. A notification cannot veto or roll back applied state. Missing handlers preserve normal mutation and closing with `command_count == 0`. `legacy_activated` retains the aggregate bool, even if a handler writes the action back to its original value. Counts saturate and overflow does not stop dispatch. `event.target` is the public trigger; `command` is the reducer's actual confirmed item. Real mouse/touch, keyboard and supported MENUITEM accessibility events retain their genuine source, frame and event index. Current registration follows reduction, so ordinary dispatch has no copied activation snapshot. No trigger-opening event, focused target or programmatic state write is invented as activation evidence. Existing flat-list non-pointer confirmation uses its active cursor; accessibility target identity does not independently replace that cursor. This slice preserves that behavior and does not claim complete accessibility parity. Flat descriptors do not gain MenuTree check/radio/submenu features. The payload is borrowed synchronously and pointer-free copies survive the frame/context. Keep descriptor/value/state/user/render storage alive through submission. Direct mutation of in-flight navigation, freeing active storage, recursive submission and context destruction during callbacks remain unsupported; defer removal/shutdown until submission/frame completion. Existing disabled/inert/layout-only, popup dismissal and scrolling invalidation rules apply. Existing custom row rendering remains in the same painting phase; a closing frame completes reduction without repainting the closed popup. [test_simple_menu_events.c](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_simple_menu_events.c) proves repeated A/A/B, complete-pass close timing, pointer/touch/key/accessibility commands, actual legacy-hook ordering and frozen command identity, owner writes/later consumption, missing/disabled/inert/omitted handlers, custom row rendering through old/new paths, scroll rejection and copied lifetimes. Legacy Choice plus Select/Combobox event tests protect neighboring reducers. Native validation uses the invisible wrapper: ```sh python scripts/test_local.py --build-dir build -- -R '^(simple_menu_events|choice|select_events|combobox_events)$' ``` The integrator registers the test and documentation exports; no generated artifacts or parity promotion are included. --- ## Controlled Slider events Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SLIDER_EVENTS.md # Controlled Slider events Include `cui/cui_slider_events.h` for `cui_base_slider_events`. This additive, drawing-free facade uses the existing controlled double-precision Slider reducer. Submit it inside a box with the same ID. The legacy `cui_base_slider_controlled`, `cui_slider_options` binary layout, phase timing and capture/presentation state remain unchanged. ```c static void position_request(void *user, const cui_component_slider_request *r) { double *owner = user; if (r->phase == CUI_SLIDER_UPDATE) *owner = r->requested; /* Accept. Leave unchanged to reject. */ /* COMMIT is a final proposal, not proof the owner accepted an UPDATE. */ } /* Persistent state: */ cui_slider_state drag = {0}; double position = 0.25; /* During submission inside a same-ID track box: */ cui_component_slider_result result = cui_base_slider_events( ui, track_id, cui_string("Position"), position, &drag, (cui_slider_options){.minimum=0, .maximum=1, .step=0.01}, (cui_component_slider_handler){position_request, &position}); ``` This header exposes the Base reducer. Use the separate [Styled facade](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/STYLED_SLIDER_EVENTS.md) for themed track/thumb rendering. Source bounds, clamping, step rounding, pointer capture and normalized float semantics match the old controlled reducer; requested values and owner snapshots remain double. ## Typed phases and owner decisions | Phase | Shared metadata kind | `requested` | Result count | | --- | --- | --- | --- | | BEGIN | LIFECYCLE | Current owner value at gesture/key start | `begin_count` | | UPDATE | REQUEST | Proposed clamped/snapped value | `request_count` | | COMMIT | COMMIT | Final proposed gesture/key value | `commit_count` | | CANCEL | LIFECYCLE | Gesture starting value | `cancel_count` | No confirmed CHANGE notification is emitted. BEGIN/CANCEL describe lifecycle, not proposed UPDATEs; COMMIT does not imply application acceptance. CANCEL does not restore external owner storage: the owner decides whether to restore its value from `requested`. State `preview/start/dragging` belongs to the reducer; do not mutate it from the handler. It is presentation/capture state, not a hidden confirmed value. `current` is the immutable value passed to this invocation, including for later callbacks after an owner assignment. For two Right keys in one submission both propose from that same entry value, preserving the existing controlled policy. An active gesture's cancel value can differ from that invocation's `current`. Owner acceptance is observed on the next submission. Same-call semantics also retain the entry value. Request input consumption and application acceptance are separate; rejection does not unconsume or propagate anything. The old `on_request` and `user` options must both be NULL. Conflicts reject before submission, state mutation or callback dispatch. A missing new handler is read-only. Disabling, making read-only, removing the handler or making the range zero-width cancels an active drag according to the old reducer. If a handler remains, an option-driven CANCEL is delivered with its precise reason. Removing the handler cannot deliver a callback; capture still stops and counts stay zero. ## Genuine evidence and copied lifetime Each input-driven callback carries the actual local frame sequence/event index, known pointer/keyboard source and a pointer-free scalar input snapshot. All callbacks from a single key or pointer-down/up event share that input identity; counts are phase callback counts, not distinct input counts. No activation snapshot is fabricated for pointer movement, release, generic cancel or keyboard phase dispatch. `HAS_ACTIVATION` is absent even for BEGIN/COMMIT. A generic `CUI_EVENT_CANCEL` has UNKNOWN source and no `HAS_SOURCE`; its actual input type/index still exist. Do not infer a pointer origin just because unused pointer fields have defaults. Option-driven cancellation has `has_input=false`, UNKNOWN source and no frame/index/activation presence flags. Its reason is DISABLED, READONLY or ZERO_SPAN (that precedence if several apply). It is not an input event or an invented programmatic action. Input-driven reasons are INPUT. Only presence flags establish shared evidence; zero unused fields are not proof. The input snapshot deliberately excludes text pointers, inline text, composition and unrelated event payloads. The entire `cui_component_slider_request` is thus copyable by value beyond callback/frame lifetime; frame identity remains local to that context. Handler/user are borrowed for the call only. No registration, retained callback or event queue is added by the facade. Do not recursively submit frames/controls, destroy context/state/users, free active storage or mutate drag state during dispatch. Record teardown/omission requests in app state and apply them after frame completion/renderer consumption. Changing the application's owner value is supported; general reentrancy is not. ## Results and verification `valid/submitted` are true when the existing reducer admitted this active submission, including disabled/read-only submissions; outside active submission or on invalid arguments they are false. Later rendering can still fail under Core's existing frame contract. Counts increment only when the new callback is actually invoked and saturate at SIZE_MAX with `count_overflow`; dispatch is not stopped by saturation. Reading/copying results never invokes a callback. Do not perform the same side effect in both the handler and the frame-count consumer. `tests/unit/test_slider_events.c` checks actual queued pointer/key batches, ordered phases, double values, genuine frame/index/source and contact data, absence of invented activation, owner rejection/acceptance and immutable same-call values, passive idle frames, copied payload lifetime, semantic snapshots, Escape/generic/option-driven cancellation, missing-handler read-only cleanup and invalid/conflicting-option atomicity. Existing `test_slider_controlled.c` and `test_base.c` remain behavioral regressions for the original path. Native tests run through `python scripts/test_local.py --build-dir `. Base and Styled tests establish portable reducer behavior and software rendering. They do not establish all-family uniformity, browser/physical-touch/GPU acceptance or bridge/binding exposure. Headers and sources are distributed through the normal source metadata/amalgamation/SDK tooling. For themed rendering with the same double-valued phases, use the implemented [Styled Slider facade](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/STYLED_SLIDER_EVENTS.md). Foreign request handlers remain unsupported. --- ## Software triangle meshes Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SOFTWARE_MESH.md # Software triangle meshes The deterministic software adapter implements `CUI_DRAW_MESH` and advertises `CUI_RENDER_MESH`. Expanded vertex triples are borrowed and never modified. Only XY is transformed by positive scale and origin; ST is interpolated in screen space. Command bounds do not crop mesh geometry: ancestor clip commands and the framebuffer viewport determine clipping. Each pixel is sampled at its center. Triangles are oriented consistently and use a top-left edge rule, so opposite sides of an exactly shared edge cannot both blend the same center. Degenerate triangles are empty geometry. Double precision edge, derivative, and interpolation calculations avoid float product overflow; bounding boxes are intersected with the clip and viewport before any integer conversion. Extremely ill-conditioned geometry remains subject to finite floating-point precision. Analytic coverage follows upstream's pre-WGPU 0.3.8 `fs_path_rasterization` shader: when `length(vec2(dSdx, dSdy)) < .001`, coverage is one. Otherwise it is `clamp(.5 - (S*S-T)/length(2*S*gradS-gradT), 0, 1)`. Both screen derivatives participate. At an exactly zero gradient, where shader division is undefined, the software adapter defines coverage as one for negative `S*S-T`, zero for positive, and one half for zero. Triangle boundaries themselves are sampled without extra geometric antialiasing. Uniform linear premultiplied color is unpremultiplied, clamped to SDR RGB, sRGB encoded, and quantized to bytes; source alpha is multiplied by analytic coverage and rounded to a byte. Rendering then uses the adapter's existing straight-alpha byte-domain source-over blend. This does not provide linear-light composition, HDR output, GPU bit identity, or full upstream path API parity. All meshes in the list are validated before clearing the framebuffer. Invalid vertex counts, nonfinite inputs, invalid alpha/scale, and transformed bounds outside the public mesh validity contract return false and preserve the target. Other command failures retain the software adapter's existing partial-render behavior. Borrowed arrays must remain valid through render completion. `tests/unit/test_render.c` checks numeric sRGB/alpha oracles, partial and opaque coverage with horizontal and vertical S derivatives and nonconstant T, shared edges in both windings, transforms, clipping, immutable inputs, degenerate and extreme geometry, and rejection before any framebuffer mutation. --- ## Spinner Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SPINNER.md # Spinner Use `cui_spinner_ex` for the frozen source-style decorative loading icon. It paints the Loader SVG at 16 logical pixels in `theme.text` by default, rotating through one turn every 0.8 seconds with quadratic ease in/out. Sizes 12, 14, 16 and 24 correspond to source presets at a 16-pixel rem. Existing `options.size` remains explicit logical pixels; any positive size up to 4096 is allowed. The application owns whether loading is happening and when to stop submission. Spinner adds no status role, busy relationship, focus stop or completion event. Announce the actual operation using the application's semantic tree when needed. ```c /* Persistent application state: one instance per independent spinner. */ cui_loading_motion loading_motion = {0}; /* During an active frame: */ cui_spinner_options options = cui_spinner_options_default(); options.now_seconds = host_now_seconds; options.size = 24; options.custom_color = true; options.color = (cui_color){220, 40, 90, 255}; options.reduced_motion = user_reduced_motion; cui_loading_motion_result result; if (cui_spinner_ex(ui, loading_id, &theme, &loading_motion, options, &result)) { /* Absolute deadline in host_now_seconds' clock domain; zero means idle. */ next_wake_seconds = result.next_wake_seconds; } else { /* Report submission failure; inspect the Core frame error as appropriate. */ } ``` Keep motion state between frames. Initial zero state starts at the first successful supplied time; explicitly zero it to restart. Time is finite [0,1e12], rewinds clamp to the last sample, and duration zero selects 0.8 seconds. Explicit durations must be finite [0,60]. Context or option reduced motion samples raw phase zero, **calls custom easing at zero**, and returns inactive/deadline zero with no perpetual invalidation. A shifted easing therefore freezes at its shifted angle. This corrects the earlier `cui_spinner_ex` behavior that skipped easing under reduced motion; a nonfinite reduced easing now fails atomically rather than being silently bypassed. The legacy pure `cui_loading_motion_sample`, Skeleton and the eight-dot `cui_spinner` keep their prior contracts. Moving results request the next sample at 60 Hz. Hidden or clipped submission does not automatically cancel application scheduling; omit hidden spinners when appropriate. Stop scheduling when the operation completes. ## Named rem sizes and custom pixels An optional descriptor preserves the source distinction between named rem sizes and fixed custom pixels: ```c cui_spinner_sizing sizing = {.size = CUI_SPINNER_LARGE, .rem_size = 20}; options.sizing = &sizing; /* Large = 1.5 * 20 = 30 logical pixels. */ /* Or fixed pixels, unaffected by rem or theme font changes: */ sizing = (cui_spinner_sizing){.size = CUI_SPINNER_CUSTOM, .pixels = 64}; ``` XS/S/M/L multiply rem by .75/.875/1/1.5. A zero named `rem_size` selects 16 logical pixels; applications pass their root rem explicitly. This is independent of the theme's text font size. Named rem must be finite [0,4096] and the resolved size must be in (0,4096]. CUSTOM uses only finite `pixels` in (0,4096]; its rem is ignored. When `sizing` is non-NULL it overrides `options.size`, even if the latter is invalid. NULL retains the old explicit-pixel/default behavior. No automatic ambient rem scope is introduced. The descriptor is copied synchronously and not retained; keep it alive through the call. Custom paint callbacks receive the same resolved logical size as the default Icon painter. `cui_spinner_options` grew: rebuild libraries, generated distributions and callers with the same headers. Zero-initialize options or use `cui_spinner_options_default`; old positional/binary layouts must not be mixed with new builds. ## Custom icons and styling A synchronous paint callback receives the selected size, color and center rotation in radians. Use any available named icon or a caller-owned Icon state. Host-loaded icons retain their existing loader/asset lifetime requirements. ```c static bool paint_loading_icon(cui_context *ui, cui_id id, const cui_theme *theme, float size, cui_color color, float radians, void *user) { (void)user; return cui_icon_named(ui, id, theme, cui_string("loader-circle"), (cui_icon_options){.size = CUI_ICON_CUSTOM, .custom_size = size, .custom_color = true, .color = color, .custom_transform = true, .transform = cui_icon_rotation(radians)}) == CUI_ICON_OK; } /* Before submission: */ options.paint = paint_loading_icon; ``` `paint_user` and `ease_user` are borrowed only for the call and never retained. `ease(phase,user)` receives normalized raw phase and may return **any finite number of turns**, including negative turns and overshoot. `result.phase` keeps that value; the painter receives its equivalent rotation reduced to [0,2π) before multiplication, so even very large finite values cannot overflow radians. At large float magnitudes fractional turns may already be lost to float precision. NaN and infinity reject before paint. The shared legacy sampler and Skeleton still require finite [0,1] easing and skip easing under reduced motion. A failed easing/paint call preserves motion state/result; paint callbacks must leave their own submission unchanged on failure. Core capacity errors retain Core's existing failed-frame contract. Borrowed bitmap data in successful draw lists expires at the next frame as with other Icon commands. Compose a parent `cui_box` for placement, padding, backgrounds, borders, opacity and clipping. Supported Icon style fields can also be supplied inside a custom callback. Icon padding and borders floor the allocated dimensions while the SVG paints the complete box; see the Icon guide for numeric constraints. Arbitrary inherited source Icon styling remains an explicit parity limitation. This guide does not claim complete Icon styling or complete renderer/platform parity from Spinner tests. Parent composition also supports content-inset padding. Explicit transparent color remains transparent; it is not a fallback sentinel. ## Source boundary and legacy API The reference is upstream kit 0.7.1 commit `87d10ae5e1299d1be18670a37570c5402f952e34`, `crates/component/src/spinner.rs` and its `Icon`/`Sizable` implementations. Spinner exposes icon, color, easing and size. Its source duration is private; CUI additionally exposes a bounded duration option. Spinner itself has no general Styled implementation, but its custom Icon can carry style. Default easing comes from pinned upstream 0.3.8. The older `cui_spinner` is a compatible eight-dot phase ring with legacy Loading status semantics and continuous invalidation while moving. It remains available; use `cui_spinner_ex` for the source-style SVG, decorative semantics and explicit wake scheduling. The two APIs intentionally have distinct contracts. ## Gallery and verification The existing **Spinner** gallery entry offers source preset/custom sizes, Loader/Loader circle/Arrow right, theme/custom/transparent colors, and default quadratic/linear easing. Optional size-identity/rem selectors exercise the named descriptor while legacy pixels remain the default. Additional easing choices show quarter, negative/extra turns, shifted linear easing and deliberate nonfinite rejection. Copy its concrete C example and open this guide from the component. No extra catalog family is introduced. `tests/unit/test_spinner_contract.c` verifies all source pixel sizes plus custom 64, default color, transparent color, actual rotated custom SVG pixels, static reduced-motion restoration, supported Icon background/radius styling, ancestor opacity and clipping, and decorative/quiescent behavior. Existing `test_status_motion.c` covers clocks, callbacks, custom easing and rejection. `tests/web/test_spinner_gallery.py` loads real WASM and exercises controls, bitmap/pixel changes, reduced-motion quiescence, desktop/390px and DPR 1/2, copyable usage and guide navigation. Native tests run through `python scripts/test_local.py --build-dir `; browsers stay headless. These tests are evidence for the listed behavior, not hardware/GPU acceptance. The native contract regression additionally compares real asymmetric Arrow right pixels for quarter-turn/1.25-turn/negative equivalent turns, opposite turns and large finite whole turns. It checks reduced custom ease(0), nonfinite failure atomicity, live-to-reduced transitions and named rem/default/custom pixel sizing through both default and custom Icon painters. Actual WASM now covers these descriptor and finite-turn cases in `tests/web/test_spinner_contract_gallery.py`: desktop/390px, DPR 1/2, asymmetric Arrow-right bitmap and canvas equivalence for .25/−.75/1.25 turns, reduced shifted ease(0), NaN/±Infinity rejection without painter or state/result commit, recovery and no stale wake after rejection. Named rem 0/16/20/32 is checked through both default/custom painters, while CUSTOM and NULL-descriptor pixels stay fixed. Logical layout size is exact; rotated bitmap bounds may include a one-pixel raster-rounding fringe, so bitmap bounds are not the rem metric. Complete inherited Icon styling, source-style bridge Spinner, combined raw-data lifecycle and broader host acceptance remain open. --- ## Loading motion contracts Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/STATUS_MOTION_GUIDE.md # Loading motion contracts The pinned upstream kit 0.7.1 source at `87d10ae5e1299d1be18670a37570c5402f952e34` defines Spinner in `crates/component/src/spinner.rs`, Skeleton in `skeleton.rs`, and linear Progress in `progress/progress.rs`. Its upstream dependency is exactly `upstream-pre=0.3.8`; `src/elements/animation.rs` defines quadratic `ease_in_out` and the forward/reverse `bounce` used here. Spinner defaults to a medium 16-pixel Loader in foreground color, with a repeating .8-second quadratic rotation. Its source public customization is icon, color, easing and size; speed is private. Skeleton is a decorative styled rectangle using the theme skeleton color (secondary by fallback), a two-second bounced quadratic opacity from 1 to .5, and an optional secondary half-opacity. It has no loading boolean, busy/status role, accessible name, completion event, or focus stop. Adding those semantics to the placeholder would misrepresent the source. Associate loading status with the actual operation in the application's semantic tree. CUI's legacy `cui_spinner` dot-ring and `cui_skeleton` cosine/phase APIs retain existing dimensions, semantics and invalidation. The opt-in `cui_spinner_ex` and `cui_skeleton_ex` paint the source-style Loader and bounced placeholder. Neither adds semantics. CUI has no dedicated skeleton theme token, so the new placeholder uses `theme.secondary`; the secondary option halves alpha again. Progress's existing determinate cubic-bezier transition and one-second indeterminate quadratic segment are unchanged. Reduced-motion indeterminate Progress retains its centered 35% segment and busy progressbar semantics. ## Ownership and scheduling Use one zero-initialized caller-owned `cui_loading_motion` per independent animation; it has no allocations. Zeroing it explicitly restarts the timeline. The first successful sample starts at the supplied clock value. Subsequent backward time clamps to the last sample. Time must be finite and in [0,1e12]; period must be finite and in (0,60]. For the component options, duration zero selects the source .8/2-second period; negative, nonfinite and over-60 durations reject atomically. Changing duration applies the new period to the same origin. The component returns `active` and an absolute `next_wake_seconds` in the **supplied clock's domain**. Moving primitives return the next 60 Hz sample; reduced motion returns phase zero, full base opacity, false activity and deadline zero. Context reduced motion also overrides the option. Custom easing is not called while reduced. These APIs do not request perpetual Core invalidation. Schedule the returned deadline and paint again then, as the gallery does: ```c options.now_seconds = cui_frame_time(ui); if (cui_spinner_ex(ui, id, &theme, &motion, options, &result)) host_deadline = result.next_wake_seconds > 0 ? host_now + fmax(0, result.next_wake_seconds - cui_frame_time(ui)) : 0; ``` If supplying host time directly, use the result directly. Repeating loading has no inherent completion; stop submitting it when the operation stops. Activity means submitted motion is enabled, not that pixels are visible: clipping and parent visibility do not automatically stop caller scheduling. Hosts may omit hidden primitives and restart/reset state as appropriate. Custom easing receives normalized phase (Skeleton first applies its triangular bounce). It must return finite [0,1]; invalid output preserves state/result and paints nothing. The custom Spinner paint callback receives color, size and center rotation in radians; its userdata is borrowed for the synchronous call and never retained. The default uses the existing bounded context-owned SVG icon cache, with draw-list bitmap lifetime unchanged. A paint callback returning false must leave its own paint unchanged; CUI cannot roll back arbitrary user callback side effects. State/result commit only after success. General Core frame-capacity errors still follow Core's existing frame error contract. ## Validation `tests/unit/test_status_motion.c` checks clock start/reset/rewind, default and invalid durations, callback rejection, finite wakes, reduced quiescence, no invented Skeleton semantics, custom paint pixels, default SVG/software pixels, and unchanged Progress transition/indeterminate behavior. It links `cui`, `cui_software` and native text dependencies. Root owns CMake registration. `tests/web/test_status_motion.py` runs real WASM in Playwright 1.58.0 with pinned Chromium 1208 by default (`--chromium` may select 1228). It checks animated frame progress with finite gallery wake deadlines and no perpetual redraw, actual canvas/mask pixels, reduced-motion frame and pixel stability, decorative semantics, and existing Progress busy/reduced-motion behavior. Distribution regeneration is integrator-owned; stale distribution checks are expected until that step. --- ## Styled double Slider Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/STYLED_SLIDER_EVENTS.md # Styled double Slider Include `cui/cui_styled_slider_events.h` for `cui_slider_events`. This additive controlled Slider paints a horizontal bar and optional label, using the existing [Base double event reducer](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SLIDER_EVENTS.md) exactly once. The old float-pointer `cui_slider` API, layout and behavior are unchanged. ```c static void position_request(void *user, const cui_component_slider_request *r) { double *owner = user; if (r->phase == CUI_SLIDER_UPDATE) *owner = r->requested; /* Accept; leave unchanged to reject. */ } /* Persistent caller-owned data: */ cui_slider_state drag = {0}; double position = 10000000000.25; /* During UI submission: */ cui_component_slider_result result = cui_slider_events( ui, slider_id, &theme, cui_string("Position"), position, &drag, (cui_slider_options){.minimum=10000000000., .maximum=10000000001., .step=.125}, (cui_slider_style_options){.width=240}, (cui_component_slider_handler){position_request, &position}); ``` `result` has the Base facade's admission flags and actual callback counts; reading it never dispatches another effect. BEGIN/UPDATE/COMMIT/CANCEL and their copied evidence retain the Base contract. UPDATE is a request, not proof of owner acceptance; no confirmed CHANGE is emitted. Legacy `options.on_request` and `options.user` must both be NULL. A missing new handler is readonly. ## Geometry and style The public ID identifies the fixed-width hit rectangle. The centered painted bar has exactly its x and width, so its endpoints map to minimum and maximum. Its default visual height is 8 logical units inside a 24-unit-high hit area. The label sits above it and is noninteractive; hiding it does not remove the semantic name. `cui_bounds(ui, slider_id)` reports the hit rectangle, not the private outer column. Style zero values select defaults: width240, track_height8, hit_height24 and font_size from the theme. Positive overrides are logical units, finite and <=4096; hit_height must be at least track_height. Negative, nonfinite or oversized values reject the call. Theme radius must be finite, nonnegative and <=4096; it is clamped to half each painted shape's height. Zero radius stays square. The default fill uses theme primary; the default track uses primary at 20-percent alpha. `custom_colors` selects explicit track/fill colors. Disabled controls use theme muted and its 20-percent-alpha track, including when custom colors exist. Keyboard/pointer focus adds a 15-percent-alpha theme focus background to the hit rectangle without a border or padding that could shift normalization endpoints. No thumb, vertical variant, preset size or animation is implied. Input uses **previous completed layout** bounds, as Base does. Submit once to establish geometry. On a width change, this submission's queued input still uses the last completed width; new paint/layout uses the new width. The next submission uses that completed geometry. The facade does not rerun layout or dispatch. ## Confirmed value and drag preview Owner value, range, step, preview and gesture start stay double. The range and its span must be finite, ordered, with the confirmed value inside it; step is finite and nonnegative. For rendering only, clamp the selected paint value within bounds, compute a ratio in double, clamp it to [0,1], then convert that bounded ratio to float for the logical fill coordinate. No confirmed or proposed value is cast through float. Zero span paints zero fill. Semantic numeric values remain Base's normalized float0..1; supply `value_description` for application units. While `drag.dragging` remains true after reduction, paint its preview. Otherwise paint the immutable confirmed value passed into the call. A rejected drag thus previews while held and returns to confirmed paint on release. Keyboard requests do not paint an unaccepted proposal. Accepting in the callback updates external owner state, observed on the next submission; same-call semantics also retain the entry snapshot. Two keys in one call propose from that same snapshot. Escape/generic cancel and disabled/readonly/zero-span transitions retain Base cancellation behavior. CANCEL offers the captured start to the owner; it does not write owner storage. When capture ends, paint uses the confirmed entry value, even if different from start. Removing the handler ends capture without delivering callbacks to a missing handler. Omission itself dispatches no synthetic cancel. Keep one zero-initialized caller-owned state per stable ID. During submission, Base owns its capture/preview fields. Handlers may accept/reject through external owner state, but must not mutate active state, theme or borrowed data, destroy context/state/users, or recursively submit UI. Defer omission/destruction until return and renderer consumption. All invalid public inputs are checked before opening boxes: no callbacks, capture mutation or UI submission on rejection. `tests/unit/test_styled_slider_events.c` uses software pixels for bar endpoints, preview/rejection/acceptance and finite extreme ranges, plus real queued touch, keyboard and cancellation input. It compares Base/Styled phases, exact doubles above float precision, normalized semantics, resize boundaries, missing handlers, invalid-input atomicity and deferred omission. The label test inspects text command placement; its font-free pixel fixture does not claim glyph raster coverage. Legacy Slider and component tests remain required. Browser/foreign bindings and full Slider-family parity are outside this slice. --- ## Retained completed-close observers Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SURFACE_EVENTS.md # Retained completed-close observers Include `cui/cui_surface_events.h` for additive Base and Styled surface facades. They observe completed closes; they do not control close acceptance or notify opening, destruction, dismissal attempts or vetoes. Existing surface state/options layouts and entrypoints are unchanged. ```c static void closed(void *user, const cui_surface_lifecycle_event *value) { cui_surface_result *last = user; *last = value->result; } /* These objects must remain at stable addresses through every possible close. */ cui_surface_event_state surface; cui_surface_result last = CUI_SURFACE_NONE; cui_surface_events_init(&surface, surface_id, CUI_SURFACE_DIALOG); cui_surface_events_set_handler(&surface, (cui_surface_event_handler){closed, &last}); /* On each submitted frame: */ cui_surface_event_result result = cui_surface_begin_events( ui, theme, &surface, cui_string("Title"), cui_string("Body"), options); if (result.control_result) { /* Compose the body. */ cui_surface_end(ui); } ``` `cui_base_surface_update_events`, `cui_base_surface_begin_events`, `cui_surface_begin_events` and `cui_alert_dialog_events` each refresh the retained registration in a by-value copy of options before native update. All other options, including `decide` and `decision_user`, pass through unchanged. Do not separately update then begin on the same input. `control_result` preserves the native bool; for the void Alert composition it is always false. `valid` describes adapter preflight only, not geometry/render success. `close_count` counts actual observer invocations during that call, including a close before subsequent native failure. An absent observer still closes normally and yields zero count. No result replay occurs when replacing a handler or submitting another frame. Use existing `cui_surface_open`, `cui_surface_close`, `cui_surface_request_close` and `cui_surface_take_result` on `&surface.control`. Direct close bypasses decision policy, exactly as before; request-close waits for submission and consults the existing decision callback. Pending requests are one slot, not a queue. The observer runs after the result is committed, focus is restored and the overlay closes. Taking the persistent result neither triggers nor cancels notification. Direct close within a valid active frame invokes the retained observer but returns no facade-local callback count. Only request-close is documented safe between frames. The existing imperative close calls active-frame focus-scope dismissal: calling it outside a frame can commit/notify while reporting CUI_ERROR_LIFECYCLE. This facade preserves that diagnostic; it does not make that operation safe. The payload's `event` is shared LIFECYCLE metadata with the surface ID and UNKNOWN source. It carries no frame, event index or activation flags: an imperative call or animated completion does not establish an input cause. The pointer-free payload can be copied beyond callback/context lifetime. It does not keep the surface or context alive. Result is the existing ACCEPTED/CANCELLED/CLOSED value; imperative legacy close retains its existing handling of other supplied values. Storage and handler user data must outlive all possible closes. Never copy or move an attached `cui_surface_event_state`, edit adapter fields, or replace its retained `control.on_close/close_user`. A Sheet observer runs only at completed exit, with the latest handler installed between calls; it can outlive the request's frame. `set_handler` replaces one listener, never appends, and ignores user data when no function is supplied (the stored user pointer is cleared). An empty handler keeps the adapter installed. Incoming options with either legacy close callback field populated are rejected before any state/UI mutation. `decide` is allowed. Reentrant wrapper calls, handler replacement and detach during notification fail preflight. Surface/context/ registration destruction, raw reentrant surface operations, and foreign exception unwinding during callbacks are unsupported. Mutate unrelated application owner state and defer teardown until the outer component call returns. `cui_surface_events_detach` succeeds only when closed, not exiting, outside an active call, and still holding the matching registration. It clears that registration and handler without closing, taking the result or freeing anything. After detach ordinary legacy calls may use `control`. Reinitialize closed detached storage to use events again; init is not teardown of a live surface. Plain legacy update/begin with ordinary options on attached storage is unsupported: it overwrites the retained callback. Use the event-aware wrappers. Custom legacy composition can call `cui_surface_events_options` and pass its transformed options to that exact surface call. The helper preserves all other options, leaves output untouched on failure, and provides no wrapper-local count. Never pass those transformed options to another surface. A later wrapper detects overwritten registration and fails; it cannot recover notifications already missed by an unsupported legacy call. Keep the owning storage alive if mixing invalid calls; there is no implicit recovery or safe teardown promise. The test suite covers all wrapper refresh paths, actual callbacks/counts, decision veto, imperative close, no-handler reduction, conflicts without mutation, helper-driven legacy composition, stale registration detection, Sheet exit and handler replacement, detach and reuse. Existing surface tests remain unchanged. This C facade does not add bridge notifications or binding subscriptions. --- ## Table and DataTable behavior contracts Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TABLE_BEHAVIOR.md # Table and DataTable behavior contracts Source reference: upstream kit 0.7.1, commit `87d10ae5e1299d1be18670a37570c5402f952e34`, `crates/component/src/table/{table,column,state}.rs`. These are original portable C implementations. This guide describes the implemented subset and compatibility choices, not full family parity or native accessibility certification. ## Selection and action columns `cui_table_column.nonselectable = true` prevents column/cell selection without disabling the column. Header sorting, resizing, reordering and focus remain available; custom child buttons keep their independent base behavior. Whole-row selection still highlights cells in that column, matching the source's action-column granularity. `disabled` retains its separate existing behavior. `cui_table_options.row_selection_disabled`, `column_selection_disabled`, and `cell_selection_disabled` independently block the corresponding selection mode. They suppress selected presentation for that mode while preserving stored selected keys, so re-enabling the policy restores controlled selection. They do not disable sorting, cursor navigation or custom row/cell controls. Row-header activation does not request row-selection escalation while row selection is blocked. Nonselectable cells remain focusable grid cells with readonly selection semantics, enabling navigation through a row containing custom action controls. Activation result fields can still report a clicked cell; `selection_changed` stays false when selection is rejected. Range selection skips nonselectable columns in cell/column mode before counting required capacity. It does not insert phantom action-column selections. Application-provided selection storage remains bounded by its declared capacity. The model-free `cui_table_is_selected()` helper sees mode policies and stored keys; because it has no model argument, callers implementing custom paint must additionally check `column.nonselectable` outside row mode. Styled DataTable applies this check itself. ```c columns[1].nonselectable = true; cui_table_result result = cui_data_table(ui, id, theme, model, &state, (cui_table_options){ .width = 480, .height = 240, .selection_mode = CUI_TABLE_SELECT_CELL, .row_selection_disabled = true, .sort_cycle = CUI_TABLE_SORT_CYCLE_SOURCE, .accessible_name = cui_string("Workspace files") }, label_cell, render_cell, userdata); ``` ## Sort requests and borrowed data Zero-initialized `sort_cycle` remains `CUI_TABLE_SORT_CYCLE_LEGACY`: Default→Ascending→Descending→Default. Explicit `CUI_TABLE_SORT_CYCLE_SOURCE` follows the pinned source: Default→Descending→Ascending→Default. Both mouse/header activation and keyboard activation use the same reducer. Switching to another column begins at that policy's first direction. Invalid sort-cycle enums reject submission before layout/state changes. Sorting updates `state.sort_column`/`state.sort` and returns `sort_changed`; it does not mutate borrowed row data. The application handles the request, reorders/rebinds its rows, and retains stable row keys. Selection and semantic row indices reconcile against those keys. Result flags describe the final state for one frame; multiple queued input events may coalesce into one flag, so this is not an event-by-event callback log. A frame without a new sort event does not repeat the request. The styled implementation invokes the supplied label callback once per rendered cell for semantic and default visible text, rather than twice. Custom render callbacks also run once per rendered cell. Hosts may themselves call the label callback within custom rendering; CUI does not prevent that application choice. Models, callback userdata and arrays stay borrowed according to the existing bind contract; no ownership transfer or implicit async work occurs. ## Named composable Table and cell sizing `cui_table_begin_ex()` adds an explicit root accessible name and row/column counts. `cui_table_begin_cell_ex()` supplies header/body role, accessible name, parent ID, one-based row/column indices, alignment and sizing. `cui_table_begin_row_checked()` validates row options before opening a row. End these checked begins only when they return true. A caption remains visible descriptive content; it does not replace the explicit root name. Names are synchronously copied by Core into its bounded frame storage; input string bytes need only remain valid during submission. Root counts and cell/row indices must fit `INT_MAX`. Dimensions are finite 0..65536, padding finite 0..4096, and enums must be defined values. Invalid checked inputs, including a self-parent relationship, add neither layout nor semantics. Legacy void begin/end helpers retain their existing defaults and normalization behavior, including the generic `Table`/`Cell` names and 4px cell padding. Explicit positive cell height overrides design sizing. A non-INHERIT `design_size` with zero height uses `cui_design_measure()` control height at density `theme.font_size / 16`. Default design padding uses its vertical control padding so the design line height fits; an explicit `custom_padding` override wins. This is an intentional symmetric padding adaptation, not the source's independent edge-padding API. Row design sizing follows the same height rule. Child typography is host-owned: derive font and line height through `cui_design_measure()` and use those when submitting the child text. Choosing a design size does not silently resize arbitrary nested controls. ```c cui_design_metrics metrics; cui_design_measure(CUI_DESIGN_LG, theme->font_size / 16, &metrics); if (cui_table_begin_cell_ex(ui, cell_id, theme, (cui_table_cell_options){.width = 220, .design_size = CUI_DESIGN_LG, .name = cui_string("Paid"), .parent = row_id, .row_index = 1, .column_index = 2})) { cui_text_with_line_height(ui, cui_string("Paid"), metrics.font_size, theme->text, metrics.line_height); cui_table_end(ui); } ``` Column spans continue to use `cui_table_span_width()` and the existing span begin helper. Core has no row/column-span semantic fields, so this change does not invent them or claim span announcements. Independent per-column edge padding, full source Table flex/minimum-size behavior, dedicated Table palette tokens and independent scrollbar-axis visibility remain gaps. The source's pinned feature is fixed-left columns; no pinned-row feature is introduced. ## Evidence `tests/unit/test_table_selection_contracts.c` tests source/legacy cycles, borrowed-data immutability and stable-key rebind, selection-only opt-outs, restored stored keys, header sort/resize and custom child pointer/Enter activation, range capacity, label/render callback counts, strict invalid-input behavior, explicit header/root/row/cell semantics, and actual nested text containment at all 14 design sizes in two densities. Existing `test_table.c` retains legacy navigation/resize/move/virtualization/selection coverage. The real WASM gallery exposes canvas buttons for selection, action-column and sort-policy choices. Its Table story uses named parts, actual design typography and horizontal scrolling for large text. `tests/web/test_table_selection_contracts.py` checks Chromium 1208 source sort cycling, action-button touch activation with selection blocked, readonly action-cell semantics, all-size metadata/text sizing, mobile touch and disabled controls. Worker validation passed strict C11 warning builds, the scoped headless suite and ASan/UBSan with leak detection. Standard CTest passed 102/103; only stale generated `dist/cui_table.h` failed its distribution check, which the integrator owns. Browser evidence uses the approved generated-JS bridge for the integrator-owned Table selector/height and DataTable420 preview. The integrator owns test registration. Native screen-reader output and per-platform accessibility bridges remain separately unverified. --- ## DataTable transitions Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TABLE_EVENTS.md # DataTable transitions Include `cui/cui_table_events.h`. The additive `cui_table_reduce_events`, `cui_base_data_table_events` and `cui_data_table_events` take a `cui_table_event_handler` and return unchanged legacy `control`, validity/submission flags and actual `selection_count`, `sort_count`, `column_width_count`, `column_move_count`, `activation_count` and `context_request_count` (saturating with `count_overflow`). A missing callback ignores user and preserves reduction, including multi-selection behavior. Each applied sort key/direction transition notifies inside reduction, before final semantics and every Styled render callback. Three cycles can return to the entry state while producing three typed events and preserving the legacy `sort_changed` flag. Both legacy ascending-first and source descending-first cycles remain unchanged. This changes sort state only; caller rows are not sorted. Earlier successful notifications remain delivered if later input fails. The pointer-free payload preserves exact native `cui_id` keys and direction values. Shared CHANGE metadata has the table root target and genuine current frame/index/source; HAS_ACTIVATION is present only when a real snapshot exists. Do not assume final semantics, geometry or paint are available during callbacks. Disabled/loading/inert/layout-only paths preserve legacy bookkeeping without sort callbacks. No new consumed-event filtering is applied. Handler/user are borrowed synchronously. Copy payloads/change unrelated application state, but do not mutate/rebind the model, rows, columns, state or workspace; recurse; destroy storage/context; or unwind foreign exceptions during callbacks. Defer model edits/removal/teardown until outer submission and renderer consumption finish. Existing render/label callback arguments and virtual-window timing remain unchanged. New facades require a nonzero root ID; legacy APIs remain unchanged. Single selection emits `cui_table_selection_change` for each actual primary row/column pair transition, with the effective operation mode. Navigation in manual mode does not select; activation may still select. Same-pair activation emits no CHANGE, while A->B->A emits twice even though the legacy final `selection_changed` is false. Escape clearing is observed. Row-header operations can apply ROW selection while also producing the old mode-request result; the callback precedes later result bookkeeping and does not reject that selection. A column activation can emit selection then sort in the existing write order. Selection-disabled/nonselectable policies do not disable independent sorting. A non-NULL `on_selection` with `multiple_selection=true` returns `valid=false`, `control.error=CUI_TABLE_INVALID` before reduction, state/column mutation or paint. There is no silent primary-only multi observation. Nil selection/sort-only handlers still support legacy multi reduction, including accepted progress before errors. The separate set-observation API below supports complete multi selection. Column movement/resize and activation/context are covered below; mode requests remain a separate slice, while viewport/load remain aggregate result observations. Existing bridge V1 table notifications remain aggregate post-step snapshots; native multiplicity and 64-bit keys here do not imply binding parity. ## Multi-selection snapshots Use `cui_table_reduce_set_events`, `cui_base_data_table_set_events` or `cui_data_table_set_events` with `cui_table_set_event_handler` and `cui_table_selection_workspace`. The handler supports selection, sort, column-width and column-move callbacks; its selection callback receives `cui_table_selection_set_change`, not the scalar payload. Its return is `cui_table_set_event_result`: `events` contains the same legacy result and actual callback counts as above, and `preflight` distinguishes workspace/argument failure from a later legacy capacity error. This requires `multiple_selection=true` when `on_selection` is non-NULL. Scalar facades keep their existing explicit multi-observer rejection. ```c cui_table_selection before[32], after[32]; /* Each >= state.selection_capacity. */ cui_table_selection_workspace scratch = {before, after, 32}; cui_table_set_event_handler handler = { .on_selection = on_set_change, .on_sort = on_sort_change, .user = application }; cui_table_set_event_result result = cui_base_data_table_set_events( ui, table_id, model, &state, options, scratch, handler); /* Keep scratch and all owner resources alive until this call completes. */ ``` Each actual selection operation snapshots the multiset and primary pair before and after the old mutation. Payload `previous`/`value` spans are sorted by exact unsigned `(row,column)` keys; duplicates retain multiplicity. Storage-order-only changes do not notify; primary-only changes do. Ctrl toggles, range replacement, row-header mode and Escape follow their existing policies. Repeated/net-zero transitions notify separately; rejected operations with no change do not. Earlier notifications survive a later capacity error, while old flags/errors remain unchanged. Callbacks run before final semantics and Styled rendering. No per-item delta or transaction rollback is provided. Both scratch arrays have `capacity` writable entries; capacity must be at least `state.selection_capacity` and at most 4096. Zero capacity permits NULL arrays. An iterative heapsort canonicalizes only scratch: O(n log n) observation time, O(1) auxiliary storage and exactly two caller buffers, with no allocation or owner-array sorting. This does not change the complexity of legacy range selection. Spans are borrowed **only during the callback** and reused at the next operation; copy entries into application-owned storage to retain them. Copying the payload struct alone does not retain the text-free spans. Handler/user borrow synchronously. No mutation of active owner/model/scratch, recursion, destruction or foreign unwind is supported; defer edits and teardown until submission/render consumption finish. Preflight checks all arguments/counts/extents/alignment before any bookkeeping, input consumption, callbacks or painting. Full declared scratch ranges must be disjoint from each other, state, its full selection buffer, model object and bound row/column descriptor arrays. Invalid arguments/extents take precedence over short capacity, then overlap. Failure returns `events.valid=false`, no submitted/counts, `events.control.error=CUI_TABLE_INVALID` and INVALID, WORKSPACE_CAPACITY or OVERLAP in `preflight`, leaving owner/columns/scratch/input consumption unchanged. Success sets `preflight=OK`, including a subsequent operation's CUI_TABLE_CAPACITY error. Scratch allocations must additionally be exclusive of context/internal allocations, label/string/group bytes, userdata and other resources: opaque aliases, dangling pointers and actual allocation lengths cannot be universally checked. They remain caller preconditions, not a runtime memory-safety guarantee. A NULL selection callback ignores workspace entirely, preserves single/multi legacy reduction and still supports optional sort observation; unused userdata is ignored. Passive/disabled/loading behavior and bridge omissions above also apply. ## Column width and movement Both scalar and set handlers add optional `on_column_width` and `on_column_move`. Use designated initializers for these unreleased structs and rebuild clients when updating the header. Legacy state/options/result layouts and entrypoints are unchanged. The shared result adds saturating `column_width_count` and `column_move_count`, with the existing `count_overflow` flag. `cui_table_column_width_change` copies `{event, column, previous_width, width}` with exact float widths after the old helper's clamps. It observes each successful pointer-move resize or grip Left/Right key resize. Repeated clamped no-ops do not notify. `cui_table_column_move_change` copies `{event, column, previous_index, index}` after a successful Ctrl+Left/Right header reorder or actual pointer drop. Indices are operation-time array positions; the stable exact `cui_id` identifies the column after subsequent moves. Both payloads are pointer-free. Capture facts inside the callback or copy the struct for later use. Notifications run immediately after the successful helper mutation, before later gesture cleanup, semantics and Styled paint. A drop callback still sees the active drag state; it must not mutate it. Event metadata is frozen before descriptor movement, uses the table root target and genuine triggering frame/index/source; a pointer-move resize has pointer provenance without inventing an activation. Callback order follows the reducer's existing operation order, including repeated changes and cycles returning to the entry width/order. No extra consumed-event filtering, focus changes or legacy result-flag reinterpretation is added. Programmatic `cui_table_resize`/`cui_table_move_column` calls stay silent. Fixed regions, immovable/disabled columns, finite/clamped widths, >4px drag threshold, passive/layout-only/loading and missing callback behavior remain unchanged. A below-threshold header gesture may still sort as an ordinary click; an actual drag suppresses that click. Cancel/Escape ends the existing gesture without rolling back an already-applied resize; no begin/commit/cancel event is invented. Handlers/user remain borrowed, and the mutation/reentrancy/teardown restrictions above apply. Base only submits semantics, so pointer routing requires actual caller-provided geometry (the tests prime with Styled geometry). No new dispatch, GPU validation or bridge/binding event coverage is implied. ## Activation and context requests Both scalar and set handlers add optional `on_activate` and `on_context_request`. `activation_count` and `context_request_count` count actual synchronous calls, saturating with `count_overflow`. Missing callbacks ignore unused userdata and preserve all legacy writes. Set facades with no set-selection callback need no workspace to observe these actions; existing preflight rules remain unchanged. `cui_table_activation` copies ACTIVATE metadata, `area`, `row` and `column` for each accepted cell or row-header activation. CELL uses both effective cursor keys; ROW_HEADER always has column=0. A repeated same-item action still activates even when selection is unchanged, nonselectable, selection-disabled or rejected for capacity. It does not imply selection applied/committed. Header sorting remains covered by sort/selection events; no generic header action is added. Facts and metadata freeze before selection observers run. Notification follows that branch's selection attempt/CHANGE and legacy activated-field writes, before later mode-request bookkeeping, focus/reveal work and final semantics/paint. Keyboard facts use the effective cursor, which can differ from the original routed child after earlier navigation. The old result remains a last-write aggregate: row-header activation writes only activated_row, so activated_column can carry from an earlier cell action. Typed ROW_HEADER payloads explicitly use column=0 without altering that legacy behavior. `cui_table_context_request` copies REQUEST metadata, `area`, `row` and `column` for each eligible secondary POINTER_DOWN on a cell, row header or column header. COLUMN_HEADER uses row=0, ROW_HEADER column=0. It notifies immediately after the old context fields are written, before subsequent cursor/selection handling. The context item need not be selected. A request neither selects it nor opens a popup, and has no rejection return. Disabled row/column and global/passive policies keep their existing distinctions; nonselectable alone does not suppress context. Metadata has the table root target and genuine frame/index/source. Secondary press is POINTER source without fabricated activation evidence. HAS_ACTIVATION is present only when the existing accepted-activation snapshot API supplies it; absence does not invalidate an accepted raw Table action. Callback facts survive an earlier selection observer consuming input; no new consumed-event filter is introduced. Standard Table roles support accessibility focus but currently reject ACTIVATE without a pointer_activatable override; no role remap or parity claim. Both payloads are pointer-free and copyable beyond the callback/frame/context. Handler/user and active resources retain the borrowed lifetimes and mutation/ reentrancy/destruction restrictions above. Record intent and defer teardown. Read viewport/load observations from `control` after submission: they remain completion aggregates, not per-input callbacks or a networking API. The bridge/bindings do not gain these native events. ## Row-mode intent requests Both handler types accept `on_mode_request(user, const cui_table_mode_request *)`; `mode_request_count` counts actual synchronous calls, saturating with `count_overflow`. The pointer-free REQUEST contains `current` (the submitted options selection mode), `requested` (ROW), effective `row`, and `reason` (`CUI_TABLE_MODE_FROM_ACTIVATION` or `CUI_TABLE_MODE_FROM_NAVIGATION`). Row-header activation runs selection CHANGE, ACTIVATE, legacy mode-request flag writes, then mode REQUEST. Automatic row-header navigation runs selection CHANGE, flag writes, REQUEST, then the existing focus/reveal work. Facts and real input evidence freeze before the first selection observer. Requests survive failed or unchanged selection, including repeated HOME and already-ROW intents. This is notification of existing intent: no options mutation, veto, commit or rollback. Manual navigation and disabled row selection do not request mode; manual activation retains the legacy request behavior. Disabled/loading/inert/layout-only paths remain unchanged. Missing callbacks ignore user; a set facade with no selection observer ignores its workspace even with a mode observer installed. Callbacks run before paint and may copy facts or update unrelated state. Do not mutate active options/owner/model/workspace, recurse, destroy resources or unwind across C. Defer teardown until submission and renderer consumption finish. Viewport/load remain result-only completion observations. No bridge/binding API or accessibility ACTIVATE support is added by this slice. --- ## Tabs aggregate selection observers Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TABS_EVENTS.md # Tabs aggregate selection observers Include `cui/cui_tabs_events.h` for `cui_base_tabs_events` and `cui_tabs_events`. They add an optional applied selection CHANGE observer to existing Base/Styled Tabs, preserving the old APIs, options, bool results, input handling and painting. ```c static void tab_changed(void *user, const cui_tabs_selection_change *event) { app_state *app = user; app->last_tab = event->value; /* unrelated application state */ } cui_tabs_event_result result = cui_tabs_events( ui, container_id, &theme, items, count, &selected, options, render_panel, panel_user, (cui_tabs_handler){tab_changed, app}); ``` The Base variant draws nothing and takes an explicit nonzero compound `target` before the item array; Styled uses its nonzero container ID. These IDs identify the aggregate event, not an invented activating tab. Null context, zero target or null selected storage reject before calling the legacy reducer. Other legacy validation and maintenance remain unchanged. `result.changed` is the exact old bool, which is not a successful-admission/submission signal. At most one callback runs after Base finishes its selection and semantic/roving focus finalization, before Styled reveal/animation updates, paint, render slots and panel callback. The selected pointer has already been written. A missing observer still permits legacy writes and has zero callback count; its unused user pointer is ignored. Reading either result field does not dispatch again. Payload `previous` and `value` are stable selected IDs. All payload fields are pointer-free and may be copied. Metadata has CHANGE, the compound target, UNKNOWN source and HAS_FRAME with the actual active frame sequence. There is no event index, activation or reason: overflow MenuTree reduction and direct tab navigation are separate passes, so a final selection cannot honestly identify one input. This is an explicit aggregation exception. Multiple transitions coalesce; if the final ID equals the initial ID, there is no callback. Selecting the same tab, manual focus-only navigation, opening/closing overflow, scrolling and reorder requests do not by themselves report selection CHANGE. Existing drag request fields remain separate and the caller still applies reordering after the frame. The observer cannot reject selection that has already been applied. No callbacks are delivered outside an active painted submission, from layout-only work or when globally disabled. The wrapper still calls the legacy Base reducer for its normal maintenance, including disabled drag cleanup and empty overflow cleanup. Inert/modal/consumed-input behavior remains Core's routing behavior; there is no new readonly/inert policy and no synthesized input for maintenance. Invalid or disabled selected IDs remain caller-owned as before; no repaired value or synthetic change is introduced. Observer/user are borrowed during submission. Keep selection, item arrays, labels, state, theme, render/panel users and overflow scratch alive and unchanged. Do not mutate/free active resources, destroy the context or recursively submit UI from the observer. Set unrelated flags to request omission/removal after the outer call; wait through frame/render consumption before teardown. The indicator's measured bounds and other retained state keep their existing longer lifetimes. Omission does not dispatch cancellation of retained work. Render/panel callbacks retain legacy order; their own arbitrary model mutations are not Tabs reducer events. `tests/unit/test_tabs_events.c` compares old/new selection, focus, panel choice, semantics and draw commands. It covers queued pointer/key selection, same-tab silence, multiple/net-zero transitions, manual navigation, absent observer, callback-before-panel order, consumed input, disabled/inert/layout-only work, invalid selected IDs, copied payload lifetime, deferred omission, overflow selection, real reorder-request silence, and disabled/empty Base maintenance. Legacy `test_choice.c` remains required. Native tests run through the private display wrapper. No new browser, host accessibility or foreign-binding proof is claimed; this slice adds no REQUEST/COMMIT/ACTIVATE or popup lifecycle facade. --- ## Tabs scroll ownership and boundary handoff Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TABS_SCROLL_CHAINING.md # Tabs scroll ownership and boundary handoff Scrollable Tabs now consume each wheel or touch-converted SCROLL event when their bounded offset actually changes. A refused event is offered to an eligible ancestor through the existing `cui_defer_scroll_event` API. Public options, zero-initialized behavior and selection callbacks are unchanged. This matters to browser page fallback: before the fix, a vertical touch move changed the Tabs offset by 30 pixels but left the event unconsumed. The existing `web/touch_page_host.h` policy consequently made the page eligible and the browser scrolled the page by the same 30 pixels. A parent following Core targets did not automatically double-scroll; the observed leak was the host page fallback. Wheel events had the same missing consumption signal, although the production gallery's wheel preflight can prevent page scrolling independently of that signal. A second case occurs when several events share one frame. Core initially routes them using the previous layout snapshot. If the first reaches the Tabs edge, the second now defers to the parent rather than disappearing with the retained child target. An event that moves the child partially is consumed entirely, matching shared Scrollable behavior; this change does not recover its residual delta. Boundary handoff therefore happens on a later refused event. No inertia or momentum behavior is added. The source change is restricted to the Tabs scroll loop in `src/base/cui_choice.c`. Core pointer presence, capture, modal routing, native adapters, browser production handlers, DataTable and shared scrollbar visibility/timing are unchanged. ## Regression evidence `tests/unit/test_choice.c` adds an actual styled Tabs scene inside a shared Scrollable. Both orientations and precise/line deltas assert child movement and consumption, no parent movement for accepted deltas, ignored already-consumed input, disabled child routing, and two events in one frame with the second moving the parent exactly once. The accepted-event assertion fails on the original source; the failure is preserved in `/home/matteo/.cache/cui-validation/tabs-before.log`. `tests/web/tabs_scroll_probe.c` composes public styled Tabs and Scrollable APIs and the unchanged page-host policy. `test_tabs_scroll_chaining.py` builds this source as strict C11 WASM with pinned Zig 0.16.0, then drives actual Chromium mouse-wheel/Shift-wheel and CDP touch contacts. It asserts current first-tab bounds and changed canvas pixels, child-to-parent boundary handoff, page remaining stationary, disabled wheel/touch behavior, cancellation without selection, and one selection from the next real touch tap. No test invokes a model mutation or reducer export to substitute for user input. Reset is fixture initialization between independent cases. Before-fix CDP evidence is preserved in `tabs-before-touch.log`: Tabs offset 30, parent offset 0, consumption 0, page scrollY 30, one fallback. After-fix tests report PASS in `tabs-final-browser.log`; the screenshot is `tabs-final-browser/tabs-scroll.png`, under `/home/matteo/.cache/cui-validation/`. This is a controlled real browser fixture, not a claim that every gallery mode or physical device was tested. The Canvas2D fixture draws ordinary Tabs rectangles, borders and text; it is not a general CUI renderer conformance test. Run the browser proof from the repository: ```sh TMPDIR=/home/matteo/.cache/cui-validation/tmp-storage/tabs \ uv run tests/web/test_tabs_scroll_chaining.py \ --output /home/matteo/.cache/cui-validation/tabs-final-browser ``` Playwright is pinned to 1.58.0 and defaults to its installed Chromium 1208 executable. `--case touch` isolates the touch diagnostic; default execution includes the full suite. The browser fixture uses the same Shift-plus-vertical-wheel translation as the gallery; native SDL Shift-wheel parity remains outside this change. The warning-enabled native build completed without warnings. Full CTest passed 119/120; only `distribution` failed because generated distribution sources are integrator-owned and stale after this source edit. Focused `test_choice` passed with AddressSanitizer, UndefinedBehaviorSanitizer and leak detection. Logs are `tabs-native-build.log`, `tabs-native-ctest.log`, and `tabs-asan.log` in the validation directory. No physical OS touch, native window-leave or full Tabs/scrollbar parity certification is inferred from these tests. --- ## Contextual paragraph text alignment Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TEXT_ALIGNMENT.md # Contextual paragraph text alignment `cui_text_paragraph_colored_aligned` adds physical left, center and right alignment without changing existing function signatures. It accepts the same text, style, wrapping and full-text color spans as `cui_text_paragraph_colored`, followed by a `cui_text_align`. It reserves an available-width paragraph box and positions every final visual row independently within that box. The width comes from this frame's layout, including the parent's padding; it does not read previous-frame bounds. Center uses half the remaining row width; right uses all of it. An overflowing row receives a negative center/right offset, as in the pinned source. Empty and trailing lines retain their normal height without producing a text command. These are physical directions: RTL text does not turn LEFT into logical start. Original paragraph bytes, bidi context, selected byte ranges and intersected color spans are unchanged. The resulting draw command bounds carry the final aligned origin, so existing renderer, clip and copied-snapshot consumers receive that position. No geometry session is retained or newly acquired for alignment itself. `cui_label_options.alignment` forwards the same choice. Zero initialization keeps the existing left/default path, including the legacy paragraph box sizing. Center and right also expand the optional semantic wrapper to available width, so adding a semantic ID does not change the text's alignment. Masked labels continue to submit only bullet bytes, without highlight spans or original semantic names. The old paragraph API, ordinary `cui_text`, contextual line APIs and legacy Label wrapper keep their existing behavior. Applications can still align whole boxes through `cui_box`; text alignment is distinct because rows may have unequal widths. Scrolling/clipping owners retain Core's existing sizing conventions; applications that permit oversized scroll content should supply its intended inner width. The source requirement is frozen upstream kit commit `87d10ae5e1299d1be18670a37570c5402f952e34`, `crates/component/src/label.rs:192-215`: Label forwards its inherited Styled refinement to its containing div. The frozen website documents `.text_center()` and `.text_right()` at `website/component/label.md:36-49`; the actual story exercises both at `crates/story/src/stories/label_story.rs:193-195`. Its pinned upstream-pre 0.3.8 StyledText renderer forwards `text_style.text_align` to wrapped line painting; `src/text_system/line.rs:954-976,1000-1005` defines the signed row-width offset. This API covers those three alignment choices, not arbitrary upstream StyleRefinement, justification, logical start/end, or platform pixel parity. `test_text_alignment_source` checks all three choices at changing current-frame widths, wrapped and unwrapped unequal rows, hard breaks, blank/trailing lines, padding, original RTL paragraphs and intersected spans, copied command lifetimes, invalid alignment/UTF-8 rejection, capacity failure and next-frame recovery, legacy origin preservation, secondary/highlight colors, and masked semantic Label alignment. It is portable C11 and runs headlessly with strict compiler warnings and ASAN/UBSAN. Integrators register this new test and regenerate distribution. --- ## Gradient text Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TEXT_GRADIENT.md # Gradient text `cui_text_paragraph_painted` paints real glyph coverage with a continuous linear color field. One glyph can contain many colors. Wrapping, shaping, fallback, contextual line sources, alignment, carets and selection retain their existing geometry. The paint does not insert extra text runs or split shaping clusters. ```c cui_text_gradient_stop stops[] = { {0, {236, 72, 153, 255}}, {1, {59, 130, 246, 255}}, }; cui_text_paint paint = { .kind = CUI_TEXT_PAINT_LINEAR, .x0 = 0, .y0 = 0, .x1 = 1, .y1 = 0, .anchor = CUI_TEXT_ANCHOR_BLOCK, .stops = stops, .stop_count = 2, }; bool ok = cui_text_paragraph_painted(ui, cui_string("A colorful heading"), 36, 44, (cui_text_style){0}, true, CUI_TEXT_ALIGN_LEFT, paint); ``` Call inside an active frame. Check the returned boolean and frame error. Core copies the 2–8 stops into frame storage; the caller may reuse its array after the call. The emitted stop pointers and text remain borrowed until frame invalidation. A retained draw-list snapshot must deep-copy both. `cui_typography_text_painted` provides the same operation using a typography token. A zero-initialized solid paint uses `paint.color` through the existing solid paragraph path. ## Coordinates and interpolation Input endpoints are finite normalized coordinates in [0, 1], and must differ. Use (0,0) to (1,0) for rightward paint, (0,0) to (0,1) for downward paint, or (0,0) to (1,1) for a diagonal. Reversing endpoints reverses the direction. `CUI_TEXT_ANCHOR_BLOCK` uses the complete paragraph layout container, including hard breaks and empty rows. Every visual row receives the same resolved axis. `CUI_TEXT_ANCHOR_LINE` restarts the axis in each visual row's advance box, after alignment. Ink overhang can extend beyond that box. Anchors use layout line boxes, not glyph ink bounds. Draw commands contain resolved global logical coordinates. A resolved axis collapsed by an empty layout dimension samples its final stop. Stop positions are finite, nondecreasing values in [0, 1]. Outside the first or last stop, extend that stop's color. Equal positions make a hard edge: the last stop at the exact position wins. Project each pixel center onto the axis. Interpolate **premultiplied, encoded sRGB byte channels**, including alpha, then unpremultiply and round to RGBA8. This is neither linear-light nor Oklab interpolation. Transparent red to opaque blue therefore has a blue midpoint with half opacity. Multiply the sampled alpha by glyph coverage. Ancestor opacity is applied once to copied stop alpha in Core. Existing surface compositing follows. This explicit contract does not promise CSS gradient color-space equivalence. ## Renderer support Software and SDL advertise `CUI_RENDER_TEXT_LINEAR_GRADIENT` when a native font is available. They sample actual glyph masks. SDL samples in logical coordinates at the current raster density, preserving Retina positioning and existing solid text cache behavior. Its temporary colored glyph surface is bounded to 4 MiB; allocation or renderer errors return failure. Painted glyph results are not cached by paint identity. The Canvas module `web/modules/cui_text_paint.js` paints one complete shaped visual row into a coverage mask, then samples the same field per physical pixel. It preserves contextual shaping and italic ink overhang. Existing clipping, alpha and compositing apply when the mask is drawn. Its temporary mask is bounded to 4 MiB per row. Positive axis-aligned scale and translation are supported; rotation, shear, invalid paint and oversized masks throw explicit errors. Sokol and SDL_GPU reject gradient draw lists before clearing or submitting any commands. They do not advertise the capability. GPU implementation and hardware acceptance remain future work. Custom renderers must inspect the capability and paint kind, and implement the documented sampling or reject the list. Ignoring paint and drawing a solid substitute is unsupported. Gradient paragraphs currently do not combine with byte color spans. Prepaint writers reject gradient commands explicitly. There are no radial gradients, textures, animated stop ownership, automatic selection colors or binding APIs in this change. Selection highlighting remains a separate draw operation. ## Validation and integration `tests/integration/test_text_gradient.c` checks copied stops, opacity, block and line anchors, wrapping and identical bounds/caret/selection queries, hard edges, transparent interpolation and two colors inside one actual native glyph. `test_text_gradient_sdl.c` checks real captured glyph pixels and clips at densities 1, 1.5 and 2 under private Xvfb. `tests/web/test_text_gradient.py` runs headless Chromium pixel checks at the same densities and compares contextual italic mask coverage with a direct full-line Canvas fill. These checks do not constitute macOS hardware or GPU renderer acceptance. For integration, register the native tests with an explicit font fixture, copy the new browser module with the gallery, and inline the private paint helper when generating the Core amalgamation. Regenerate distribution/SDK artifacts together with the public draw-command layout change. Test native builds through `python scripts/test_local.py --build-dir `; browser tests stay headless. ## Public gallery example Open **Theme** in the public gallery, then change **Typography paint** from **Solid text** to **Linear gradient text**. The typography sample uses the real Core painted-paragraph API with copied pink-to-blue stops; the browser receives the resolved axis and stops from WASM. The font family, size, weight and italic controls continue to apply. The gradient's paragraph wraps within the sample container. The solid sample keeps its existing single-line presentation. The component's copy button supplies the painted-paragraph C example while the gradient is selected. Its **Gradient text** guide link opens this guide. This uses the existing Theme entry and preserves all 78 catalog families. It does not reuse byte color spans as a gradient substitute. `tests/web/test_gradient_gallery.py --directory ` loads the real compiled gallery, changes the public paint control, checks serialized paint stops and resolved coordinates, and reads actual glyph interiors. It exercises desktop and 390px viewports at device pixel ratios 1 and 2, copyable code, the return to solid paint and guide navigation. The guide must be included in the public documentation generator before this integration test runs. --- ## Base Input change and submit notifications Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TEXT_INPUT_EVENTS.md # Base Input change and submit notifications Include `cui/cui_text_input_events.h` for two additive Base-only APIs: `cui_base_input_events` submits the ordinary Input reducer and observes each event; `cui_base_input_reduce_event_events` observes one event for composite controls that already register their textbox and reduce events in queue order. Existing Input signatures, options/results, validation, presentation and mutation policy remain unchanged. A [Styled Input facade](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TEXT_INPUT_STYLED_EVENTS.md) adds the same observer at its existing reduction seam. [Textarea and Editor](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MULTILINE_EVENTS.md) have separately documented aggregate observers. Foreign bindings do not expose these synchronous C observers. ```c static void input_event(void *user, const cui_component_text_event *event) { unsigned *changes = user; if (event->event.kind == CUI_COMPONENT_EVENT_CHANGE) ++*changes; /* Update independent application state. */ /* Inspect text only in this callback; copy with a bounded helper if needed. */ } /* During submission, inside the textbox's same-ID layout box: */ cui_input_event_result result = cui_base_input_events( ui, input_id, cui_string("Name"), edit, &behavior, (cui_base_input_options){0}, (cui_component_text_handler){input_event, &change_counter}); /* Reading result counts must not repeat the callback's side effects. */ ``` This is drawing-free Base behavior. Painting, measured hit testing and styled password mask resources must still use the appropriate existing composition. Do not call an old reducer/Styled Input and this facade for the same events: that would edit the model twice. The single-event API requires prior textbox registration with `cui_interact`, increasing indices and the existing semantic/ paint completion responsibilities. It does not replay the rest of the queue. ## Meaning and ordering CHANGE is a post-mutation notification when the existing single-event reducer reports changed and the committed document revision actually differs. It is not a rejectable proposed value and cannot veto or undo the edit. Selection-only motion, preedit-only updates and rejected/no-op edits do not report CHANGE. A missing observer does not make the control readonly: ordinary editing continues. Use existing `validate`, normalization/format/matcher and readonly options for their documented policies; no new REQUEST or COMMIT is invented here. SUBMIT reports the existing single-line eligible nonrepeated Enter result. It is an intent, not proof of accepted form data or successful validation. Existing modifier, readonly, disabled, composition/preferred-character and consumption behavior is preserved. In particular readonly Input can still report Enter under its legacy policy; disabled Input does not. A rejected text edit followed by an eligible Enter can produce SUBMIT without CHANGE. Multiline editing has no new submit facade in this slice. For each event: existing checked operation and presentation completion, final revision comparison, CHANGE if changed, SUBMIT if eligible, then the next queue event. TEXT/Enter/TEXT/Enter therefore exposes both intermediate committed values, not just the final frame buffer. The whole-frame `control` field is the unchanged legacy aggregate result; `change_count` and `submit_count` count actual observer calls only, saturating at SIZE_MAX with `count_overflow`. No observer means zero counts even when `control.changed` is true. Result reads/copies never dispatch. IME START/UPDATE/CANCEL normally only affect provisional state. A successful COMPOSITION_COMMIT that changes the committed revision reports CHANGE, not a new COMMIT event. Rejected host COMMIT still ends its session using the existing cleanup before observation; rejection does not become a document change. Undo/Redo and synchronous clipboard edits report their actual committed revision changes, retaining existing history/validation exceptions and clipboard errors. No programmatic model edits outside these reducers are retrospectively replayed. ## Evidence, privacy and lifetime `event` carries exact context-local frame/index identity. Known KEY_DOWN/UP origins are KEYBOARD; actual pointer types are POINTER. TEXT and composition origin remain UNKNOWN: a host-delivered text event does not prove a physical keyboard. Presence flags establish evidence. No `HAS_ACTIVATION` or synthesized activation snapshot is attached to text, movement, submit or IME operations. No raw input/clipboard/preedit text is copied into metadata. `before/after` are scalar `cui_edit_state` snapshots with UTF-8 byte offsets, revision and history availability. They are not old text, a diff or a complete multicursor selection set. `text` borrows the **current committed** model buffer only through the callback. Copying the event struct alone does not retain text. Use `cui_component_event_copy_utf8` with caller storage and an explicit byte limit; check its status before retaining the returned owned-buffer span. No implicit per-event document-sized allocation is introduced. For masked Input or any password content purpose, `has_text=false` and `text` is empty/NULL, including SUBMIT. Scalar length/selection/revision metadata remains available; this API does not promise to hide those fields or make logging them appropriate. A nonsecret empty value has `has_text=true` with an empty span. Handler/user are borrowed synchronously. Observers may change unrelated app state and record future edits, omission or teardown. They must not mutate, rebind or destroy the active model/context/state/workspaces/caller buffers, free userdata/resources or recursively submit. Apply such deferred changes only after frame completion and renderer consumption. These are **preconditions**, not runtime guards: the engine acceptance callback's mutation guard does not extend automatically to a post-reducer observer. Existing presentation callbacks retain their previous timing/side-effect contract. Never implement rejection by calling Undo from an observer. ## Verification scope `tests/unit/test_text_input_events.c` exercises ordered TEXT/Enter multiplicity, intermediate values, exact indices/sources, passive counts, missing-observer edits, selection/no-op behavior, Undo/Redo, accepted/rejected IME commits and preedit, secure redaction, synchronous paste, presentation completion before observation, bounded owned copies, invalid single-event indices and explicit composite single-event reduction. Legacy Input/acceptance/password/Questionnaire tests remain the behavioral regressions; native tests use `python scripts/test_local.py --build-dir `. This establishes Base Input notification behavior, not browser/OS IME acceptance, foreign request rejection, full event-family uniformity or general callback reentrancy. Styled and multiline observer guarantees have their own guides. Integrators register the new test and refresh source metadata/generated distributions/SDKs with normal tooling. --- ## Styled Input observers Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TEXT_INPUT_STYLED_EVENTS.md # Styled Input observers `cui_input_events` accepts the same arguments as `cui_input_ex`, followed by a `cui_component_text_handler`, and returns `cui_input_event_result`. For example: ```c cui_input_event_result result = cui_input_events( ui, id, &theme, cui_string("Name"), edit, &state, options, (cui_component_text_handler){on_text_event, app}); ``` The handler receives committed CHANGE and eligible Enter SUBMIT events in input order. A batch can deliver several of each; `result.control` preserves the legacy aggregate result and the counts describe actual callback invocations. A null handler still edits and produces zero callback counts. SUBMIT does not certify form validity. Validation remains in the existing options. Payloads and exact frame/index evidence follow [Base Input](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TEXT_INPUT_EVENTS.md). Text is borrowed only during the callback; use `cui_component_event_copy_utf8` to retain a bounded copy. Masked and password-purpose inputs redact committed text on both event kinds. IME preedit is not a committed CHANGE. The observer runs after each event's presentation completion, before Styled Input finalizes its mask cache and paints. Existing formatting, secure staging and allocation failure behavior remain in the same submission. Failed mask preparation does not notify or apply queued edits. Keep context, edit, state, theme, buffers, workspace and resource descriptors alive and unchanged throughout submission. Observers may update unrelated application state, including a flag to omit the control next frame. They must not edit, rebind, free or destroy these objects, recursively submit UI, or paint. This is a caller precondition, not a runtime guard. Defer removal/destruction until after the frame and renderer have consumed its borrowed resources. The additive facade does not change `cui_input`, `cui_input_ex`, their options or results. [Editor and Textarea observers](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MULTILINE_EVENTS.md) have separate aggregation and timing contracts. Language bindings do not expose these C observers. `tests/unit/test_text_input_styled_events.c` compares legacy and facade results, selection/revision and draw commands, ordered intermediate copies, masked IME, password redaction, missing observers, deferred omission and mask allocation failure. Existing Input acceptance and password tests remain required. --- ## Themes Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/THEME_GUIDE.md # Themes A `cui_theme` C struct carries surface/background, text/muted, primary/on-primary, border/focus/destructive colors and typography/spacing/radius/control height. `cui_theme_light`, `dark`, `high_contrast`, and `terminal` return runtime values. Pass the theme to every styled call; copying and adjusting a token is an explicit per-component override. Prefer component option overrides for local changes: Button has `custom_colors` and Avatar has explicit fallback colors. A theme copy remains useful when a whole subtree shares an override. The public struct stays flat for compatibility; grouping its fields would break existing designated initializers and bindings. Button variant names describe presentation, while `CUI_THEME_BUTTON_*` names describe shared palettes; see [the mapping](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BUTTON.md). In particular, Ghost has no dedicated theme palette enum. The website follows your system light/dark preference by default. Its header palette button selects Follow System, a built-in theme, or one of the pinned named upstream palette adaptations; an explicit choice persists across visits. The Theme preview shows six actual semantic color tokens alongside typography and controls. It is a design-system demonstration, rather than a separate input widget. Native applications choose a `cui_theme` and pass it into styled component calls; system appearance is supplied by the host. High contrast and the terminal theme demonstrate alternative presentation over the same base behavior. Motion uses host frame time and component state; Switch, Shimmer, disclosure, loading indicators and indeterminate Progress expose reduced-motion handling. A comprehensive typography/shadow/motion token system, native theme-file loader and automatic global density provider remain pending. The gallery density selector adjusts its example theme. Intent tokens `warning`, `success`, `info`, and `danger` can be used as filled surfaces or as text/borders on the theme surface. `on_warning`, `on_success`, `on_info`, and `on_danger` supply their filled-surface text colors. All four built-in themes test at least 4.5:1 contrast for each pair and each intent color against its surface. Applications extending a custom theme must set these new fields; the fields append to the prior public structure rather than reordering existing ones. Each theme has `buttons[CUI_THEME_BUTTON_*]` palettes with independent filled normal/hover/active colors, foreground, outlined normal/hover/active colors, outlined foreground and borders. Default, primary, secondary and the four intent palettes can be overridden independently. Link normal/hover/active foregrounds, input background/border, secondary foreground and accent colors are separate. Built-in constructors derive these initial values from CUI's own palette; custom themes must initialize the extended fields. These are solid-color tokens; gradient backgrounds and shadows remain separate rendering capabilities. `spring_control` provides response seconds, damping ratio, epsilon and travel permission (defaults: 0.18 seconds, 1, 0.001, true) for component motion. A theme's motion settings are configuration; components still own their retained motion state and the host supplies time/redraw scheduling. `popover` and `radius_lg` independently style notification surfaces. Built-in themes initialize popover to surface and the large radius to radius+2 (zero remains square); applications can override both without changing ordinary controls. The independent `secondary` background and `secondary_foreground` tokens style semantic secondary content such as Tag. Button palettes remain separately overridable. Tabs have independent `tab_foreground`, `tab_active_foreground`, `tab_active`, `tab_bar`, `tab_bar_segmented`, and `secondary_hover` colors. These do not follow later edits to Button palettes automatically. `spring_move` configures positional motion separately from `spring_control`, defaulting to response0.28seconds, damping0.85, epsilon0.1 and enabled travel. ## Override a token ```c cui_theme theme = cui_theme_light(); theme.radius = 8; theme.font_size = 16; theme.gap = 12; cui_button(ui, id, &theme, cui_string("Save changes"), false); ``` Retain the chosen theme in application state. Change it in response to your host's appearance notification or theme menu callback and invalidate the context. Component values and models remain intact when the theme changes. `cui_theme_preset_get` loads a named palette by index without exposing platform types; see the Theme Presets guide for the pinned collection. --- ## Portable theme registry and host seam Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/THEME_REGISTRY_GUIDE.md # Portable theme registry and host seam This optional module adds bounded named themes and source semantic configuration. Existing `cui_theme` color/button fields, constructors, all 38 preset names and preset colors remain unchanged. It does not automatically change component motion, Core preferences, native fonts, or host theme selection. The reference is upstream kit 0.7.1 commit `87d10ae5e1299d1be18670a37570c5402f952e34`, specifically `crates/component/src/theme/{schema,registry,motion,mod,color}.rs` and Base `theme_tokens.rs`. upstream's serialized shadow layout comes from pinned `upstream-pre=0.3.8`, `src/style.rs` and `src/color.rs`. ## Semantic configuration `cui_theme_semantic_import` accepts the actual standalone source wrapper: ```json {"tokens":{"colors":{"primary":"blue-600/80","foreground":"#1234"}, "radius":{"md":6,"full":9999},"spacing":{"xxl":32}, "typography":{"sans":"My embedded font","md":{"size":18,"line_height":26,"weight":500}}, "shadow":{"sm":[{"color":{"h":0,"s":0,"l":0,"a":0.18}, "offset":{"x":0,"y":1},"blur_radius":2,"spread_radius":0,"inset":false}]}}} ``` This is separate from the legacy ThemeSet schema. Groups are `colors`, `radius`, `spacing`, `typography`, and `shadow`; motion is **not** in this JSON schema. All source semantic groups are represented. There are 17 configurable color roles; snapshot `selection` is an eighteenth role that source configuration does not override. Radius has none/sm/md/lg/xl/full; spacing has xxs/xs/sm/md/lg/xl/xxl. Typography includes sans/mono and xs/sm/md/lg/xl/mono_md, each with size, line_height and numeric weight. Shadow arrays are sm/md/lg with the exact serialized BoxShadow fields above; colors inside shadows use normalized HSLA, not string color names. Optional field `null` preserves an inherited value; non-optional groups/text-style objects require objects. String colors support source hex #rgb/#rgba/#rrggbb/#rrggbbaa and 22 named palette families at scales 50,100,...,900,950; a missing scale uses 500. Black/white and `/opacity` percentages are supported. Hex is RGBA, not ARGB. Arbitrary CSS rgb()/hsl() strings and semantic gradients are not accepted by the pinned source parser. CUI rejects invalid scale/opacity/color values; the source sometimes falls back or silently ignores invalid overrides. CUI also rejects unknown keys, duplicate keys (including escaped duplicates), invalid Unicode/NUL, nonfinite numbers and unsupported fields instead of silently losing data. Decimal parsing is independent of the host numeric locale. Snapshots own font strings and shadows. Defaults project generic colors/radii from the supplied CUI theme, use the source spacing/text scales and source sm/md/lg elevation metadata. Font defaults are logical `.SystemUIFont` and `monospace`: this module performs no platform font discovery. Source shadow metadata has no corresponding legacy CUI shadow-enabled field. Imported families, weights, line heights, scale-only spacing/radius and elevation remain available in the returned snapshot for application-owned UI. Applying tokens updates only generic legacy fields and font_size/radius/radius_lg. Surface maps to popover; muted background and foreground remain distinct. Specialized button, sidebar, tab, chart and other component skins stay unchanged, as in the source's generic projection policy. Selection is not rewritten by this projection. Hosts must explicitly map the returned typography to their font factory/style state; storing a family does not make it render automatically. ## Registry ownership and transactions Allocate a `cui_theme_registry_entry` array, then initialize a registry with it. No registry API allocates or reads files/network. Capacity is 1..256; seeded initialization/reset requires room for exactly 38 frozen presets, including Default Light and Default Dark. Unseeded reset produces an empty registry. Every entry owns its UTF-8 name, semantic font strings and shadow data. Existing `cui_theme` icon loader callbacks/userdata remain borrowed; their host lifetime must cover any use of copied themes. The caller array must outlive the registry and must not be mutated directly while registered. Reset invalidates all prior borrowed query pointers; unused array slots are not a second registry. `put` matches names case-sensitively. Existing names are skipped unless replacement is explicit; skip does not change revision. Sorted queries put defaults first, light before dark, then names using ASCII folding with deterministic UTF-8 byte ordering/ties. This differs from source Unicode lowercasing. No Unicode-insensitive sorting parity is claimed. Legacy `cui_theme_registry_import` accepts source ThemeSet shape: `{name,author,url,themes:[{name,mode,is_default,font.size,font.family, mono_font.size,mono_font.family,radius,radius.lg,shadow,colors:{dotted keys},highlight}]}`. The concrete representable color map is `src/theme/cui_theme_legacy_fields.inc`. It includes 85 source keys; it does not implement every source role, highlight syntax themes, gradient backgrounds or all derived fallback policies. The existing preset adaptations remain the authoritative frozen built-ins. Unsupported legacy fields reject the whole import by default. Explicit `allow_unsupported` permits the mapped subset and returns `partial=true` plus `unsupported_fields`; this is never a claim of full legacy import parity. `is_default` affects ordering, while host selection names remain explicit. Provide a disjoint caller scratch entry array large enough for the complete resulting registry, not merely the new entries. Scratch, live entry storage and JSON source bytes must be mutually disjoint. The optional report must not alias these regions or registry metadata. Scratch contents are temporary and may change on failure; live registry entries/count/revision do not. All new entries are validated before a single commit. Source skip-existing is the default batch policy; explicit replacement is available. Conflicting names within a batch follow the same policy. Imported source strings may be released immediately after the call. Mutation increments revision once per successful batch; skipped-only batches leave it unchanged. Revision overflow rejects. These are UI-thread APIs, not a concurrent registry: transaction atomicity does not imply cross-thread synchronization. Limits are explicit: 64 KiB JSON, 4096 parser nodes, depth 16, 127 UTF-8 bytes per owned name/font, eight shadows per elevation. Parsing uses one shared 64 KiB decode workspace and bounded node storage, with small recursive frames. An unoptimized GCC 64-bit build measures about 232 KiB for the importer plus at most 17 parser frames; the full registry test passes with a 512 KiB stack. ABI/compiler overhead varies; avoid invoking imports from a tiny host thread stack. Windows default-stack Debug testing is required. Use caller heap/long-lived storage for large entry arrays and scratch. Geometry values are bounded to 1e6, text size/line height to 4096 and weight to 1..1000. These stricter CUI bounds reject atomically instead of truncating. The new module has no destruction function because its registry/snapshots own no allocations. ## Motion and appearance `cui_theme_motion_default` represents every pinned MotionTokens field: durations instant/fast/normal/slow = 0/.12/.18/.28 seconds; enter/exit/move cubic Bézier curves (.16,1,.3,1),(.4,0,1,1),(.2,0,0,1); control/move springs .18/1/.001 and .28/.85/.1 with travel enabled; short/medium distances .25/.5 rem. `cui_theme_bezier_sample` solves x before sampling y. Custom finite Bézier y may overshoot; x stays in [0,1]. This exposes the semantic policy's Bézier curves, not every Base Easing enum (steps, piecewise/custom closures). `cui_theme_motion_project` copies the full policy and converts distances using an explicit rem pixel size. Reduced projection sets durations, distances, spring response and travel to zero; it keeps easing/damping/tolerances. Durations/response are bounded to 60 seconds, damping/epsilon and Bézier y to 1000, rem size to 4096, rem distances to 4096 and projected distances to 1e6 pixels. Invalid input leaves output unchanged. Existing component-specific curves (for example Plot's quartic appear curve) are distinct; no implicit adoption changes those defaults. `cui_theme_host_update` accepts caller preferences and selection names. It selects registered light/dark themes in follow-system or forced mode, explicitly projects motion, and maps reduced motion/auto-hide into the copied scrollbar style. High contrast chooses CUI's existing high-contrast palette as a local policy extension; this is not a claim of source/platform high-contrast detection. Host revision must not rewind. The output owns its snapshots and reports visual `changed`, typography `metrics_changed` and separate `motion_changed` flags; repeated identical preferences do not replay changes. The host performs rendering invalidation, font/style rebinding and Core preference calls as needed. No OS observer, portal query, filesystem watcher, async callback or global appearance mutation is installed. A host can read/watch its own appearance and file events, call a transactional import, and then resolve again using registry revision. Registry queries borrow until the next mutation; resolved host snapshots remain owned and valid after registry reset/destruction of caller storage. ## Tests and integration The dedicated portable unit test covers schema/Unicode/colors, ownership, strict capacity failures, structured malformed input, rollback, source skip/replace and case sensitivity, sorting/reset, all 38 preset/button compatibility, full motion projection, host revisions and no replay. An optional primary-source fixture test reads the pinned Ayu/Aurora JSON, verifies strict rejection and observable partial imports, then overwrites source and scratch to check owned entries. Missing reference fixtures return 77. The native test paints imported and high-contrast themes with an actual Noto Sans font/software renderer; missing font fixtures return 77 rather than passing an empty glyph raster. `tests/web/test_theme_registry.py` builds a standalone pinned Zig 0.16.0 WASM probe and runs Playwright 1.58.0/Chromium 1208. Real matchMedia preference events feed the host seam and change actual canvas pixels/typography/motion snapshots. This validates the explicit host contract, not an SDK-installed browser observer. `--chromium` can select revision 1228. Integrator registration: add `src/theme/cui_theme_registry.c` and `cui_theme_motion.c`, package `cui_theme_registry.h`, embed the private JSON, equality, palette and legacy map files in amalgamation, register `tests/unit/test_theme_registry.c` (cui) and `tests/integration/test_theme_registry_native.c` (cui+cui_text+cui_software, skip 77). Default builds stay Rust-free. Root owns CMake/distribution/notice updates. Stale distribution verification is expected before that regeneration. Programmatic `put` treats `.theme` as authoritative for the seventeen shared generic color roles, md/lg radius, and md font size. Conflicting `.semantic` values in those fields are normalized. Selection, other scales/text styles, font families, spacing, shadows, and motion remain intact. Use semantic JSON/the projector or update both snapshots when editing shared semantic values. --- ## TimeField applied change observers Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TIME_FIELD_EVENTS.md # TimeField applied change observers Include `cui/cui_picker_events.h`. Use `cui_base_time_field_events` for semantics without Styled paint, or `cui_time_field_events` for the complete Styled control. Both preserve the old operation and return `cui_picker_event_result`: `changed` is its exact legacy bool; `change_count` counts actual callbacks (0 or 1). The existing entrypoints and options/state layouts are unchanged. ```c static void time_changed(void *user, const cui_time_change *change) { bool *save_needed = user; /* Unrelated host state, not the active time owner. */ *save_needed = true; /* Copy *change to retain previous/value and metadata beyond this callback. */ } /* During UI submission, using existing caller-owned time/state/theme: */ /* cui_picker_event_result result = cui_time_field_events( ui, id, theme, cui_string("Appointment"), &state, &time, (cui_time_options){.seconds = true}, (cui_time_handler){.on_change = time_changed, .user = &save_needed}); */ ``` The callback reports `cui_time previous, value`, with hour 0–23 and minute/second 0–59. Twelve-hour display still reports the original 24-hour model; hidden seconds are retained and participate in validity. An invalid time, even an invalid hidden second, preserves legacy rejection without repair or notification. Required pointers and a nonzero compound ID are checked before legacy work. Styled also requires a theme. Invalid admission returns a zero result. Each facade calls its complete old operation once, then compares all three time fields. Base notifies after final semantics/invalidation. Styled notifies after its existing paint. Missing callback still permits editing and ignores user. Multiple inputs or digit writes yielding one final difference produce one callback; net-zero changes produce none. Focus, digit draft, invalid-digit rejection and segment repair alone are silent. Assigning a new owner value before the call sets its baseline; it is not a programmatic notification. Metadata kind is CHANGE, target is the TimeField compound ID. A proven active frame is present; source is UNKNOWN, without input index or activation. An aggregate can combine multiple routed segment inputs, so it does not promise a unique pointer/key cause. Flags alone establish evidence. There is no request/rejection, COMMIT, SUBMIT, draft lifecycle, IME composition, undo or new text-input support. Disabled/readonly controls preserve old segment/draft repair, focus policy and semantics, with no observation. Actual inert/layout-only scopes likewise suppress new observations while retaining the legacy work; the facade does not override Core routing. The old per-frame bool is preserved independently of notification. Payload is pointer-free and copyable. Callback/user/payload pointer are borrowed synchronously. Do not mutate/rebind/free active time/state/context, input, theme, labels or other active resources, or recursively submit UI from the observer. Unrelated flags and copying are allowed. Defer omission/destruction until outer return and renderer consumption; keep caller resources live through that boundary. These are notifications of already applied edits, not owner-rejectable requests. `tests/unit/test_time_field_events.c` compares legacy/facade Base and Styled state, results, focus/redraw, semantics/tab policy and paint. It covers routed pointer selection plus editing, rollover, digit multiplicity/net-zero edits, 12-hour model, hidden seconds, invalid input, missing observer, actual passive/inert scopes, readonly/disabled maintenance, copied payload and deferred omission. Existing `picker`, `picker_base_only` and `picker_events` remain regression gates. Tests run through the private local wrapper; no browser/native-display parity is implied. C bridge and Python/Node/TypeScript/Go/Rust retain their existing time values and generic CHANGE events. This C facade adds no foreign typed previous/value payload or synchronous callback timing contract. Full TimeField/binding parity is not claimed. --- ## Toolbar command activation Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TOOLBAR_EVENTS.md # Toolbar command activation Include `cui/cui_toolbar_events.h` and call `cui_toolbar_command_events` in a custom Toolbar item renderer. Existing container and command entrypoints remain unchanged. For example, an application-owned adapter can hold its command, handler and last result: ```c typedef struct { cui_toolbar_command command; cui_component_activation_handler handler; cui_toolbar_command_event_result result; } command_item; static void render_command(cui_context *ui, const cui_theme *theme, const cui_toolbar_presentation *p, void *user) { command_item *item = user; item->result = cui_toolbar_command_events(ui, theme, p, &item->command, item->handler); } ``` Use `render_command` as a `cui_toolbar_item.render`, with the adapter as its user. The handler uses the shared user-first signature `void callback(void *user, const cui_component_event_metadata *event)`. `valid` means legacy command/presentation/name validation passed. `submitted` means the command ran during ordinary active submission with a nonzero frame sequence; it does not promise allocation success or paint delivery. Measurement, inert/layout-only and out-of-frame work does not emit an observer callback. `activation_count` counts actual observer calls, zero or one. A missing callback ignores its user and leaves interaction/legacy callbacks intact. The command still interacts once, submits its icon/label/box, calls legacy `on_activate(activate_user)`, then calls the new observer. Repeated accepted inputs coalesce exactly as before; this API does not provide per-input callbacks. Choose one callback/result path for each application side effect to avoid doing it twice. Selected state is caller-owned presentation, not a Toggle CHANGE. Disabled commands do not activate; a disabled Toolbar container suppresses navigation only and may still host enabled commands. ACTIVATE metadata targets the command ID. Evidence freezes immediately after interaction, before icon or legacy callbacks can consume events/change focus. Exactly one accepted activation carries its genuine snapshot/index/source. If multiple activations coalesce, or genuine evidence is absent, only the proven frame is supplied: source UNKNOWN, no invented index or activation snapshot. No REQUEST, rejection, commit, container event, dispatch or binding API is added. Handler/user borrow through the synchronous call. Metadata is pointer-free and copyable beyond frame/context lifetime. Command/presentation/theme/strings/icon resources and context must remain live through outer return and renderer consumption. New observers may copy payloads and set unrelated flags; they must not mutate/free/rebind active resources, recurse, destroy context or unwind across C. Legacy hooks retain their timing and mutations but must leave resources needed by remaining rendering/observation live. Record deferred omission/teardown and perform it after submission and renderer consumption. Omitting a command emits nothing; there is no retained registration or replay. --- ## Gallery touch coverage Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TOUCH_COMPONENT_COVERAGE.md # Gallery touch coverage Audit baseline: release `65da7b2`. The final run passed 41 of 42 assertions across 36 families; Carousel failed its swipe assertion. All 78 stories rendered without page errors. This inventory covers all 78 manifest families. Rendering a story is an inventory check, not touch verification. “Verified” means only the named representative assertions passed using actual Chromium CDP `Input.dispatchTouchEvent` contacts. It does not mean every variant, platform or interaction in that family passed. The next16 integration fixes Carousel contact lifetime/cancellation ordering and text-area caret reveal overriding a pan. Its local Chromium rerun passes all 42 representative assertions; the historical baseline failure above remains recorded. Additional control and clipboard coverage is recorded in [the follow-up audit](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TOUCH_FOLLOWUP.md). These checks do not establish physical-device or complete per-family acceptance. Run from the repository root after building the WASI gallery: ```sh python scripts/build_web.py --zig /path/to/pinned/zig uv run tests/web/test_touch_components.py --chromium /path/to/chromium ``` The default command fails on a failed interaction. `--allow-defects` continues and returns success for evidence collection; inspect the JSON report and printed failures before assessing readiness. `--report PATH` saves semantic inventory and assertion results. `--inventory-only` only renders the 78 stories. Dependencies are pinned in the test script. Configuration inputs create fixtures but do not perform the asserted component gestures. Textarea uses one row to produce overflow. Editor receives keyboard Enter events to create overflow before its touch pan assertion; this does not verify touch typing or IME. Component taps, drags, pans and pinch use CDP contacts, never mouse emulation or direct Core event injection. Disabled Button, List option and Resizable assertions verify unchanged state. Button backtracking drag and nested Dialog checkbox drag verify ghost-tap suppression. Dock moves a real tab between workspace regions. VirtualList asserts a changed bounded row window; DataTable tests both pixel scrolling and visible grid-cell selection. ## Matrix Applicability describes the default gallery fixture. “Conditional” means a display or container family can have interactive options or children; those paths still need coverage. “Not applicable” means no intrinsic touch action is exposed in this fixture, not that the family was verified to pan its ancestors. Status `Unverified` always remains explicit for those rows. | Family | Applicability | Status | Assertions or remaining scope | | --- | --- | --- | --- | | Accordion | Applicable | Verified | tap expands Configuration. | | AlertDialog | Applicable | Verified | touch opens and dismisses overlay. | | Alert | Not applicable | Unverified | Default fixture has no intrinsic touch action. | | Attachment | Conditional | Unverified | Default fixture displays content; optional actions/interactive children unverified. | | Avatar | Conditional | Unverified | Default fixture displays content; optional actions/interactive children unverified. | | Badge | Conditional | Unverified | Default fixture displays content; optional actions/interactive children unverified. | | Bubble | Conditional | Unverified | Default fixture displays content; optional actions/interactive children unverified. | | Button | Applicable | Verified | tap; backtracking drag suppresses ghost tap; disabled tap. | | Checkbox | Applicable | Verified | two taps toggle checked state. | | Clipboard | Applicable | Unverified | Copy action and platform clipboard unverified. | | Collapsible | Applicable | Verified | tap expands Show details. | | DropdownButton | Applicable | Unverified | Primary/split popup actions unverified. | | Empty | Not applicable | Unverified | Default fixture has no intrinsic touch action. | | Focus Trap | Applicable | Unverified | Touch focus containment unverified. | | GroupBox | Conditional | Unverified | Default fixture displays content; optional actions/interactive children unverified. | | HoverCard | Applicable | Verified | touch focus reveals profile card. | | Icon | Conditional | Unverified | Default fixture displays content; optional actions/interactive children unverified. | | Image | Conditional | Unverified | Default fixture displays content; optional actions/interactive children unverified. | | Kbd | Not applicable | Unverified | Default fixture has no intrinsic touch action. | | Label | Not applicable | Unverified | Default fixture has no intrinsic touch action. | | Marker | Not applicable | Unverified | Default fixture has no intrinsic touch action. | | Message | Conditional | Unverified | Default fixture displays content; optional actions/interactive children unverified. | | MessageScroller | Applicable | Verified | vertical pan consumes logical pixels. | | Notification | Conditional | Unverified | Default fixture displays content; optional actions/interactive children unverified. | | Pagination | Applicable | Verified | touch advances current page. | | Progress | Not applicable | Unverified | Default fixture has no intrinsic touch action. | | Radio | Applicable | Verified | tap selects Priority. | | Rating | Applicable | Verified | touch selects five-star rating. | | Shimmer | Not applicable | Unverified | Default fixture has no intrinsic touch action. | | Skeleton | Not applicable | Unverified | Default fixture has no intrinsic touch action. | | Spinner | Not applicable | Unverified | Default fixture has no intrinsic touch action. | | Stepper | Applicable | Verified | touch selects Review step. | | Switch | Applicable | Verified | two taps toggle checked state. | | Tag | Conditional | Unverified | Default fixture displays content; optional actions/interactive children unverified. | | Toggle | Applicable | Verified | two taps toggle pressed state. | | Tooltip | Applicable | Verified | touch focus reveals tooltip content. | | Calendar | Applicable | Verified | touch selects calendar day. | | ColorPicker | Applicable | Unverified | Swatch and continuous color drag unverified. | | Combobox | Applicable | Unverified | Touch suggestion selection unverified. | | DatePicker | Applicable | Unverified | Calendar popup selection unverified. | | Editor | Applicable | Verified | vertical pan consumes pixels after keyboard-created overflow. | | Form | Applicable | Unverified | Submit and touch validation flow unverified. | | Input | Applicable | Verified | touch focuses editable control (text/IME not asserted). | | Input Group | Applicable | Unverified | Grouped action/focus flow unverified. | | NumberInput | Applicable | Verified | touch focuses editable control (text/IME not asserted). | | OtpInput | Applicable | Verified | touch focuses editable control (text/IME not asserted). | | Questionnaire | Applicable | Unverified | Question transitions and answers unverified. | | Select | Applicable | Verified | touch opens popup, selects Priority, closes popup. | | Slider | Applicable | Verified | horizontal touch drag changes value. | | Speech | Applicable | Unverified | Speech input/device permission flow unverified. | | Textarea | Applicable | Verified | vertical pan consumes pixels in overflowing one-row fixture. | | TimeField | Applicable | Verified | touch focuses editable control (text/IME not asserted). | | Carousel | Applicable | Unverified | FAILED: slow horizontal swipe leaves selected page unchanged; see defect below. | | DescriptionList | Not applicable | Unverified | Default fixture has no intrinsic touch action. | | Dialog | Applicable | Verified | touch opens and dismisses overlay; nested modal blocks parent scrolling and preserves drag-vs-tap. | | Dock | Applicable | Verified | touch drags tab from center into right edge. | | List | Applicable | Verified | touch selects Priority option; disabled option preserves selection. | | Menu | Applicable | Verified | touch opens menu and invokes option. | | Popover | Applicable | Verified | touch opens and dismisses overlay. | | Resizable | Applicable | Verified | touch resizes panel; disabled resize remains locked. | | Root View | Conditional | Unverified | Default fixture displays content; optional actions/interactive children unverified. | | Scrollable | Applicable | Verified | vertical pan consumes logical pixels. | | Settings | Applicable | Unverified | Navigation and compound control/scroll behavior unverified. | | Sheet | Applicable | Verified | touch opens and dismisses overlay. | | Sidebar | Applicable | Verified | vertical pan consumes logical pixels; touch selects Files. | | StatusBar | Conditional | Unverified | Default fixture displays content; optional actions/interactive children unverified. | | Tabs | Applicable | Verified | tap selects Activity. | | Theme | Not applicable | Unverified | Default fixture has no intrinsic touch action. | | TitleBar | Conditional | Unverified | Default fixture displays content; optional actions/interactive children unverified. | | Toolbar | Applicable | Unverified | Grouped action/overflow behavior unverified. | | Tree | Applicable | Unverified | Touch selection/expand and scroll unverified. | | VirtualList | Applicable | Verified | vertical pan consumes logical pixels; touch changes bounded visible row window. | | Chart | Not applicable | Unverified | Default fixture has no intrinsic touch action. | | Command | Applicable | Unverified | Command selection and confirmation unverified. | | DataTable | Applicable | Verified | vertical pan consumes logical pixels; touch selects actual visible grid cell. | | Plot | Applicable | Verified | two actual touch contacts zoom opted-in viewport. | | Table | Not applicable | Unverified | Default fixture has no intrinsic touch action. | | TextView | Applicable | Unverified | Text selection, links and enabled scrolling unverified. | ## Confirmed defect **Carousel slow swipe fails to advance.** On the default horizontal `Workflow carousel`, the viewport is 716 logical pixels wide. Start in its content center, send four touch moves totaling 65% of its width to the left, with 50ms between moves, then release. `gallery_carousel_stats(0)` remains at page 0 instead of advancing. This happens with actual PointerEvents generated from CDP contacts. The test preserves this failed assertion rather than changing the source under audit. The root is a horizontal scroll owner. Core translates touch pan into precise scroll events. Carousel currently treats a gap of 28ms as a wheel-burst end and snaps a partial move before the next touch move. This is a source-based explanation to investigate, not a verified fix. Relevant owners should preserve the continuous contact lifecycle or grant explicit drag ownership; normal slow finger movement must not require sub-28ms events. ## Remaining coverage Nested **modal** ownership is verified: dragging in the child modal neither scrolls the obscured parent nor toggles its checkbox; a later tap toggles the child checkbox. Nested **scroll boundary chaining** is unverified in this gallery audit: no default fixture has two simultaneously overflowing scroll owners. Core headless nested-chain tests are separate evidence and do not establish gallery/component coverage. Add an actual nested overflow fixture before marking this behavior verified here. These assertions run in headless Chromium with emulated touchscreen contacts. Physical Android/iOS hardware, Safari, Firefox, native SDL, multiwindow routing, pen contacts, custom cursors, every disabled variant, cancellation during unmount and all 78 family variants remain unverified by this suite. Public shared cursor/state hooks and prior Core/SDL tests are documented in [INTERACTION.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/INTERACTION.md); they are not a substitute for this component inventory. Input focus assertions do not establish soft-keyboard, composition, text-selection or IME behavior. A display family marked not applicable still depends on its containing scroll/viewport owner for gestures. Validation for this audit branch: warning-enabled CMake/Ninja build passed; local CTest passed 88/88. No source behavior or existing test files were changed. --- ## Touch follow-up audit Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TOUCH_FOLLOWUP.md # Touch follow-up audit Baseline: `fda9f70` on `integration/next16`, following the original 78-family [coverage inventory](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TOUCH_COMPONENT_COVERAGE.md). This follow-up adds actual Chromium CDP touch contacts for ten interactive families. It changes no component, gallery, Core or adapter source. It does not establish complete family parity. Build the gallery with the pinned Zig toolchain, then run: ```sh uv run tests/web/test_touch_more.py --chromium /path/to/chromium ``` The test imports the existing `Audit` helper from `test_touch_components.py`. Both scripts must remain adjacent. Its Playwright dependency is pinned. The default command returns failure when an assertion fails. `--allow-defects` is an evidence-collection mode that returns success despite failed assertions; inspect the printed results and JSON report. `--report PATH` overrides the default `/tmp/cui-touch-followup-report.json`. `--inventory-only` records semantics without running gestures and must not be interpreted as interaction verification. All asserted component actions use `Input.dispatchTouchEvent`, producing browser PointerEvents with actual contact identities. No component action substitutes a mouse click, accessibility DOM click or direct `gallery_event` call. DOM options only configure fixtures. Combobox receives ordinary keyboard text to prepare its query; focusing, suggestion selection and outside dismissal use touch. Clipboard permissions are granted to the browser context, and the test reads the real `navigator.clipboard` contents after a touch copy action. It never stubs the host clipboard provider. ## Results The follow-up passed 15 of 16 cases. One controlled ToggleGroup semantic assertion failed. These results cover representative gallery behaviors only. | Family | Status | Assertions and limits | | --- | --- | --- | | DropdownButton | Verified | Touch primary action increments invocation count; split menu selects a real item and closes; outside touch dismisses; disabled primary and menu triggers do neither. Submenus remain unverified. | | Combobox | Verified | Touch focuses the query, selects the matching Banana option, closes the popup, and exposes Banana as selected when the query reopens it. Outside dismissal and disabled touch are asserted. Query setup uses keyboard text. Multi-selection/chip removal and touch text entry remain unverified. | | Command | Verified | Enabled row confirms and invokes its callback; disabled row does not confirm. A backtracking row drag causes no ghost confirmation. Touch opens the modal palette, confirms a row, and dismisses outside. Filtering and touch text entry remain unverified. | | Calendar | Verified | Touch selects a date; disabled touch on another date preserves the first selection. Month/year navigation, ranges and disabled-date constraints remain unverified. | | DatePicker | Verified | Touch opens the calendar, selects a date and closes with updated trigger text; outside touch dismisses; disabled trigger stays closed. Range mode remains unverified. | | ColorPicker | Verified | Touch Red-channel drag changes RGBA; disabled drag preserves RGBA. Palette touch selects exact `0x5865F2FF`; a two-dimensional saturation/value drag changes color. Screen EyeDropper and other color models remain unverified. | | Clipboard | Verified | Trusted touch copy writes `Hello from CUI` into the actual clipboard; touch read displays that content. Disabled copy preserves a distinct sentinel. Platform permission-denial paths remain unverified. | | Toggle / ToggleGroup | Partial; defect | Standalone toggles twice and ignores disabled tap. Multiple selection retains Bold and Italic; disabled group preserves selection. Single selection updates the model correctly but leaves incorrect checked semantics, as detailed below. | | Tree | Verified | Touch expands docs and exposes children, selects core.c, ignores a disabled base.c selection, and collapses src to remove its children. Overflow scrolling and custom row slots remain unverified. | | Focus Trap | Verified | Touch opens the scope, focuses its first child, closes it, and restores opener focus. Keyboard containment is outside this touch assertion; nested traps remain unverified. | Combobox query text and selected option are independent in the current API. The test checks the selected option rather than requiring the query to be replaced with its label. Likewise, the Command gallery's confirmation callback deliberately keeps its surface open; the test checks confirmation and a separate outside dismissal rather than inventing automatic close behavior. ## Confirmed defect With the Toggle gallery in single-selection mode, Bold initially selected, touch Italic and then idle for 150ms after the normal post-release wait. The controlled model reports `[Bold=0, Italic=1, Underline=0]`, while checked semantics report `[1, 1, 0]`. The selected values are therefore correct but their exposed state is wrong. The failing case is retained in the default test command. The gallery callback replaces sibling values while the group is being rendered. An earlier sibling may already have been painted or registered before that callback changes it. This is a source-review hypothesis for the component/gallery owner; this audit does not claim a fix or claim that all controlled groups behave this way. A fix must make rendered and semantic states agree after the callback without requiring a later unrelated input event. ## Integrated correction The integrator fixes controlled sibling semantics and requests repaint without replaying callbacks (`2ad721c`). The integrated Chromium follow-up passes all 16 assertions at source `57f8066`; the original baseline defect above remains historical evidence. ## IME scope and remaining work The separate [IME documentation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/IME.md) and `test_ime.py` explicitly cover four consumers: Input, Textarea, Editor and Questionnaire input controls. This follow-up does not run composition assertions. Ordinary keyboard preparation of a Combobox query is not IME verification. NumberInput, OtpInput and Combobox composition, preedit rendering, commit/cancel and undo remain unverified here; this audit makes no claim that every textbox has those capabilities. All gestures in this follow-up run in headless Chromium. Physical touchscreen hardware, Safari/Firefox, native SDL, all variants, focus transfer during active composition, permission-denied clipboard access and every remaining interactive family are still outside its verified scope. Nested overflowing scroll boundary chaining remains the gallery coverage gap described in the original inventory. Validation: warning-enabled CMake/Ninja build (`-Wall -Wextra -Wpedantic -Werror`) passed; local CTest passed 90/90. The new CDP suite reports its known failing ToggleGroup assertion independently of those existing native tests. --- ## Mobile page touch navigation Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TOUCH_PAGE_NAVIGATION.md # Mobile page touch navigation The browser host now lets a single vertical contact navigate the document when Core and its component reducers leave the movement unconsumed. This follows the `3c8879ef` read-only audit (based on `3c992ec`), which passed only 3 of 10 navigation assertions. The implementation branch starts at `d56820e`; its strict mobile suite passes 19/19 assertions. This is headless Chromium with a 390 × 844 mobile viewport and actual `Input.dispatchTouchEvent` contacts. It does not establish physical Android/iOS, Safari or Firefox coverage. All 78 manifest families remain present. After building the gallery with the pinned Zig toolchain, run: ```sh uv run tests/web/test_touch_page_navigation.py --chromium /path/to/chromium ``` The script imports the adjacent `test_touch_components.py` helper and pins Playwright. The default command fails on any assertion failure. `--allow-defects` is evidence-collection mode and must not be treated as a passing result. The JSON report defaults to `/tmp/cui-touch-page-navigation-report.json`; override it with `--report PATH`. ## Ownership and lifecycle Canvas retains `touch-action:none` so the browser cannot steal intrinsic control drags, internal scrolling or opted-in viewport gestures. The private bounded [host policy helper](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/web/touch_page_host.h) examines actual Core dispatch after component reducers. It uses Core targets, consumption, clipped hover/scope queries, and completed semantic parents; JavaScript does not repeat hit testing. The host gives Core first refusal. Consumed moves stay entirely with Core. A single contact can claim page navigation only after eight pixels of dominant vertical movement and an unconsumed move. Modal scopes deny fallback, including hits on disabled modal content. Slider, Scrollbar, Separator, explicit drag priority and opted-in gesture owners reserve their streams. Protected ownership is retained from the initial down event. Completed semantic parents protect custom drag ancestors as well as the direct target. An unconsumed scroll can retain a nonzero Core target at a boundary: persistent ownership and failed ancestor deferral do not necessarily clear it. The helper therefore uses the reducers' final consumption rather than requiring target zero. If a movement is partially consumed at a boundary, its entire delta stays with Core; page handoff waits for a later unconsumed move. No residual delta is guessed. On page claim the browser queues exactly one Core touch cancellation, clearing pressed/captured component state. It retains browser pointer capture until the contact ends and applies later page movement from client coordinates. It does not feed the ended Core contact further moves or releases. A second contact blocks page movement until the stream ends; a new finger arriving after page claim is also kept out of Core to avoid becoming a fresh primary tap. A later single-contact gesture starts normally. Cancellation, window blur and navigation clear browser host contacts. Both C and JavaScript retain at most 16 contacts. The helper retires raw pointer releases and Core-converted `SCROLL/ENDED` and `GESTURE/ENDED` releases. Missing those converted endings would falsely mark later gestures as multiple contacts. Synthetic capture-handoff cancellation is kept separate from physical contact termination. ## Wrapper padding The audit separately reproduced a trap in canvas wrapper padding. Changing only `.canvas-wrap` from `overflow:auto` to `overflow:clip` restored native vertical page scrolling there. Canvas remains responsive at 100% width; horizontal Scrollable/VirtualList behavior remains inside Core. Code blocks retain their separate `overflow:auto` behavior. The full browser suite, including 390px layout, passed with this narrow change. Preview-card styling is unchanged. ## Verified assertions | Beginning or owner of gesture | Verified result | | --- | --- | | Body margin and canvas wrapper padding | Native vertical document pan works. | | Passive Avatar, Image and Label canvas | Vertical document pan works. Label is the typography-content representative; no manifest family was added. | | Button drag without internal owner | Navigates page without activating the button. | | Button backtracking drag, then actual tap | Drag produces no ghost activation; the next tap activates exactly once. | | Scrollable with remaining range | Consumes exactly 110 logical pixels while the page stays fixed. | | Scrollable bottom and top boundaries | Internal offset stays at 458 or zero; unconsumed vertical pan navigates the page. | | Slider and Resizable | Relevant control values change while page position stays fixed. | | ColorPicker saturation/value plane | Two-dimensional drag changes RGBA without moving the page. | | Plot | Opted-in pan and actual two-contact pinch remain with the viewport; pinch changes its domain. | | Dialog with disabled opener | Touch on modal content cannot navigate the document; close still works. | | Multiple contacts | Do not navigate the page; a later single contact can navigate. | | Second finger after page claim | Cannot ghost-activate a button; a later ordinary tap works. | | Physical cancellation after page claim | Stops movement; Core cancellation count increases exactly once and later taps work. | The new [headless C test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_touch_page_host.c) uses real Core scenes to exercise passive eligibility, direct/ancestor drag protection, viewport protection, modal denial including disabled content, consumed-move refusal, boundary routing, converted terminal-event retirement, multitouch recovery, cancellation and bounded contact capacity. The integrator registers it in the native and WASI suites. ## Validation and limits Warning-enabled native CMake/Ninja build passed. The new C test separately compiled with `-std=c11 -Wall -Wextra -Wpedantic -Werror` and passed. Existing full CTest ran 90/91: only the generated-distribution check failed because root-owned distributions await regeneration; the earlier RTL render regression is absent at this implementation baseline. Real CDP suites passed: page navigation 19/19, original touch smoke, component coverage 42/42, follow-up coverage 16/16, and full browser coverage of all 78 stories, mobile 390px layout and `/cui/` hosting. These are representative tested behaviors, not complete family or device parity. Canvas page fallback follows finger movement and does not synthesize fling inertia. Physical mobile browsers, soft-keyboard/IME navigation, browser zoom, all custom gesture combinations and every component variant remain unverified. The partial-boundary-consumption limitation above is deliberate. Unexpected browser pointer capture loss clears the host contact and cancels Core once. A real CDP contact with `releasePointerCapture` verifies ghost suppression and a usable subsequent tap. Normal release after pointer-up finds no contact. --- ## Tree applied selection events Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TREE_EVENTS.md # Tree applied selection events Include `cui/cui_tree_events.h`. `cui_tree_reduce_events`, `cui_base_tree_events` and `cui_tree_events` add synchronous selection observers to the corresponding legacy calls. They edit the same caller-owned selected key. A missing observer still permits editing; its user pointer is ignored. No request/rejection API is implied. Required pointers and nonzero compound ID are checked before admission; invalid arguments return `result.error = CUI_TREE_INVALID` without legacy work. ```c static void selection_changed(void *user, const cui_tree_selection_change *change) { bool *needs_save = user; /* unrelated application state */ *needs_save = true; /* Copy *change here to retain it after this callback. */ } /* During UI submission, with existing caller-owned model/state/selected: */ /* cui_tree_events(ui, id, theme, model, &state, &selected, options, (cui_tree_handler){.on_selection_change = selection_changed, .user = &needs_save}); */ ``` Each different selected-key write emits one CHANGE immediately after the write. A→B→A emits two callbacks even when legacy `result.selection_changed` is false. `selection_count` counts actual observer calls, saturating at SIZE_MAX with `count_overflow`; `result` preserves every legacy aggregate field. Already-selected row invocation emits no selection CHANGE. Manual selection suppresses navigation writes but retains existing row-invocation selection. Cursor repair, scrolling, search timeout and programmatic model edits do not emit selection events. Payload `previous`/`value` are stable keys; `node_index` is the current affected model slot, not stable across reorder and not an input index. `event.target` is the compound ID. Genuine accepted activation snapshots are copied when available and retain their original row/toggle `activation.target`. Normal Tree reduction runs before current-frame semantic submission, so snapshots need not be available: fallback carries only proven active frame, actual event index and known event-type source. Typeahead TEXT has UNKNOWN source; no keyboard device is inferred. Presence flags are authoritative. No observer runs for disabled/passive/layout-only work. Notifications precede existing later cursor/focus/scroll/semantic/paint work: row selection notifies before cursor assignment; navigation notifies after cursor assignment but before focus. Do not assume operation-final state or semantics in an observer. Reducers, consume order, visible-row layout and paint run once. Callbacks, user and payload pointer are borrowed during the call. Payload values are pointer-free and copyable. Never mutate/rebuild/free active model/nodes/labels, expanded array, selected key, state, input or context, or recursively submit UI from an observer. Unrelated app flags may change. Defer structural changes, omission and teardown until outer return plus renderer consumption. Nodes/expanded arrays remain borrowed until next successful model rebuild; model must be explicitly destroyed. Omission does not reset it. There is no new bridge/language binding API. ## Expansion Set `handler.on_expansion_change` to receive `cui_tree_expansion_change` with key, current model index and applied `previous`/`expanded` bools. `expansion_count` counts actual calls. Repeated toggle or Left/Right input preserves each actual transition; leaf/no-op requests are silent. Programmatic `cui_tree_set_expanded`, direct external edits and rebuilds are outside these UI observers. The callback follows the setter's rebuild attempt. On a valid unchanged borrowed model, visible mappings already match the new bool; existing later cursor, focus, consume and semantic submission have not moved. Capture key/index values rather than pointers into the model's alternating mapping banks. The legacy setter writes the bool before rebuilding and does not roll it back on rebuild failure: a real bool difference is still notified while the old aggregate result remains unchanged. Do not assume updated mappings on failure. Existing valid-data/lifetime preconditions still apply; observer callbacks cannot edit the borrowed model or expanded array. Toggle-origin activation evidence, when available, retains its toggle ID; Left/Right navigation has actual keyboard/index evidence without manufactured activation. ## Row activation Set `handler.on_activate` for `cui_tree_activation`. Each existing row-invocation branch emits ACTIVATE after selected/cursor/legacy `activated` are assigned, including an already-selected row. Any selection CHANGE precedes it and shares the same frozen originating evidence. `activation_count` records actual callback count; legacy `result.activated` still retains only the last key. A toggle expands without invoking the row; navigation, search, repair and scrolling do not invent invocation. Missing activation observer preserves the old action/result. All counts independently saturate at SIZE_MAX and share `count_overflow`. Current Core does not offer accessibility ACTIVATE for TREEITEM roles; querying support returns false and queuing it is rejected. This facade does not change that. Branch toggles have Button semantics and can support accessibility activation; the submit-before-reduce-only composition can provide accepted copied evidence. Normal Tree remains reduce-before-submit; this guide makes no new accessibility routing guarantee for it. Existing focus/navigation semantics stay unchanged. No move, rename, context-menu, async-load or rejectable expansion hook is added. Those are separate owner operations. C bridge and Python/JS/TS/Go/Rust continue to use their existing aggregate/net-change paths; they do not acquire per-transition C callbacks or row-activation forwarding from this header. --- ## Typography controls Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TYPOGRAPHY.md # Typography controls `cui_text_ex` combines a logical pixel font size, an optional logical line height, a color, and `cui_text_style`. Styles offer Normal, Medium, Semibold, and Bold weights, independent italic and monospace flags, and an explicit family ID. Use `cui_text_line` for unwrapped text with the same controls. The basic `cui_text` API uses the default family's regular face and its measured height. Font size and line height are independent: use the selected face's actual font metrics when alignment requires its ascent, descent, or leading. For reusable application styles, use the shipped header-only [`cui_typography_roles` and `cui_typography_token` helpers](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TYPOGRAPHY_TOKENS.md). They resolve caller-owned body, heading and code defaults into a copy that can be overridden locally; they do not mutate the theme or a global current style: ```c #include "cui/cui_typography.h" cui_typography_token title; if (cui_typography_resolve(&roles, CUI_TYPOGRAPHY_HEADING, &title)) { title.align = CUI_TEXT_ALIGN_CENTER; bool submitted = cui_typography_text(ui, cui_string("Workspace"), title, ink); (void)submitted; /* Handle failure and end-frame diagnostics in the host. */ } ``` Here `roles` and `ink` are application-owned values; call inside an active frame. Resolution validates only the selected role and preserves output on failure. See the token guide for a full role initializer, color spans, exact native-face registration, and wide/narrow composed tests. Use `cui_typography_text_painted` for [linear gradient glyph paint](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TEXT_GRADIENT.md) on supported renderers. Tracking, variable axes and arbitrary numeric weights remain future work. Family IDs are application-defined `uint32_t` keys. Zero retains the default family. Register regular and variant faces for a named family on the same `cui_font` used by the context's measurement callbacks and renderer: ```c const uint32_t editorial = 7; cui_text_style body = {.family = editorial}; cui_text_style title = {.family = editorial, .weight = CUI_TEXT_WEIGHT_BOLD}; /* Check registration results and supply application-owned font paths. */ bool ready = cui_font_register_style(font, body, body_path) && cui_font_register_style(font, title, bold_path); if (ready) { cui_text_metrics_changed(ui); /* Between frames, before the next layout. */ /* Inside the next frame: */ cui_text_ex(ui, cui_string("Editorial heading"), 30, ink, 36, title); } ``` Registration is per call, so a successful regular registration remains if the following bold registration fails. For an atomic application font switch, prepare a separate font object and its registrations, then update the wrapper host and renderer references together between frames and invalidate affected contexts. If the context uses the font directly as its fixed `measure_user`, recreate that context to bind another font, or change registrations on the existing font. Keep the old font alive until its outstanding draw lists have been consumed. Fonts and paths are explicit resources; these APIs do not fetch fonts, discover installed families, or synthesize bold or italic faces. An unset named-family variant uses that family's regular face. Unknown families fall back to the default family's requested style and then its regular face. The native `cui_font_measure`, `cui_font_measure_styled`, and `cui_font_get_metrics` functions already accept `void *` as their first parameter and match the corresponding `cui_config` callback types. Direct assignment is valid when `measure_user` is the font itself. No function-pointer cast is needed. If your user pointer contains application state instead, use wrappers that extract its font, as in this complete C11 program: ```c #include "cui/cui_text.h" typedef struct { cui_font *font; } text_host; static cui_size text_measure(void *user, cui_str text, float size) { text_host *host = user; return cui_font_measure(host->font, text, size); } static cui_size text_measure_styled(void *user, cui_str text, float size, cui_text_style style) { text_host *host = user; return cui_font_measure_styled(host->font, text, size, style); } static bool text_metrics(void *user, float size, cui_text_style style, cui_font_metrics *out) { text_host *host = user; return cui_font_get_metrics(host->font, size, style, out); } int main(int argc, char **argv) { /* Paths: default regular face, editorial regular face, editorial bold face. */ if (argc != 4) return 1; text_host host = {.font = cui_font_open(argv[1])}; if (!host.font) return 1; cui_text_style body = {.family = 7}; cui_text_style title = {.family = 7, .weight = CUI_TEXT_WEIGHT_BOLD}; if (!cui_font_register_style(host.font, body, argv[2]) || !cui_font_register_style(host.font, title, argv[3])) { cui_font_close(host.font); return 1; } cui_context *ui = cui_create((cui_config){ .measure = text_measure, .measure_styled = text_measure_styled, .font_metrics = text_metrics, .measure_user = &host }); if (!ui) { cui_font_close(host.font); return 1; } if (!cui_begin_frame(ui, 600, 300, .016f)) { cui_destroy(ui); cui_font_close(host.font); return 1; } cui_text_ex(ui, cui_string("Editorial heading"), 30, (cui_color){20, 20, 20, 255}, 36, title); cui_text_ex(ui, cui_string("Body copy"), 16, (cui_color){20, 20, 20, 255}, 24, body); cui_draw_list draws = cui_end_frame(ui); int status = draws.count && cui_last_error(ui) == CUI_OK ? 0 : 1; /* A real host paints draws with host.font before ending its lifetime. */ cui_destroy(ui); cui_font_close(host.font); return status; } ``` Save the complete program as `typography.c`. With the default native library build and existing FreeType/HarfBuzz development packages, compile it with: ```sh cc -std=c11 -Wall -Wextra -Wpedantic -Werror -Iinclude typography.c build/libcui_text.a build/libcui.a $(pkg-config --cflags --libs freetype2 harfbuzz) -lm -o typography ./typography /path/default-regular.ttf /path/editorial-regular.ttf /path/editorial-bold.ttf ``` Link the optional native `cui_text` adapter and Core; its FreeType/HarfBuzz requirements are described in [TEXT.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TEXT.md). This example submits a draw list; the application supplies its renderer and window/event loop. The host struct and font must outlive the context's measurement callbacks and every draw that uses them. A custom renderer maps the complete style, including family, to the same faces used for measurement. Reuse stable family IDs, and call `cui_text_metrics_changed` between frames in every affected context after changing registrations. See [TEXT.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TEXT.md) for ownership, fallback ordering, native registration, thread confinement, and headless test fixture details. These controls are text primitives; they do not imply that every component has a per-control family option or that TextView supports arbitrary family changes within a shaped run. --- ## Typography roadmap grounded in the current implementation Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TYPOGRAPHY_ROADMAP.md # Typography roadmap grounded in the current implementation Audit baseline: `integration/density-reconcile`, commit `b96c6844`. This is a proposal; the declarations below are illustrative and are not shipped APIs. No font dependency, production code or renderer was changed for this audit. Subsequent implementation added [body/heading/code tokens](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TYPOGRAPHY_TOKENS.md) and [linear gradient text](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TEXT_GRADIENT.md) for software, SDL and Canvas, plus [cluster letter spacing](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/LETTER_SPACING.md) for native Bidi/software/SDL. Those guides and current public headers define the shipped APIs. The proposed broader authoring declarations below remain design notes, especially browser tracking, numeric weights/stretch and variable axes. ## What applications can use today | Request | Current support and evidence | Remaining work | | --- | --- | --- | | Body, heading, mono families | `cui_text_style.family` is an application `uint32_t` ID. `cui_font_register_style` opens/owns a face; `cui_font_set_style` borrows one. See `include/cui/cui_text.h`, `src/text/cui_text.c:family_find`, `docs/TYPOGRAPHY.md`. | Semantic roles and convenient theme defaults; automatic OS family lookup is absent. | | Weight, italic, monospace | Four weights: normal, medium, semibold, bold; independent italic/mono flags. Exact face registrations are selected consistently for native measure, metrics and raster. | Arbitrary numeric weights, explicit stretch and variable-font axis authoring. No synthetic bold/italic guarantee. | | Condensed type | A condensed font file can already be registered under a distinct family ID. | A same-family condensed variant cannot be selected independently of existing style keys; add an explicit stretch key before promising that API. | | Size and line height | Float logical sizes; explicit line height or zero for natural measurement. Core interns family, size, style and line height. | Named reusable typography tokens and clear defaults across components. | | Wrap and alignment | `cui_text_ex` wraps within a constrained parent; `cui_text_line` is unwrapped. Paragraph APIs preserve strict UTF-8, hard breaks, grapheme-safe wrapping and optional left/center/right alignment. | One convenient options API, logical start/end alignment and explicit overflow/ellipsis policy. | | Letter spacing | `cui_text_style.letter_spacing` with explicit provider capability; native contextual measurement, geometry, wrapping, caret and software/SDL rendering share cluster tracking. See `LETTER_SPACING.md`. | Canvas, GPU and foreign style API remain unsupported. Broader authoring declarations below remain proposals. | | Gradient text | Copied linear stops, block/line anchors and real per-pixel glyph masks in software, SDL and Canvas. See `TEXT_GRADIENT.md`. | GPU implementation, radial/conic paints, color-span combinations and broader native acceptance. | Named-family fallback currently resolves exact family/style, named-family regular, default-family style, then opened regular. This is variant fallback; missing glyph fallback is separately configured through the ordered font fallback chain. Neither mechanism discovers installed OS fonts. Style registration changes require `cui_text_metrics_changed(ui)` between frames so existing layout caches remeasure. Core accepts custom styled measurement and metrics callbacks with a shared user pointer. If the host supplies only legacy measurement, every family can measure as the same fallback. A convenient API must either require the complete provider or expose capability failure rather than silently advertise full typography. The native layout API already retains actual selected faces and exposes positioned glyphs, visual runs and cluster advances. It accepts paragraph direction and language at `cui_font_layout_line`; the convenient Core typography entry points do not expose every one of those shaping inputs. Cluster edges intentionally do not represent arbitrary caret positions inside ligatures or full editing navigation. Native contextual behavior also requires the optional bidi build; disabled builds report unavailable for that functionality. See `include/cui/cui_text.h` and `tests/packaging/sdk_text_fixture.c` for the existing contract and checks. Canvas is a separate host implementation: `web/gallery.js:canvasFont` maps IDs to CSS font stacks and weights 400/500/600/700; measure uses `measureText`, draw uses `fillText`. Browser system fonts and shaping are distinct from native FreeType/HarfBuzz. The gallery now consumes the portable linear text paint using a full contextual line mask; native software/SDL have separate pixel checks. A browser demo alone cannot prove native text capability. ## Recommended authoring model First ship semantic tokens on the existing primitives; this is useful without redesigning native shaping. Keep font resources in the optional text/host layer, layout contracts in Core, and theme conveniences in base/components. Core must continue to have no FreeType, HarfBuzz, SDL, browser or Clay types in public APIs. A proposed public convenience layer can look like this: ```c /* Proposed API sketch; names and binary layout need review. */ typedef enum { CUI_FONT_BODY, CUI_FONT_HEADING, CUI_FONT_CODE } cui_font_role; typedef struct { cui_text_style face; float size; /* logical px; finite, positive */ float line_height; /* logical px; 0 = selected face natural */ float letter_spacing; /* logical px; 0 preserves current shaping */ } cui_typography; typedef struct { cui_typography body, heading, code; } cui_typography_theme; /* Resolve role and token first; submit a complete immutable style to Core. */ ``` For today's equivalent, applications can keep these token structs locally, register IDs for each family, and submit `cui_text_ex` with explicit size/height. Use the landed `cui_text_style.letter_spacing` only after checking the provider capability as described in `LETTER_SPACING.md`; it is unavailable on Canvas. A future `cui_text_options` submission should contain resolved typography, wrap policy, alignment and paint, with a bool/status result for unsupported combinations. Keep legacy APIs as wrappers with zero tracking, current wrapping and solid paint. Decide token inheritance explicitly: role defaults at the theme layer, caller overrides resolved once; avoid changing every frozen component's metrics by implication. Use an additive versioned descriptor/provider for extended font selection rather than reinterpreting the four existing weight enum values as CSS numbers. Suggested extended selection is numeric weight 1..1000, finite positive width percentage (100 normal), italic flag and family ID, with documented exact/fallback policy. A font registry can initially map those requests to explicit static files. Variable axes and optical sizing should follow only after axis identity, clamping, ownership and cache keys are specified. Registering a condensed static face under another family is the reliable interim path. ## Tracking must change layout and paint together The same resolved shape parameters must reach styled measurement, contextual geometry, wrap candidate widths, selection/hit testing, retained layouts and draw. The original audit found callbacks could not carry tracking or stretch. Native tracking now uses the landed style field and explicit provider capability; `LETTER_SPACING.md` supersedes the tracking proposal below. Numeric stretch remains proposed. Do not let Core compute `character_count * spacing` independently of the shaper. Define tracking between eligible shaped clusters in visual advance order, with no extra gap after the final eligible cluster. Combining marks must stay attached; ligatures, Arabic joining, Indic shaping, default-ignorables, tabs and hard breaks need explicit rules and fixtures. Retain natural shaping for zero tracking. The landed policy preserves optional and required ligatures; splitting UTF-8 text into independent character draws destroys contextual shaping. Negative tracking requires an explicit overlap policy and must not invalidate finite geometry or hit-test ordering assumptions. Line boxes, ink bounds and advance bounds are distinct. Explicit line height sets baseline spacing and may be smaller than ink height; it must not stretch raster glyphs. A gradient anchor must not be inferred from cropped glyph bitmaps. Cache keys must include all shape parameters, selected face generation, direction, language and relevant feature settings. Paint changes should reuse geometry. Font-load/registration changes invalidate metrics; gradient-stop changes do not. ## Gradient glyph paint Start with solid and linear gradients; defer radial/conic gradients and CSS string parsing. A proposed portable `cui_text_paint` is a tagged value containing solid color or finite start/end points, a bounded copied stop array and an explicit coordinate space. Use resolved logical coordinates with a documented anchor: whole paragraph block or each visual line. Make the default paragraph-wide so a multiline heading has one continuous gradient. Resolve final box/alignment before publishing commands, and preserve the same anchor on every emitted line. Specify stop ordering, duplicate-stop hard edges, out-of-range rejection or clamp, zero-length axis behavior and interpolation/color space. Reuse a documented CUI color convention rather than claiming exact Tailwind/CSS fidelity by appearance. Recommend premultiplied-alpha interpolation with explicit color-space selection; CSS matching must name and test the matching space. Gradient alpha multiplies coverage and cumulative ancestor opacity exactly once. Current draw colors and bitmap opacity already absorb ancestor opacity in Core; extending paint requires one consistent policy for stop alpha and span alpha, not a second backend factor. Native software currently multiplies glyph coverage by `r->ink.a`; SDL3 caches coverage textures and applies a single RGB/alpha modulation per glyph (`backends/software/cui_software.c:glyph`, `backends/sdl3/cui_sdl3.c:glyph`). A single modulation cannot express a continuous gradient across a glyph. Keep the coverage cache independent of paint and sample the gradient at each output pixel in software. For SDL, add a bounded temporary RGBA mask/composite path first or a proper masked gradient rendering path; changing tint once per glyph is not sufficient. Cache any painted result by paint, anchor, density and mask revision, or do not cache it. SDL_GPU/Sokol need equivalent explicit support or observable unsupported status; do not silently flatten to one color. Canvas should render a full shaped line mask and apply a gradient in the same resolved coordinate space using a bounded offscreen surface and compositing. Preserve context state, clips, logical-to-device scale, baseline and opacity. Avoid one `fillText` call per letter. If browser and native shaping differ, test semantic anchor/alpha behavior independently and state the raster difference. All paths must include italic overhang and fallback glyph ink beyond advance bounds, respect ancestor clips, bound temporary allocations and handle empty text/zero bounds without NaNs or accidental giant surfaces. ## Implementation sequence and acceptance evidence 1. Add a typography example using existing body/heading/mono IDs, registered static variants and size/line-height tokens. Cover missing variant/family fallback and dynamic registration invalidation. This can deliver immediate usability without waiting for tracking or gradients. 2. Add versioned extended shape/provider contracts and shared capability handling. Establish real static condensed-face selection before variable-font work. Extend cache keys and binding generators together. 3. Implement tracking in one retained native layout path and route measurement, geometry, wrapping and paint through it. Add RTL, combining, ligature, Arabic, fallback-face, negative/zero tracking and fractional-size tests. Assert caret, selection and measured/drawn advances agree. 4. Add paint descriptors and Core lifetime/opacity/anchor tests; implement software as the deterministic reference, then SDL3 and headless Canvas. Test a gradient inside a single wide glyph, transparent stops, multiline alignment, clipping, italic overhang, nested opacity and density 1/1.5/2. Unsupported adapters must report capability limitations until implemented. 5. Publish semantic theme roles and ergonomic overrides across components, then update generated SDKs/packages. Re-run actual installed library fixtures and compare wrappers as well as native text. Preserve all 78 manifest entries. Native tests use `python scripts/test_local.py --build-dir build` on Linux; browser tests remain headless. GPU hardware parity remains explicitly deferred when unavailable under the virtual display. This audit ran no UI or native tests because it changes proposal documents only. --- ## Reusable typography tokens Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TYPOGRAPHY_TOKENS.md # Reusable typography tokens `cui_typography.h` is a header-only authoring convenience over existing Core text APIs. It gives applications three semantic roles without owning fonts, modifying the current theme or introducing new layout behavior. ```c #include "cui/cui_typography.h" const cui_typography_roles type = { .body = {.style = {.family = 11}, .size = 16.5f, .line_height = 26, .wrap = true}, .heading = {.style = {.family = 12, .weight = CUI_TEXT_WEIGHT_BOLD}, .size = 30, .line_height = 38, .wrap = true, .align = CUI_TEXT_ALIGN_CENTER}, .code = {.style = {.family = 13, .monospace = true}, .size = 14, .line_height = 23, .wrap = false} }; cui_typography_token heading; if (cui_typography_resolve(&type, CUI_TYPOGRAPHY_HEADING, &heading)) { /* In an open frame, inside a constrained layout parent. */ bool submitted = cui_typography_text(ui, cui_string("A clear heading"), heading, (cui_color){24, 30, 40, 255}); (void)submitted; /* Real applications handle submission/capacity errors. */ } ``` Roles are ordinary caller-owned values. Resolution copies the selected token; change the copy to override one call without changing defaults. Only the selected role must be valid. Invalid roles/tokens preserve the output. Valid sizes are finite logical pixels in `(0, 65535]`; line height is finite in `[0, 65535]`, with zero selecting natural metrics. Alignment is physical left/center/right. Weight uses the existing normal/medium/semibold/bold enum. There is no implicit scaling, inheritance, mutable current style or guessed font registration. `cui_typography_text_colored` accepts existing paragraph-relative UTF-8 byte color spans. Both submission helpers use `cui_text_paragraph_colored_aligned`, retaining strict UTF-8 validation, grapheme-safe wrapping and contextual geometry when the host supplies it. `wrap=false` retains hard breaks but may overflow; use a clipping ancestor where needed. A constrained parent width is required to demonstrate wrapping. Explicit line height sets spacing, not glyph stretching. Check the helper result and the existing end-frame error contract for layout failures. `cui_typography_text_painted(ui, text, token, paint)` uses the same token geometry with a solid or copied linear text paint. See [gradient text](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TEXT_GRADIENT.md) for stops, directions, paragraph/line anchors, renderer capabilities and lifetime. This helper does not combine gradient paint with byte color spans. ## Native font registration and composed example `examples/typography/app.c` composes a centered heading, wrapped body, an italic local override and clipped unwrapped code. All three families have distinct IDs. Compile with `CUI_TYPOGRAPHY_NATIVE` to enable `typography_example_font`: it takes five explicit file paths (body regular, heading regular, heading bold, body italic, code regular), opens an owner and registers the exact styles used by the example. Failure closes the partially built owner and returns NULL. There is no OS name lookup or synthetic italic/bold claim. The returned owner must outlive the renderer/context use and be closed by the host. Configure the native context and renderer with the same font owner: ```c cui_config config = { .width = 900, .height = 700, .measure_styled = cui_font_measure_styled, .measure_user = font, .font_metrics = cui_font_get_metrics, .text_geometry = cui_font_text_geometry, .text_geometry_line = cui_font_text_geometry_line }; ``` Then call `typography_example_frame` from the native host's frame loop and submit its draw list to the existing renderer. The example itself creates no window. After changing registrations, call `cui_text_metrics_changed` between frames. Custom hosts and Canvas must apply the same family mapping in measurement and paint; tokens do not make browser and native shaping identical. `tests/unit/test_typography_tokens.c` checks validation, immutable resolution, failed-input atomicity, styled/color-span forwarding and centered geometry. `examples/typography/test_app.c` checks family/style/float-size commands, body baseline spacing, wrapped line counts and stable roles across wide/narrow/wide frames. Compiled with `CUI_TYPOGRAPHY_NATIVE`, it requires all five explicit path environment variables `CUI_TYPOGRAPHY_BODY`, `CUI_TYPOGRAPHY_HEADING`, `CUI_TYPOGRAPHY_HEADING_BOLD`, `CUI_TYPOGRAPHY_BODY_ITALIC`, `CUI_TYPOGRAPHY_CODE`; without them it returns 77. It compares native measurement and raster output for each used exact variant against the separately opened actual file. Use distinct family files to exercise the intended body/heading/code configuration. ## Extending typography later These tokens expose supported properties only. Tracking, numeric weight/stretch and variable axes require complete provider, measurement, geometry and cache contracts before authoring fields can be added. A future extended layout/paint descriptor can have a new token type and helpers while keeping these functions as wrappers for zero tracking and solid/span paint. Current source callers need no migration to use this convenience header; font registration, context callbacks and existing text entry points remain available. --- ## Source-compatible contextual wrapping Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/UNICODE_WRAP.md # Source-compatible contextual wrapping `cui_text_paragraph_colored(..., wrap=true, ...)` now computes visual rows at the current frame's assigned width using the frozen runtime's actual candidate and fallback policy. It retains all original UTF-8 bytes, including trailing spaces, and intersects color spans with each final row. `wrap=false`, ordinary `cui_text` and the existing unwrapped contextual APIs retain their previous behavior. This policy comes from upstream-pre **0.3.8**, the exact dependency of frozen upstream kit commit `87d10ae5e1299d1be18670a37570c5402f952e34`. StyledText calls `LineLayout::compute_wrap_boundaries`; its classifier is `LineWrapper::is_word_char`. This is not the Unicode default word algorithm, UAX #14, CSS line breaking, or the separate editor-oriented `wrap_line` helper. The source considers ASCII letters/digits, its explicit Latin/Cyrillic/Vietnamese/ combining-mark/Bengali ranges, selected punctuation and three glue characters to be word characters. A word character following an ASCII space creates a candidate; a non-word character other than ASCII space creates a candidate after the first non-space character. On overflow it selects the last candidate, otherwise falls back before the overflowing item. Only ASCII space has that special whitespace role; tabs and Unicode spaces follow their explicit classifier result. State and advance accounting follow the measured LineLayout implementation, including its preservation of spaces in the previous row. Nonbreaking glue still participates in fallback when an entire token cannot fit, as in the source. CUI deliberately restricts candidates and fallback to extended grapheme boundaries and, when available, shaped-cluster boundaries. Combining sequences, emoji ZWJ/ modifier sequences, regional-indicator pairs, Hangul clusters and Indic conjuncts stay intact. A single indivisible cluster wider than the width occupies its own overflowing row. The requirement to preserve complete graphemes takes precedence over a source platform that happens to emit multiple glyph items for one grapheme. Existing `cui_config.text_geometry_line` supplies a full contextual shaped session. Core queries the whole selected line's selection rectangles once, sorts them by original byte offset, and unions shaped-cluster boundaries with grapheme boundaries. Advances are copied into bounded frame storage and the session is released before layout publication. The current-frame layout callback performs no heap allocation or host measurement. Native font callers can use `cui_font_text_geometry_line`. If contextual geometry is unavailable, Core measures each grapheme once through the existing styled measurement callback. That fallback preserves byte/cluster safety but cannot reproduce shaping interactions such as kerning or ligatures which a measurement-only host does not expose. RTL and mixed text retain their complete original paragraph for contextual bidi shaping of every row; row ranges remain contiguous logical original-byte ranges, not copied visual-order strings. This is a source-policy port with these explicit adaptations, not a claim of pixel parity across platform shapers or every upstream style refinement. The two opt-in hooks in the pinned Clay header allow custom intrinsic width/minimum and final wrapping after width sizing and before height propagation. Hooks are inactive for ordinary text and unwrapped text. Core's normal layout, clipping, prepaint and bounds tracking continue to operate on the resulting visual rows. Clipping/scroll container sizing retains the existing Core conventions; give text an explicit inner width when a scroll owner intentionally allows wider content. Strict UTF-8 validation, grapheme preparation, geometry extraction, and conservative storage/element reservation finish before publication. Heap work and copied frame metadata are bounded by configured frame storage. Invalid input or preflight capacity failure publishes no layout. Exhausting final wrapped-row or clipped-span capacity marks a Core capacity error and empties the draw list; the next frame starts clean. Callbacks used for measurement/geometry cannot submit UI mutations. Grapheme scans and measurement-only preparation are linear in text length; geometry preparation uses one bulk query and an O(n log n) sort. Wrapping runs twice in linear time to reserve all final rows before emitting any. No original masked input is introduced: the Label component submits already-masked display bytes, so copied cluster metadata also contains only those display scalars. ## Provenance and validation - Runtime source: [upstream-pre 0.3.8 LineLayout](https://docs.rs/crate/gpui-pre/0.3.8/source/src/text_system/line_layout.rs) and [LineWrapper](https://docs.rs/crate/gpui-pre/0.3.8/source/src/text_system/line_wrapper.rs). Official crate archive: `https://crates.io/api/v1/crates/gpui-pre/0.3.8/download`. SHA256 `d7f0bc3ebba070f8981b3f8e905a12f47d27794a30d029e59cdb9edf7a4b3360`. The classifier/candidate policy was ported into C; the copyright/license notice for the Apache-2.0 runtime appears below. - `src/core/cui_unicode_grapheme.h` copies the exact Unicode 17 generated grapheme ranges and UAX #29 scan from `src/base/cui_edit.c` at `74bdb58b`, with private names and a bounded forward helper. It adds no Core dependency on Base and downloads no new Unicode data. Official input URLs/hashes remain in `third_party/unicode/17.0.0/manifest.json`; the shared Unicode V3 notice is below. - The Core private include `cui_unicode_grapheme.h` must be expanded by distribution generation. The patched Clay header and pin are described in its adjacent PIN.md; integrators update the dependency checksum and generated distribution together. `test_unicode_wrap_source` runs all 766 vendored official grapheme conformance fixtures and source-specific narrow-width cases covering punctuation, glue, leading/trailing spaces, tabs, Unicode spaces, CJK, RTL, combining marks, emoji, Indic and Hangul. It checks exact original row bytes/spans, oversized atomic clusters, legacy/nowrap behavior, current-frame prepaint/bounds, shaped ligature cluster preservation, capacity recovery and linear measurement-call growth. `test_contextual_wrap_source` retains paragraph/Unicode-separator and copied software snapshot coverage. Defining `CUI_TEST_WRAP_RENDERER` additionally enables real-font raster tests; the Unicode test accepts a primary font path and optional owned RTL fallback font path. Sanitizer and WASI builds exercise the same portable code. ## upstream runtime attribution Copyright 2022 - 2025 Zed Industries, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS ## Unicode generated data notice UNICODE LICENSE V3 COPYRIGHT AND PERMISSION NOTICE Copyright © 1991-2026 Unicode, Inc. NOTICE TO USER: Carefully read the following legal agreement. BY DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE. Permission is hereby granted, free of charge, to any person obtaining a copy of data files and any associated documentation (the "Data Files") or software and any associated documentation (the "Software") to deal in the Data Files or Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, and/or sell copies of the Data Files or Software, and to permit persons to whom the Data Files or Software are furnished to do so, provided that either (a) this copyright and permission notice appear with all copies of the Data Files or Software, or (b) this copyright and permission notice appear in associated Documentation. THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA FILES OR SOFTWARE. Except as contained in this notice, the name of a copyright holder shall not be used in advertising or otherwise to promote the sale, use or other dealings in these Data Files or Software without prior written authorization of the copyright holder. --- ## CUI v1.0 readiness Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/V1_READINESS.md # CUI v1.0 readiness For the maintained delivery checklist, see the [beta roadmap](https://github.com/mattmezza/cui/blob/main/BETA_VERSION_ROADMAP.md). This document retains its dated readiness assessment. CUI is a working alpha. A live gallery and passing tests demonstrate useful functionality; they do not establish production readiness or complete component parity. This assessment is dated 17 October 2026. The catalog contains all 78 families: 77 tested subsets, one implemented family and zero fully verified families. The feature ledger contains 360 entries: 315 tested, four implemented and 41 not started. Features differ greatly in complexity, so these counts are not a completion percentage or a release-date estimate. The machine-readable component manifest remains the acceptance ledger. ## Release gates | Gate | Current evidence | Required before v1.0 | | --- | --- | --- | | Component behavior | All 78 families have live examples and substantive APIs; tested subsets remain explicitly partial. | Close every feature gap, verify realistic usage, controlled state, keyboard, pointer, relevant touch, semantics and visual states for each family. | | Touch and pointers | Shared controls expose hover, pressed, focus and activation. The published integration tests contact/device routing, precise touch scrolling, opt-in pan/pinch, cancellation, drag priority and broader cursor overrides. Physical-device/family coverage remains incomplete. | Test tap versus drag cancellation, nested scrolling, capture loss, overlays, multi-contact pan/pinch, disabled controls and device-specific cursor fallbacks. Zoom must require opt-in. | | Text and editing | Unicode grapheme/word conformance, selection, multicursor edits, bounded grouped undo and cached large-document viewport work have tests. Single-selection composition across four text consumers plus Numeric, OTP and Combobox has integrated tests. Optional native bidi/hard-line shaping and explicit font fallback have tests. | Finish IME across remaining editable consumers, physical OS candidate windows/mobile keyboards, bidi caret/wrap integration and automatic font discovery, language-service integration and large-document end-to-end performance. | | Rendering | Software, browser Canvas, Linux Sokol GL and SDL_GPU Vulkan have runtime evidence for supported capabilities. Native/software analytic path meshes have integrated runtime and pixel-test evidence for uniform paints; broader source paint parity remains unfinished. | Verify capability coverage, clipping, DPI, resource lifetime, recovery, visual consistency and native renderers on the advertised platforms. | | Accessibility | Roles, state, names, actions and focus have headless semantic tests. The optional Linux AccessKit package passes native DBus and relocated CMake/pkg-config consumer tests; assistive-technology and broader platform acceptance remain open. | Implement and validate platform accessibility bridges with real assistive technologies; cover contrast, text scaling, reduced motion and touch targets. | | Platforms | Portable library CI includes Linux, Windows and macOS; browser and Linux native runtime checks exist. | Native Windows/macOS, Linux display-server variants and Android/iOS runtime evidence. Compile-only evidence must remain labeled separately. | | API and ownership | Portable C11 APIs, layered implementation, generated embedding headers and explicit memory contracts exist. | Review ABI/version policy, lifetimes, failure behavior, capacity limits and upgrade compatibility; finish the optional ecosystem promised by the scope. | | Themes and motion | Bounded owned theme registry, transactional supported imports, semantic snapshots and explicit host preference/motion projection have native, header-only and browser tests. | Validate physical native preference changes, native contrast/motion observation and broader component integration of typography, spacing and shadows; close remaining source styling and current-frame chart/plot consumer geometry gaps. | | Performance and safety | Warning builds, sanitizers, WASI and browser tests; selected measured workloads. | Reproducible startup, memory and frame-budget baselines, broad stress/fuzz coverage and regression thresholds on supported targets. | | Documentation | Browsable guides, compiled C snippets, callback/state explanations and host-language examples. | Every shipped capability has accurate usage, ownership, limitations and reproduction instructions; examples must match released APIs. | ## How progress is reported A tested feature is narrower than a verified family. A compile check is narrower than a native runtime check. A completed worker branch is narrower than an integrated and deployed release. Reports and the platform matrix preserve these distinctions. The next milestones are consistent input across touch and pointer devices, complete heavyweight component behavior, international text and native accessibility, followed by platform acceptance and API stabilization. There is no defensible v1.0 date yet. Full catalog and ecosystem scope remains active rather than being reduced to reach a release label. See [the component ledger](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/gpui-parity.json), [platform evidence](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PLATFORM_MATRIX.md), [current report](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NIGHTLY_REPORT.md) and [interaction feedback](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/website-feedback.md). --- ## Decoded video frames and a portable timeline Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/VIDEO_GUIDE.md # Decoded video frames and a portable timeline `cui/cui_video.h` supplies a decoder-neutral timeline model and a real CPU RGBA8 surface using the existing bitmap draw path. There is **no built-in codec**, container reader, network transport, audio output, subtitle engine, recorder, casting service or editor. The architecture roadmap remains [VIDEO_PLAN.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/VIDEO_PLAN.md). The optional [offline audio host foundation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/video_audio_host/README.md) demonstrates bounded PCM buffering, worker cancellation, generation-safe seeks and ordered output-consumption accounting with injected services. It is an example-local C11 controller, not a CUI component API or device adapter. Its deterministic tests require no network, microphone, speaker or window; the guide includes build and invisible-display test commands. Browser video uses the browser's existing audio decoder/output independently. The separate [FFmpeg PCM decoder proof](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/video_audio_ffmpeg/README.md) feeds that controller from real local media and converts audio to 48 kHz stereo float. Offline tests check sample content, resampler draining, exact replay-based seeks, a shared video/audio origin, cancellation and pending-worker shutdown. This optional example currently admits only bounded PCM media and replays from the beginning for seeks; it is not general compressed-media playback. Its pinned FFmpeg package has GPLv3-or-later licensing, documented in the example. These standalone proofs do not themselves connect a video UI to a device. The optional [SDL output transport](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/video_audio_sdl/README.md) supplies the controller's output interface. Its owner-thread pump submits bounded PCM chunks and reconciles SDL's software queue drain without registering application callbacks with the mixer. Headless tests use SDL's dummy driver and injected failures. That evidence covers pause, resume, discard and ordered consumption; it does not prove physical audibility or a DAC clock. The separate [native video with PCM sound example](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/video_player_audio/README.md) connects both workers and the SDL output to a real CUI VideoPlayer UI. Its initial supported profile is immutable local Matroska with FFV1 video and PCM audio, known zero container origin and duration at most 10 seconds. It offers play, pause, seek, skip and replay, and selects decoded video frames against observed SDL software-mixer consumption. It does not claim a physical DAC clock or speaker-level synchronization. Native fullscreen, rate controls, general MP4/AAC/Opus playback and actual device hotplug recovery remain unsupported in this example. The existing silent video example remains available independently. Build and test from the repository root with the pinned development dependencies listed in that example's README: ```sh cmake -S examples/video_player_audio -B build-video-sound -G Ninja -DVIDEO_SOUND_UI=ON cmake --build build-video-sound --target video_player_audio test_sound test_sound_watch test_sound_output test_sound_legacy python scripts/test_local.py --build-dir build-video-sound -- -R '^sound_' ``` Automated native checks use private Xvfb, forced SDL dummy audio and captured actual decoded pixels. They do not open a desktop window or exercise speakers. The README provides a separate explicit interactive launch command and explains PCM conversion, package licensing, device invalidation, bounded buffering, software-clock limitations and shutdown ownership. ## Initialize and advance ```c #include "cui/cui_video.h" cui_video player; bool ready = cui_video_init(&player, (cui_video_config){ .duration = 120, .duration_known = true, .seekable = true }); if (ready) { ready = cui_video_set_playing(&player, true); /* Once per host tick, with elapsed monotonic seconds, excluding paused time. */ ready = ready && cui_video_advance(&player, elapsed_seconds); } ``` The caller owns the model and UI-thread synchronization. No wall clock is read internally. Pause leaves position unchanged; rate is any positive finite value. Known duration may be zero; unknown duration uses `duration_known=false` and `duration=0`. Unknown playback advances until the host calls `cui_video_finish`. No buffering/decode state or frame queue is implied. Seeking requires `seekable`; known duration bounds the target. Successful seeks increment `generation`, including a seek to the same time, invalidating previously acquired frames. Seeking exactly to the known end stops playback. Starting an ended seekable model restarts at zero with a new generation; restarting an ended nonseekable source fails. A model with looping enabled wraps when advancing past its known positive duration only when seekable. Each advance that wraps increments generation once, even if several loops elapsed. `finish` is an explicit terminal host acknowledgement and stops regardless of loop preference. The timeline requests no decoder action itself: the host must translate seeks, restart and loop generation changes into source commands and acknowledge actual results in its own controller. Do not interpret an accepted model command as a successful asynchronous decoder seek. Keep audio-synchronized time, error, buffering and capability handling in that host/controller until an adapter contract is implemented. All model commands return false without changing the model for invalid inputs, nonfinite values, overflow, unsupported seek/restart, or exhausted generation. Initialization sets generation to one; do not reinitialize a player while old frames can still be submitted. Replacing a source requires retiring its frames and outstanding draw lists before reusing generation values. ## Submit an already-decoded frame ```c cui_video_frame frame = { .bitmap = {.pixels = rgba, .width = frame_width, .height = frame_height, .stride = row_bytes, .revision = frame_revision}, .generation = player.generation, .timestamp = presentation_seconds }; /* Inside an active frame, after the host selects the due decoded frame. */ bool submitted = cui_video_surface(ui, video_id, &player, &frame, (cui_video_surface_options){ .geometry = {.width = available_width, .height = 240, .fit = CUI_IMAGE_CONTAIN}, .opacity = 1, .description = cui_string("Video preview") }); ``` Pixels are borrowed straight-alpha RGBA8, including any row padding. Keep them unchanged until **every renderer has finished consuming the draw list**; `cui_end_frame` is not a release boundary. The helper retains no lease and invokes no release callback. A host decoder's acquired-frame lease belongs to the host; release it exactly once after consumption or after a rejected submission that has no outstanding users. Never recycle a decoder buffer immediately after surface submission. A paused preview still needs its frame's pixels alive. Increment bitmap revision when pixels change in place; use distinct retained storage when an older draw list is outstanding. The surface checks model generation, timestamp, bitmap stride/dimensions, geometry, opacity and description. A timestamp is metadata: the host selects due frames, drops late ones and schedules redraws. No automatic PTS scheduling is provided. Contain, cover, fill, scale-down and natural-size fit reuse the existing image layout rules and a clipped parent. Native texture import, YUV/HDR conversion, rotation and sample-aspect metadata are unsupported. Renderer support is that of existing CPU bitmap draws; the new tests prove software output, not every backend. ## Optional controls The surface submits no timeline/button hit targets. The controlled Styled composition is documented in [VIDEO_PLAYER.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/VIDEO_PLAYER.md). It emits requests against a read-only playback view, with optional controls and explicit host capabilities. The timeline and surface remain usable independently. ## Headless evidence `tests/unit/test_video.c` uses a deterministic synthetic clock and two borrowed RGBA frames. It checks pause/resume, rates, seek/end/restart, looping/generations, unknown duration, zero duration, invalid-input atomicity and overflow. Software rendering checks contain letterboxing, cover crop, fill, opacity, changed frame revision and stale-frame rejection. No codec or window is needed. The test must link `cui` and `cui_software`; the timeline and surface implementation are included in the portable `cui` target: ```sh cmake -S . -B build -G Ninja -DCUI_BUILD_NATIVE=OFF cmake --build build --target test_video python scripts/test_local.py --build-dir build -R '^video$' ``` The same model and software pixel assertions run under WASI with the pinned tools: ```sh uv run scripts/test_wasi.py --suite video ``` The generated `dist/cui_video.h` module and Go/Rust source SDKs expose the same API. These are C APIs; language-specific video builders are not yet provided. --- ## Video architecture proposal Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/VIDEO_PLAN.md # Video architecture proposal Original architecture audit baseline: `b96c6844`, before selecting a decoder dependency. The current portable surface and controls are implemented separately from the optional FFmpeg example below. The remaining architecture proposals do not establish shipped capabilities. The portable timeline and borrowed CPU RGBA surface are now available in `cui/cui_video.h`; [the implementation guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/VIDEO_GUIDE.md) describes their actual behavior and tests. The [controlled player](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/VIDEO_PLAYER.md) and optional [FFmpeg example](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/video_player/README.md) implement requests, a bounded host-owned queue and actual silent local-file decoding. They do not change the 78-component baseline. Audio, browser playback, general decoder-adapter ABI and production buffering/scheduling remain planned. ## Existing foundation and its limit `include/cui/cui_media.h` already defines borrowed image frames (RGBA-sized stride validation, revision, duration), an image loader, contain/cover/fill layout, and image animation state with caller-provided time and next-wake scheduling. `src/base/cui_media.c` validates frames and polls a host-side image cache. That is useful precedent for ownership and frame presentation; it is not a streaming video decoder, audio clock, seek engine, recorder or editor. `cui_bitmap` in `include/cui/cui.h` is borrowed straight-alpha RGBA8 with stride and revision. It remains valid through renderer completion. The current video surface reuses `cui_paint_bitmap` and image-fit geometry with decoded RGBA frames. It must not preload an entire movie into the animated-image frame array (currently bounded at 4096 entries). Dynamic streaming requires bounded queues and explicit frame release, buffering and end-of-stream behavior. ## Portable layers 1. **Decoded-frame surface:** accept frame identity/generation, dimensions, RGBA8 stride, pixel data and presentation timestamp. Retain/release a frame lease until the renderer finishes consuming it; never let the decoder recycle pixels at submission time. Draw using existing fit/crop rules. Start with CPU frames; zero-copy platform textures require separate optional adapters. 2. **Playback state/controller:** stopped/loading/playing/paused/buffering/ended/ failed states; position, known/unknown duration, seekability, playback rate, mute/volume and error/capability values. Commands request state changes and asynchronous results acknowledge them. No codec handles or OS types in Core. 3. **Clock and scheduler:** host monotonic time for silent playback; optional audio master clock when audio is enabled. Compare timestamps, present due frames, drop late frames by documented policy and request the next wake. Pause/resume must rebase time; seek uses a new generation so stale frames and callbacks cannot reappear. Avoid busy polling and unbounded decode queues. 4. **Composed controls:** buttons, timeline slider, time display, loading/error overlay, volume, captions and fullscreen request. Keep these optional so the same surface supports thumbnails, backgrounds and applications with custom controls. Keyboard focus, accessible names/status, seek increments and reduced motion/autoplay policy belong in the UI/host contract. 5. **Optional adapters:** decoder/container/network input, audio output/clock, subtitle sources, platform fullscreen and GPU frame import. Adapter capability negotiation must expose unsupported seek/rate/audio/captions. Worker threads may decode; UI callbacks and font/UI state stay on their documented thread. A proposed decoder-neutral interface should offer open/poll/command/close with bounded events and explicit frame acquisition/release. Do not finalize ABI before agreeing on time units, rational timestamp conversion, thread/cancellation rules, seek completion, queue bounds, frame orientation, sample aspect ratio, color metadata and source lifetime. Begin with RGBA8 SDR; document conversion/color limitations. YUV planes, HDR, GPU surfaces and hardware decoding are later capabilities, not implied by a CPU bitmap prototype. ## Different product scopes | Scope | Required pipeline | Relationship to playback | | --- | --- | --- | | Local/streamed playback | Demux/decode, timestamp scheduling, optional audio output | Initial target; controls can be composed independently. | | Recording | Capture source, timestamped audio/video, encoder, muxer, file lifecycle | Separate adapter pipeline; recording a CUI surface needs a defined readback boundary. | | Casting | Device discovery/session/transport, remote control and remote playback state | Separate host/service integration with latency and permission requirements. | | Editing | Source model, timeline, trims/tracks, preview, export/render/encode | Separate application model that may reuse the playback surface. | | Screen/camera capture | Platform capture APIs, permissions, device lifecycle | Optional input adapter; not included in a decoded-frame widget. | ## Deliverable sequence and tests First implement a renderer-independent playback state machine with a fake clock and synthetic decoder frames. Prove pause/resume, buffering, cancellation, end-of-stream, unknown duration, seek generations, rate changes and bounded queues deterministically. Add a CPU RGBA surface and fit/clipping/opacity/revision checks using software output; verify SDL under invisible Xvfb and Canvas headless. Assert that frames remain leased until consumption and release exactly once. Then compose accessible controls against the fake controller. Only after the interfaces work should a separate decision compare decoder adapters against supported platforms, license/distribution constraints, pinned versions, codec availability, audio synchronization and package size. No dependency is necessary to review or test the first two deliverables. The optional silent local-file example proves decoded play/pause/seek and cleanup. Audio-capable playback still requires audio synchronization acceptance. Recording, casting and editing each need separate acceptance criteria and scope. --- ## Reusable VideoPlayer Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/VIDEO_PLAYER.md # Reusable VideoPlayer Start with `cui_video_player_defaults()`: a 320×180 contained video surface, compact playback/skip/timeline controls, short `m:ss / m:ss` time and fullscreen. The seek row and icon buttons have 44-unit touch targets; artwork is 20 units. The seek line is four units high. Narrow bars wrap buttons/time within the configured width (minimum 160). Controls are below the surface, not overlays; there is no auto-hide policy. Rate is available explicitly, not shown by default. Set both `surface.geometry` and `controls_options.width` when resizing. The host must supply capabilities and a request callback to enable actions. Fullscreen is visible by default but disabled without `CUI_VIDEO_CAP_FULLSCREEN`; it never silently changes a window or DOM element. No volume/audio state is invented. `compact` is an appended field of `cui_video_controls_options`. Rebuild C applications against matching headers and library; this prerelease does not promise binary compatibility with an older struct layout. Legacy zero-initialized options retain their existing full-size controls. This complete portable C11 owner seam draws inside an existing CUI frame. The host fills `confirmed`, optionally supplies an already-decoded RGBA frame, and drains copied requests **after** submission/rendering. It must handle overflow rather than assuming an unbounded queue. No codec/network API is required by CUI. ```c #include "cui/cui_video_controls.h" typedef struct { cui_video_controls_state controls; cui_video_view confirmed; cui_video_request pending[32]; unsigned pending_count; bool overflow; } player_owner; static void player_request(void *user, const cui_video_request *request) { player_owner *owner = user; if (owner->pending_count < 32) owner->pending[owner->pending_count++] = *request; else owner->overflow = true; } bool player_owner_init(player_owner *owner, uint64_t source_id) { if (!owner || !source_id) return false; *owner = (player_owner){0}; owner->confirmed.source_id = source_id; owner->confirmed.capabilities = CUI_VIDEO_CAP_PLAY | CUI_VIDEO_CAP_SEEK; return cui_video_init(&owner->confirmed.timeline, (cui_video_config){.duration = 120, .duration_known = true, .seekable = true}); } bool player_owner_draw(cui_context *ui, const cui_theme *theme, player_owner *owner, const cui_video_player_frame *decoded) { cui_video_player_options options = cui_video_player_defaults(); options.controls_options.on_request = player_request; options.controls_options.user = owner; options.surface.description = cui_string("Video preview"); return cui_video_player(ui, 700, theme, &owner->controls, owner->confirmed, decoded, options); } ``` The 120-second timeline is example host metadata, not media opened by CUI. The host acquires sources, demuxes/decodes, schedules frames and audio, implements seek/rate/fullscreen, and publishes confirmed state after success. Check request source/generation before applying it; queueing is not acknowledgement. The null frame draws an empty reserved surface. For actual decoding, the existing [FFmpeg host example](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/video_player/README.md) is a separate adapter. `cui_video_surface` remains the reusable Base surface for a controls-free view. Keep captions, sample descriptions and diagnostic/debug text in host content outside the player; the standard bar displays only media position and controls. Legacy `cui_video_controls_defaults()` keeps its original layout and visible parts. The additive `controls_options.compact=true` opts into the standard bar; `cui_video_player_defaults()` selects it automatically. Existing manually built player options are not forced into the new layout. The pinned catalog already contained `skip-back`, `skip-forward` and `gauge`, but they were excluded from the default embedded bundle. They now embed their existing SVGs alongside play/pause/maximize/minimize, so standard controls need no custom loader or all-assets build. All seven names are prepared and checked for actual mask pixels by `test_video_player_defaults.c`; player seek icons are also checked in actual software-rendered pixels. Catalog names/paths and `theme.icon_loader` overrides are retained. The named Button icon cache accepts catalog names/paths; arbitrary unknown names are not introduced by this API. ## Controlled video controls `cui_video_controls.h` adds optional Styled controls above the portable video surface. This extension is independent of the frozen 78-component baseline. It does not decode, play audio, change native fullscreen, or acknowledge commands. ```c #include "cui/cui_video_controls.h" /* Retain one zero-initialized state per stable controls ID. */ cui_video_controls_options options = cui_video_controls_defaults(); options.on_request = request_playback; options.user = application; options.width = 320; options.visible |= CUI_VIDEO_CONTROL_FULLSCREEN; cui_video_controls(ui, controls_id, theme, &application->controls, application->confirmed_view, options); ``` The view is copied by value. Its timeline is confirmed application state. Each request contains `source_id`, observed timeline `generation`, and a monotonically increasing `sequence`. The callback may accept or reject it without the controls writing playback state. It must not destroy the context or controls state during submission. A missing callback makes controls read-only. Sequence exhaustion makes them read-only; retire outstanding work before replacing their state. Source IDs must be nonzero and must not be reused while old frames or requests can survive. Source or generation changes clear local scrub presentation. `PLAYING` and `FULLSCREEN` carry the desired boolean; `SKIP` carries a signed seconds delta; `RATE` carries the explicitly configured `requested_rate`. `SEEK` carries absolute double-precision seconds and BEGIN/UPDATE/COMMIT/CANCEL. BEGIN starts preview, UPDATE adjusts it, COMMIT requests the final decoder seek, and CANCEL restores the gesture's starting preview. An application can implement live seeking, but should bound outstanding seeks and ignore obsolete completions. Keyboard changes emit all three accepted phases per key. Gesture preview is not a second authoritative playback timeline. Removing a timeline/source invalidates its local preview; it does not issue a stale cancellation request. The slider uses normalized 0..1 Core numeric semantics because that ABI is float; the accessible description gives position/duration in seconds. It retains double seconds in requests. Space/Enter use existing Button behavior; focused timeline arrows use `seek_step`, Home/End use bounds. Shortcuts never inspect global keys. Buttons retain accessible labels when icon-only. Set labels to localize them. Use each `*_icon` catalog name/path and `theme.icon_loader` for replacement SVGs. No raw SVG parsing or codec types are added to the public player contract. Visibility and capability are separate: absent `visible` flags submit no hit regions or semantics; visible unsupported actions are disabled. Seek additionally requires a known positive duration and a seekable timeline. Loading/buffering/error views disable playback/seek/rate; fullscreen remains a separate host capability. Fullscreen display follows only the confirmed `view.fullscreen` value. Volume/mute/captions have no invented state; supply separate host-backed controls when those features exist. This first bar has no auto-hide timer or overflow menu. Buttons use 44-unit touch targets and flow into additional rows within the selected width (at least 160 logical units). `cui_video_player` composes surface and optional controls. A null frame reserves surface geometry for caller-supplied loading/error content. Its frame wrapper adds source identity to the existing generation check. Mismatches fail before UI submission. Pixels remain borrowed until every renderer has consumed the draw list. No release callback or implicit decoder lease is provided. ## Extended Base slider `cui_base_slider_controlled` is an additive unstyled double-precision API. Legacy `cui_base_slider` retains its float pointer mutation and return semantics. The new function accepts confirmed value by value, caller-owned `cui_slider_state`, and `cui_slider_options`. It emits typed synchronous requests with copied source events. Invalid arguments return false without changing state. Disabled/read-only transitions cancel an active drag; no callback means no requests. State and user callbacks must survive the call. Submit it inside a box with its own stable ID. ## Real optional decoder example The [silent FFmpeg example](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/video_player/README.md) decodes on a worker, retains bounded frame leases and demonstrates confirmed play/pause/seek/rate requests. Its strict external harness runs portable controls, software decoded pixels and private-Xvfb native decoded captures. It supplies no built-in codec or universal format/browser/audio support; see its exact evidence and version/license recording before using it as a host-adapter starting point. ## Browser gallery extension The gallery provides **Video** (bare surface) and **VideoPlayer** (ready-made controls) as extensions outside the frozen 78-family baseline. Build and exercise it locally (Chromium runs headless): ```sh python scripts/build_web.py --output /tmp/cui-video-web uv run tests/web/test_video_gallery.py --offline uv run tests/web/test_video_gallery.py --directory /tmp/cui-video-web python -m http.server --directory /tmp/cui-video-web # Open http://localhost:8000/#Video ``` The browser decodes a checked-in original 12-second 320×180 sample using `HTMLVideoElement`. The visible surface, buttons and timeline are CUI draw lists; there are no HTML media controls. Play/pause, two-second skips, keyboard timeline seeks and 1× / 1.5× rate requests are acknowledged from actual media state. The sample includes a quiet generated tone and loops. VideoPlayer starts paused and plays unmuted after the user presses Play; the bare Video surface autoplays muted to respect browser autoplay policies. The browser routes decoded audio to its normal output device and keeps audio/video synchronized. Fullscreen is a browser capability and may reject a request; host errors are displayed explicitly. Volume controls, audio-device selection and subtitles are not exposed by the CUI controls yet. Native hosts must supply their own audio output; the FFmpeg example remains silent. Universal codec/browser support and Safari are not validated. The host chooses VP8 WebM or H.264 MP4 using `canPlayType`, with the alternate encoding available if decoding fails. It fetches at most 512 KiB into a Blob so this small sample can seek even when static hosting does not implement byte ranges. Fetches are aborted and Blob URLs revoked on route exit. Larger streaming applications need a separate buffering/range policy. Rebuild the original assets with `python web/assets/video/generate.py`; its receipt records local FFmpeg version, exact commands and output hashes. The generator requires local `libvpx` and `libx264` encoders and uses bit-exact output settings; two consecutive local runs produce identical files. FFmpeg is a fixture-generation tool, not a browser runtime dependency; no media is downloaded during generation. Decoded frames are copied into one fixed 230,400-byte WASM buffer. Session and timeline generation checks reject stale submission. A separate decode ticket retires pending frame callbacks during every seek; the timeline generation changes on commit/cancel/skip so active scrubbing survives updates. Seek cancel restores the position captured at begin; browser decoder completion remains asynchronous. Pixels stay unchanged throughout synchronous Canvas consumption, and revisions advance on each accepted frame. Host requests are copied into a 32-entry queue and drained after rendering, never through CUI reentry. A batch exceeding 32 requests is rejected in full with a visible limit message, resetting scrub presentation and restoring an already-active scrub origin. This sample does not promise unbounded gesture batching. Late operation promises are fenced by session, operation sequence and decode ticket. No frame callback loop runs while paused; leaving the route cancels scheduling, unloads media and exits only fullscreen owned by this preview. The focused Chromium test decodes both the actual WebM and MP4 assets, including alternate-source recovery after a deliberately invalid preferred encoding. It separates real encoded decoding/CUI interaction from injected host-error protocol checks. It checks rendered pixel changes, confirmed play/pause/seek/rate, keyboard routing, mobile DPR2 geometry, stale frame rejection, route cleanup and the separate extension catalog. Other browser/platform codec and fullscreen combinations remain unverified. --- ## VirtualList final-offset observers Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/VIRTUAL_EVENTS.md # VirtualList final-offset observers Include `cui/cui_virtual_events.h`. `cui_base_virtual_list_events` and `cui_virtual_list_draw_events` take the legacy arguments plus `cui_scroll_handler`. They execute the old operation exactly once and return its unchanged result in `control_result`, alongside `valid`, independent `changed`, delivered `change_count` and `count_overflow` (always false for zero/one aggregate delivery). The callback receives the existing pointer-free `cui_scroll_change`: float x/y previous and final offsets, `has_previous`, and CHANGE metadata. Nonfinite entry coordinates produce `has_previous=false` and a zero previous pair. Final offsets must be finite. Source is UNKNOWN, with genuine frame only; no source-presence, input index or activation evidence is fabricated. Copy payload by assignment into caller storage; copies remain usable after frame and context lifetime. Base observes after owner keys and semantics. Styled observes after all row and measurement callbacks, deferred wheel finish, translation, scrollbar paint and box closure. It does not run a Base observer internally. Deferred main-axis movement can leave `control_result.view.scroll` describing the already-rendered window while the payload describes final offset. `window_pending` and next-frame invalidation retain their legacy meaning; there is no completion callback or repeated rendering. Net-zero offset operations are silent. Disabled normalization can notify in an ordinary frame. Missing handlers still reduce and set `changed`; counts remain zero. Inert/layout-only frame-zero work preserves maintenance/results but suppresses callbacks. Non-submission entry rejects before work. Invalid legacy arguments or measurement rejection preserve legacy invalid result and produce no notification. Omission retains no handler; result reads never replay callbacks. Handler/user are borrowed until return. New observer callbacks may copy payloads and update unrelated application data, but must not mutate/free active model, widget state/options/input, recursively submit or destroy context. Defer teardown until frame completion. These restrictions apply to the new observer; existing legacy row and measurement callback behavior, timing and restrictions are unchanged. Model keys/heights must remain unchanged during existing row callbacks as required by `cui_virtual_scroll.h`. Measurements remain allowed to reject the frame. This observes float widget offsets, not double model mutation, selection, rendered visibility, data delivery or GPU completion. No retained registration, capture/ bubble, veto, context-destruction support or foreign-language facade is added. MessageScroller has a separate [double-offset and tail observer](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MESSAGE_EVENTS.md); its explicit mutators remain result-only. ## Observe scrolling in an existing frame Retain the model, widget state and application data across frames. This helper assumes the caller already began a frame and supplies its existing row renderer. The callback records the applied offset; reading the result does not replay it. ```c #include "cui/cui_virtual_events.h" static void remember_scroll(void *user, const cui_scroll_change *change) { cui_scroll_offset *saved = user; *saved = change->value; } static cui_virtual_event_result draw_list( cui_context *ui, const cui_theme *theme, const cui_virtual_list *model, cui_virtual_widget_state *state, cui_virtual_render_item_fn render_row, void *row_data, cui_scroll_offset *saved_offset) { cui_virtual_widget_options options = {0}; options.scroll.width = 320; options.scroll.height = 240; return cui_virtual_list_draw_events( ui, cui_id_from(ui, "records"), theme, model, state, options, render_row, row_data, (cui_scroll_handler){remember_scroll, saved_offset}); } ``` Check `result.valid` before using the result. Use either the callback or `result.changed` for each application side effect. `result.change_count` counts delivered callbacks, so it stays zero with a missing handler even when offsets change. Keep the saved-offset storage alive through the call. `tests/unit/test_virtual_events.c` compares legacy and observed Base/Styled results, state, consumed input, semantics and composition counts, exercises real deferred child routing, exact wheel, keys/net-zero, invalid entry, normalization/disabled, missing handlers, passive work, omission and copied payload lifetime. Intrinsic measurement tests preserve legacy callback state mutation on both success and rejection, with one service call and no notification on rejection. It also runs the existing Styled virtual regression assertions. Native executions use `python scripts/test_local.py --build-dir build -- -R virtual_events`. --- ## Optional WASI verification Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/WASI.md # Optional WASI verification The portable C11 core, base models, styled controls, geometry-only software renderer, and standalone header distributions can be compiled to `wasm32-wasi` and executed under a WASI Preview 1 runtime. This is headless runtime evidence; it does not establish browser, JavaScript host, canvas, WebGPU, DOM input, clipboard, font shaping, or accessibility support. The optional runner pins Zig **0.16.0** and Python wasmtime **49.0.0**. Zig is the C compiler, linker, WASI libc, and archive tool. `uv` resolves the Python runtime dependency from the script's PEP 723 metadata without a project environment or privileged installation. No CMake changes or native graphics dependencies are needed. Existing Zig and uv installations are sufficient: ```sh uv run scripts/test_wasi.py ``` By default the script uses the repository containing it and preserves modules, objects, and individual module stdout/stderr under `build/wasi`. `--root PATH` selects another complete CUI checkout; `--build-dir PATH` selects the output directory. `--zig PATH` locates a non-PATH Zig installation. Other Zig/wasmtime versions are deliberately rejected until the pins are reviewed. The runner builds an optimized portable static archive with C11, `-Wall -Wextra -Wpedantic -Werror`, and enabled assertions. It then compiles and executes 77 registered portable suites, including component/base behavior, implementation embedding, examples and single-/multi-TU distribution consumers. Each module gets an 8 MiB stack and a configurable instruction fuel budget (40 billion by default); exceeding the budget fails the suite. Runtime exits, traps, and compilation failures fail verification and are reported individually. The runtime receives no filesystem preopens or inherited environment variables. Host-side stdout/stderr files contain only the tested module's output. WASI does not expose a process CPU clock. The virtual test contains a separately invoked benchmark branch using `clock()`, so this runner explicitly enables `_WASI_EMULATED_PROCESS_CLOCKS` and links `wasi-emulated-process-clocks`. That compatibility layer measures wall time. The runner invokes only the normal assertion path, not the optional benchmark. Per-suite times in the transcript include compilation/runtime preparation and are not framework performance claims. The transcript records the source Git revision, whether tracked modifications were present, and a SHA256 fingerprint of all portable sources, relevant tests, public/distribution headers, and vendored Clay. If those files change while the runner executes, verification fails and must be repeated on a stable checkout. Generated output files are preserved and no unrelated paths are cleaned. Actual run evidence is in [validation/wasi.txt](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/validation/wasi.txt): **15/15 modules compiled and passed runtime assertions** against source revision `8ff89cad797e8a5737532b7249323db26bbb72fb`, with tracked modifications explicitly recorded and portable source fingerprint checked for stability. An earlier run is preserved in [validation/wasi-initial.txt](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/validation/wasi-initial.txt): 14/15 passed, and the dock serializer's decimal roundtrip assertion failed. That real target-specific failure prompted a parser correction; it was not skipped or converted into a compilation-only claim. SDL/native renderer tests and FreeType/HarfBuzz shaping are outside this runner's tested surface. The runner bounds each suite to 40 billion WebAssembly instructions (overridable with `--fuel`). The expanded Choice matrix repeatedly creates independent contexts. After touch routing expanded bounded internal dispatch storage, the exact frozen module consumed 30,484,390,481 instructions and exhausted the previous 30-billion budget. The new finite budget preserves every case and assertion. The original failure and measured rerun are retained in the release evidence; this is a runner resource limit, not a passing assertion being removed. The optional bidi module also compiles and executes under WASI, including mixed-direction wrapped lines compared directly with the pinned backend, paragraph ownership and atomic failures. Its unmodified private backend receives the same documented upstream warning exceptions as CMake; CUI wrapper/tests remain strict. This no-filesystem runtime invocation does not read Unicode conformance fixtures. The complete 861,948-case conformance suite remains a separate native/sanitizer check. --- ## Browser gallery Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/WEB_GALLERY.md # Browser gallery The static site uses the same portable CUI C implementation as native applications, compiled to a WebAssembly reactor. The browser supplies Canvas text measurement, Canvas painting of CUI draw commands, and pointer/keyboard events. HTML supplies documentation navigation, search, themes and code snippets. It is an optional host, not a dependency of native CUI applications. Each live catalog entry has a public C usage excerpt. These are frame-level fragments: create a context and theme, retain any state and IDs, and provide named callbacks before invoking them. `tests/web/test_snippets.py` checks all 78 entries against public function names, argument counts and constants, then compiles every displayed excerpt with typed setup scaffolds under C11 warnings as errors. The Chromium suite runs that check before exercising the copy button. Build with Python 3 and **Zig 0.16.0**: ```sh python scripts/build_web.py python -m http.server --directory build/web 8080 ``` Open `http://localhost:8080/`. Every asset uses a relative URL, so the same artifact works beneath GitHub Pages' `/cui/` project path. The output contains `.nojekyll` and needs no server or build-time Node dependencies. GitHub Actions owns publication. All 78 reference catalog entries appear in searchable navigation, with per-feature evidence statuses and links to the pinned comparison reference. All 78 entries have live CUI browser stories: Button, Checkbox, Switch, Toggle, Radio, Slider, Input, Label, Badge, Progress, Theme, Alert, Avatar, Bubble, Empty, GroupBox, Kbd, Skeleton, Spinner, Accordion, Collapsible, Tabs, List, Select, Menu, Combobox, NumberInput, Pagination, Rating, Stepper, Clipboard, Calendar, DatePicker, TimeField, ColorPicker, Tree, Scrollable, Table, DataTable, Tooltip, HoverCard, Dialog, AlertDialog, Sheet, Popover, DropdownButton, Form, Input Group, OtpInput, Tag, Marker, Notification, Shimmer, Message, MessageScroller, Image, Attachment, DescriptionList, StatusBar, Resizable, Icon, Toolbar, TitleBar, Sidebar, Textarea, Settings, Carousel, Command, Root View, TextView, Chart, Speech and Questionnaire, plus explicitly labeled partial base-model stories for Editor, VirtualList, Dock, Plot and Focus Trap. The navigation and feature table retain actual implementation status, including partial APIs. A browser story does not establish full reference parity. Skeleton and Spinner animate using browser frame time and respect prefers-reduced-motion. Tooltip and HoverCard demonstrate real delayed floating portals and Escape dismissal. Use pointer input or focus the preview and use Tab, Enter/Space and arrow keys. Input routes UTF-8 text into the shared editor model. Disabled, comfortable/compact density, single/multiple selection where supported and theme options rebuild actual CUI draw lists. The site follows the system light/dark preference by default, including later changes; a named light or dark palette or the separate High contrast choice overrides it until Follow System is selected again. Canvas draws at the browser device pixel ratio; CUI receives logical CSS pixels. Browser fonts are measured and painted with the same system font settings. RGBA8 bitmap commands support source crops, opacity, grayscale, tint, rounded corners and nested clips. Checkbox and Radio demonstrate four sizes, required and invalid semantics, skipped Tab stops, disabled behavior, and graphical selection marks. Switch demonstrates label placement, a custom active color, spring travel and reduced-motion settling. Toggle includes standalone selection and a three-item toolbar with single or multiple selection, segmented edges, and ghost or outline styling. The Canvas host applies the CUI core's resolved pointer cursor after each frame and mirrors toolbar and separator roles with orientation and range metadata when present. The Canvas mesh consumer decodes actual CUI expanded triangles, including analytic ST coverage and linear premultiplied colors. It rasterizes physical pixel centers at the gallery's positive uniform DPR scale plus translation, preserves ordered translucent triangles and nested pixel-center clips, and consumes Core ancestor opacity once. Other Canvas matrices and composition modes are rejected. Bounded preflight completes before resizing or clearing the target; invalid geometry or resource exhaustion leaves the existing image intact. The host limits and memory accounting are specified in [the adapter design](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/CANVAS_MESH.md). `tests/web/test_mesh_canvas.py` checks exact Canvas reference images at DPR1/2 and a Core-emitted opacity fixture. This establishes this browser host's mesh path; it does not establish exact upstream path rasterization or support in native adapters. An earlier light/dark Chromium audit of the first 62 live stories identified ASCII stand-ins in C components. The subsequent source icon artwork implementation replaced those glyphs in Button, Disclosure, Tree, DropdownButton, Input Group and Notification. The gallery’s custom disclosure header still uses `+`/`-` in `web/gallery.c`; it is sample-owned content rather than component painting. The Message avatar is intentionally bottom-aligned: `src/components/cui_message.c` follows the frozen reference's `message.rs` bottom alignment. Input Group's separate block addon rows follow `src/components/cui_form.c`; the gallery gives its inline action enough width to keep “Open address” on one line. An idle-frame audit found continuous frames only for Skeleton, Spinner, Shimmer, and Attachment's brief entrance animation; Image schedules a load deadline. With reduced motion, all 62 stories in that audit stopped scheduling continuous frames. The host applies reduced-motion preferences before `cui_begin_frame`, so input and composition see the same preference and the frame consumes its invalidation. The host also skips a late media-query notification when an animation tick has already painted its current preference. Updating the preference after begin schedules a redundant follow-up frame; the Spinner browser regression exercises repeated preference transitions and verifies both zero animation deadlines and a stable frame count. Run the meaningful browser checks with pinned Playwright 1.58.0: ```sh uv run --with playwright==1.58.0 playwright install chromium uv run tests/web/test_browser.py uv run tests/web/test_time_field.py --directory build/web ``` The focused TimeField gate independently checks real pointer/keyboard input, H12/Arabic segments, read-only behavior, bounds rejection and validation reset. It complements the complete catalog gate; passing it does not establish full catalog or platform coverage. CI may use `playwright install --with-deps chromium` on its disposable runner. An installed Chromium can instead be selected with `--chromium /absolute/path/to/chrome`. Tests serve the artifact beneath `/cui/`, instantiate the real WASM, exercise pointer activation, keyboard activation, disabled behavior, checkbox state, slider stepping and input editing; exercise delayed tooltip open/Escape, hover-card close, popup selection/menu activation, modal Tab trapping, Escape trigger-focus restoration and tab arrow navigation; inspect all live stories; verify all 78 entries, search, themes, pending entries and narrow layout. There is no mocked C implementation. Limitations: Canvas text uses browser system fonts rather than native FreeType/HarfBuzz. IME composition, clipboard support beyond the optional browser Clipboard API, mobile soft keyboard, complete screen-reader focus synchronization and browser accessibility parity are pending. The host mirrors current interactive semantics into hidden ARIA elements, but that is experimental and does not establish a complete accessibility bridge. Images, shadows, device-loss handling and unrelated unimplemented draw capabilities are not simulated. The Clipboard story bridges actual CUI buttons to navigator.clipboard and reports denied/unavailable access; secure context and browser permission rules apply. Focus Trap demonstrates a core modal scope with Tab cycling and Escape/close trigger restoration. The minimal WASI host grants no filesystem or environment access. WebAssembly exports expose draw and semantic scalar accessors instead of relying on C structure offsets or leaking platform types into the public CUI API. The shader/native GPU adapters are not linked into this Canvas host. Input includes editable, read-only and required/invalid state controls. It demonstrates the styled single-line editor with pointer caret placement, drag selection, horizontal scrolling and keyboard undo/redo. Tree demonstrates retained expansion, selection, keyboard traversal and typeahead over borrowed preorder nodes. Scrollable renders actual clipped translated content and interactive horizontal/vertical scrollbars. DataTable renders a virtual window over 1,000 keyed rows, with selection, sort requests, column resize and reorder, bounded multi-selection/ranges, a pinned name-column option and two-axis wheel scrolling; sort requests are displayed without pretending that caller data was reordered. Table demonstrates stateless header/body sections and read-only header cells. DataTable exposes cell, row and column selection controls; cell Home/End stays within a row, while row Home/End reaches the first or last virtual row. Its composed mode uses real grouped headers, row headers, bounded row hooks, trailing Inspect buttons and scrollbars. Loading and empty modes invoke caller-provided placeholders over the actual model. The Menu story provides dropdown and context triggers and uses real nested menu descriptors: disabled items, separators, labels, keyboard submenus, checkbox and radio items and shortcut hints. ContextMenu opens only from a secondary click within its receiving CUI area. Dialog, AlertDialog, Sheet and Popover are composed by the portable C surface API in the WASI module and painted through the same CUI draw list as every other live story. Dialog and AlertDialog use the additive six-slot C composition route, with current-frame intrinsic sizing. Dialog starts with compact content; its Long body control adds real preference descriptions to demonstrate scrolling above an independent Save footer. Header, Title and Content are separate slots. AlertDialog omits Body when it only needs a description and actions. The host returns to idle after input and animation settle; these demos do not require a measured-height correction-frame protocol. See [Dialog composition](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DIALOG_COMPOSITION.md). AlertDialog deliberately rejects its first destructive confirmation through a decision callback. Sheet exposes left, right, top and bottom geometry with captured pointer resizing and arrow/Home/End keyboard controls bounded by minimum and maximum dimensions. Popover is a nonmodal composed account card with interactive content, collision placement and outside/Escape dismissal. Browser ARIA projection includes dialog, alertdialog, rowheader and rowgroup roles; native adapters consume the same semantic tree and render text through their configured glyph pipeline. DropdownButton demonstrates independently focusable primary export and options-menu halves, with the portable menu tree supplying selection, disabled options, checked items and nested menus. Dialog also demonstrates nested modal focus trapping and Escape restoration to its parent trigger. Canvas consumes independent corner radii and edge widths from the public draw commands. Theme includes an asymmetric shape sample; Chromium pixel assertions verify square and rounded corners, unequal border widths and explicit absent edges at device scale two. Canvas also reads each text command's weight, italic and monospace flags. The browser's styled measurement callback and paint use the same CSS font specification and a style-keyed baseline cache. Theme includes semibold, italic and monospace samples; Chromium checks both their actual Canvas font selection and measured layout widths. Form composes application-owned name/email editors with required labels, descriptions, validation errors and a Save footer. Its responsive grid switches between two columns and one; valid, email-error, read-only and disabled variants retain genuine input behavior and semantic associations. The sample validates a nonempty name and an email containing @ and a dot; submission and validation belong to the application. The Input Group story uses the retained editor with inline and block addons, an actual action button, and read-only, disabled and loading variants. The application owns the address and action count. OtpInput normalizes ASCII and fullwidth digits through the actual C reducer, supports groups and masking, reports completion counts, and schedules caret wakes at the component-provided deadline while leaving other frames idle. Tag demonstrates actual intent and named palette colors, outline/pill styling, passive labels and rich children. Marker demonstrates plain/separator/border layouts, alignment, typed text/icon and rich content, spinner suppression by typed icons, shimmer and reduced motion. Notification demonstrates actual in-app retained lifecycle timers, all eight anchors, collapsed/expanded stacks, arbitrary focusable content, actions and dismissal. Browser deadlines drive frames; OS notification delivery is not simulated. Accordion and Collapsible include optional retained spring reveals, interactive panels, custom header/box composition and multiple accordion panels. Closing subtrees continue painting while their semantics and input are inert; reduced motion snaps panels and leaves settled frames idle. Theme also demonstrates passive and explicitly focusable Log semantics. The host projects the core focusable flag into Canvas Tab routing while leaving passive logs and list items outside the tab sequence. Shimmer renders standalone animated text with repeat, reverse, once and absolute spread controls, clipped width and reduced motion. Tabs exposes all five variants and four source sizes, automatic/manual activation, bounded horizontal/vertical strips, selected-tab reveal, an all-tabs menu and keyboard/pointer scrollbars. Structured slots and caller-applied drag reordering still need dedicated browser coverage. DropdownButton exposes all twelve variants and four sizes, custom palettes, outline/selected paint, independently disabled/loading actions, split/menu-only/action-only composition and four anchors. Browser checks cover independent action/menu routing and captured pressed colors. Tooltip composition and inherited action properties still need dedicated browser coverage. Message composes real avatars, metadata, multiple bodies, seven Bubble styles and interactive content with alignment/inset controls. MessageScroller retains a variable-height application collection with tail following, append/prepend/removal, a focusable Log, optional scrollbar and animated jump/fade behavior. Image uses application-owned RGBA8 frames with a cached browser raster keyed by pointer, dimensions, stride, revision, grayscale and tint. Its story exercises all five fit modes, crop, delayed loading, fallback, opacity, grayscale, animation and reduced motion. Attachment composes six application-owned cards in a horizontal scroll group with lifecycle states, image media, actions, remove/retry callbacks, vertical layout and edge fades. DescriptionList demonstrates source row packing across one to three columns, vertical and bordered variants, and all four sizes. StatusBar composes left, center and optional right regions with default or caller styling. Resizable demonstrates constrained horizontal and vertical panels, keyboard and pointer resizing, and disabled handles. Icon renders bundled SVG masks through the Canvas bitmap path with source assets, sizes, transform and inherited or explicit theme tint; its caller-owned raster cache is collected only after the prior draw list has finished painting. Toolbar demonstrates the source size metrics, command activation, nested formatting group, optional input, scoped Left/Right navigation, wraparound, and editor caret priority. The Disabled host control disables its commands and input. TitleBar paints the source-height gradient and title slots. Browser mode hides window controls as in the reference WASM environment; an optional simulated client-decorated host exercises minimize, maximize/restore, close override, title drag, context menu and double-click actions without changing the browser window. The top-right theme picker uses the 38 pinned upstream kit theme presets, grouped by light and dark mode, plus Follow System and a separate high-contrast choice. Follow System starts from the browser color-scheme preference and responds to changes; an explicit named choice persists by ID in local storage. The page CSS and WASM preview use the same resolved preset. The picker supports arrows, Home/End, Enter, Escape and outside-click dismissal. `themes.json` is generated from `third_party/gpui_themes/presets.json`, and the site license bundle includes its attribution. Aurora's source gradient tokens currently use their first stop in the portable C theme; this is a documented adaptation, not full visual parity. Input and NumberInput expose all four source sizes through the gallery size selector. Input keeps its accessible name while painting only the single-line field, with no extra label row. NumberInput paints real SVG increment/decrement glyphs; the browser exercises their CUI pointer interactions and controlled value changes. The native size APIs define the height and font metrics; the gallery uses those actual styled components. Settings composes two application-owned pages and six fields through `cui_settings`: search, sidebar navigation, Checkbox, Switch, Input, NumberInput and a checked Menu-backed workspace choice. The gallery exposes its three variants and four sizes. Browser checks exercise field changes, menu selection, page navigation and option changes; values remain owned by the sample application. Carousel uses four real CUI slide items with source controls and pagination. Browser checks step in both axes, select a page, and wrap from the last slide when looping is enabled. Slide selection and its callback count come from the retained C state; animation is driven by the host frame clock and reduced-motion preference. Command renders the real inline palette with a retained query editor, filtered virtual rows, icon/shortcut/checked/disabled entries, keyboard navigation and action callbacks. The optional dialog mode hosts the same palette in a CUI Surface. Browser checks filtering, pointer and keyboard confirmation, loading semantics and two-stage Escape behavior: first clear the query, then cancel the dialog. Root View uses a caller-owned per-window plugin registry and automatically mounts a Dialog, Sheet and Notification layer after application content. Its sample plugin changes Root padding and paints an ordinary overlay at an absolute location without taking application layout space. Browser checks actual callbacks, separate overlay bounds, Dialog and Sheet interaction, and notification mounting; global text selection and OS window facilities remain outside this module. TextView renders a bounded caller-owned document in Markdown, safe HTML, or plain text, with real styled text, links, selection, and optional scrolling. The gallery highlights a Markdown range and checks link activation; the underlying parser is an explicit subset and does not provide complete CommonMark or HTML5 support. Chart rasterizes caller-owned data into RGBA pixels for line, area, bar, pie, radar, candlestick and Sankey stories. The gallery exercises each family, curve and label controls, with source-style optional appear animation and pointer hit behavior. The seven C adapters remain partial against the pinned source; see [CHART.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CHART.md) for the exact method audit. Speech is a deterministic provider demonstration. Caller-owned callbacks feed ready/interim/phrase/final/error events and PCM samples into the real Speech state, SVG icon button, and waveform. Browser checks provider lifecycle, transcript, teardown, sizes and reduced-motion stability. The site does not request a microphone or provide system recognition; [SPEECH.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SPEECH.md) tracks those platform gaps. Questionnaire composes the retained two-step model with item, choice and action containers, a radio group, graphical choices, optional freeform input, validation, Skip/Next/Previous/Submit actions, progress and four source sizes. Its browser story exercises real CUI pointer events, custom indicator/content/shortcut callbacks, and grouped-choice accessibility semantics. Automatic root shortcut routing, cross-item focus transfer, localization and exact source styling remain incomplete; see [QUESTIONNAIRE.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/QUESTIONNAIRE.md). The browser host forwards all ASCII letter and digit key identities to CUI alongside text events, preserving the original special-key values. Questionnaire routes alphabetic or numeric shortcut hints through the explicit C keyboard helper when its answer scope owns focus. Browser composition flags suppress shortcut activation; committed composition text reaches the retained input. Root-wide shortcut capture, cross-item focus transfer and a complete IME bridge remain pending. The browser provides `cui_measure_font_metrics` from Canvas font-wide ascent and descent for the selected weight, italic style and family. Its line spacing remains the gallery's `font_size * 1.25`, matching text layout and the alphabetic `fillText` baseline. If the browser lacks `fontBoundingBoxAscent` or `fontBoundingBoxDescent`, the callback reports unavailable and painting falls back to Canvas's top baseline; it does not treat sample-glyph ink bounds as font metrics. The browser host forwards mouse click counts from MouseEvent.detail because PointerEvent.detail is zero in Chromium. Touch and pen pointer events use one click and suppress compatibility mouse duplicates. Physical Chromium single, double and triple clicks and a touch tap verify raw WASM down/up counts. This supplies metadata; TextView multi-click selection remains under development. ## Shareable URLs and product media The build generates a static page for every component and every published documentation entry. Component URLs use `/cui/components/checkbox/` and documentation URLs use `/cui/docs/start-here/`. Legacy fragment links continue to work; the browser updates the address to the matching real page. Each static page has its own canonical URL, title and description, Open Graph metadata and a large-image social card. These tags and fallback component/documentation content are present before JavaScript runs. `sitemap.xml` lists the generated routes, and `routes.json` provides their machine-readable index. Metadata follows the [Open Graph protocol](https://ogp.me/). Actual platform caching and preview appearance are controlled by the sharing service. The homepage's light and dark workspace images show the actual CUI WebAssembly renderer. The social card uses the same original product capture. `web/assets/PROVENANCE.md` documents their source and the pinned regeneration script. `scripts/build_sharing.py` validates the share image dimensions and rejects duplicate or unsafe routes; `tests/test_sharing.py` checks complete page coverage and crawler-visible tags. Dock's gallery opts into `cui_dock_create_nary`: repeated horizontal splits become siblings under a stable split node. The browser suite splits three panes and drags the second divider, checking that only its two neighbors resize; reset, zoom and cross-region tab transfer remain covered. Existing applications retain binary/v1 behavior with `cui_dock_create`. Editor's gallery attaches eight live selection slots, bounded history snapshots and measured-column anchors. Ctrl/Alt+Up/Down or Alt-click adds cursors; text is inserted at each cursor as one undoable edit, and Escape collapses extras. The browser checks three-cursor typing and collection restoration through Undo/Redo. Further multi-range clipboard, indentation, rectangular dragging and IME behavior remain separate source work. ## Calendar and hex-entry examples Calendar exposes independent **Month menu**, **Adjacent days** and **Mark today** options through the real Calendar presentation API. The host supplies today's local civil date; the component reads no clock. Selecting an adjacent date updates selection and recenters when required. Month navigation preserves selection. The control row stacks at narrow widths. See [CALENDAR_PRESENTATION.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CALENDAR_PRESENTATION.md) for the API and lifetimes. ColorPicker also demonstrates the owned byte-RGBA hex entry from [COLOR_ENTRY.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COLOR_ENTRY.md). Editing changes its draft and preview; Enter commits a complete value into the picker. Incomplete drafts remain editable. Picker changes preserve a dirty draft until **Use picker color** explicitly replaces it. Owner synchronization runs before the next frame, after the previous draw list has been consumed. This demo is separate from the float-HSLA entry API; it does not establish HSLA popup or tab coverage. ## CI execution Pages builds the default and regex-enabled gallery once, then shares those exact artifacts with three independent browser-check groups. All existing checks remain required; deployment waits for the build and every group. Each group has a private runner and headless Chromium, so probes and temporary servers remain isolated. The transfer contains only generated gallery/fixture files, including `.nojekyll`; its artifact expires after one day. Dependency versions and Action revisions remain pinned. No cross-revision CUI gallery or fixture binary cache is used. Pages caches dependency inputs separately from those tested artifacts. The existing Python setup caches pip downloads using the workflow as its dependency key, covering the pinned uv 0.10.8 and Zig 0.16.0 distributions. Browser groups cache uv's package cache per OS, architecture, Python/uv/Playwright version, shard and test-source hash; a fallback is restricted to that same host/version/shard prefix. Chromium downloads use a separate exact OS/architecture/Playwright 1.58.0 key, shared by the shards. Only the optional Rust toolchain's manifest and two input archives are cached against `backends/regex/pin.json`; installed Rust executables, regex libraries and gallery build outputs are excluded. The preparation script still verifies each archive's checksum and reinstalls the private toolchain on every run. Pip installation, Playwright installation with Linux OS dependencies, every test and deployment gates also run on cache hits. `tests/test_pages_tool_cache.py` checks this policy offline. Before this cache change, run [39769287993](https://github.com/mattmezza/cui/actions/runs/39769287993) recorded 6 seconds for build-tool installation, 45 seconds for private Rust preparation and 50 seconds for the regex build. Browser-tool installation took 25 and 29 seconds on shards 1 and 2. Shard 3's same step eventually completed in 11 minutes 53 seconds (2026-10-22 11:19:25–11:31:18 UTC). Its full job logs were still unavailable, so these observations do not identify whether package downloads, browser downloads or Linux dependency installation caused the delay. No warm-cache timing has been measured for this change. Cold misses still download dependencies; simultaneous cold shards can download the same browser before any job has saved its cache. Cache transfer and save overhead can offset download savings. Playwright specifically cautions that browser-cache restoration can take as long as downloading, and Linux OS dependencies still require normal installation ([upstream CI guidance](https://playwright.dev/python/docs/ci#caching-browsers)). The baseline Pages run [39397271176](https://github.com/mattmezza/cui/actions/runs/39397271176) spent 25.6 minutes in its sequential build/check job. The three groups were balanced using that run's recorded step durations. The first parallel run [39401871665](https://github.com/mattmezza/cui/actions/runs/39401871665) passed all 67 checks: build plus browser validation took 11 minutes 42 seconds (09:36:33–09:48:15 UTC), about 54% less elapsed time than the baseline. This is one hosted-runner observation, not a guarantee or a reduction in total runner minutes. Deployment was intentionally skipped on the experiment branch. Hosted runner capacity and queue time also affect latency. Portable matrix builds use two concurrent compilation jobs; tests keep their existing execution order. Core and native-binding workflows cancel superseded runs on the same ref. No test coverage or deployment acceptance gate was removed. DatePicker retains its default extended-API example and locale selector. Enable **Date-only actions** for two application-owned preset dates, then optionally enable its clear button and scoped Delete key. The copy button follows the active mode and includes retained state/value initialization for the actions example. Dismiss an open modal popup before using its outside clear button. Desktop and touch tests exercise these actions and compile both copied C snippets. This coverage excludes date-time editing, arbitrary styling, observers and bindings. DatePicker additionally offers an explicit **Date + time** mode using the optional single civil date/time C facade. Minute/second, 12/24-hour and clear/Delete controls appear only in that mode; date-only/Date-only actions modes remain available when it is off. See `docs/DATE_TIME_PICKER.md` for state transfer, preset/default-time and source-event limits. Headless desktop and CDP touch proof lives in `tests/web/test_date_time_picker_gallery.py`; copied snippets strictly compile as C11. HoverCard offers explicit legacy hover/focus, conservative tap and raw-primary-release modes. The tap modes show the additive direct-C policy and copyable C snippet; raw releases use prior content-only bounds, while conservative taps retain the matching outside down/up rule. `tests/web/test_hover_card_release.py` is the focused actual-WASM mouse/keyboard/touch regression fixture; its execution is a separate validation step. Native collapsed accessibility and foreign binding policy exposure remain limited as described in `HOVER_CARD_EXTENDED.md`. --- ## Optional pinned regex provider Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/backends/regex/README.md # Optional pinned regex provider This backend is separate from default C11 CUI builds. It implements the portable `cui_text_match` ABI with source Regex1.13.1 admission and capture-free regex-automata0.4.18 PikeVM matching. See `docs/INPUT_REGEX.md` for Input ordering, lifetimes, limits and proof. `pin.json` records exact source Cargo.lock crate archives, official Rust1.85.1 manifest/toolchain archives and the private patch SHA. `Cargo.lock` is a separate frozen path-dependency build lock; archive checksums remain authoritative. `cache.patch` only adds bounded fallible capture-free cache preparation; original upstream APIs are unchanged. The patch is not a general fallible capture API. All external sources remain in the caller's private cache, never vendored binaries or global installations. Use an already verified complete official Rust1.85.1 prefix with matching target std. `scripts/build_regex.py --cache CACHE --toolchain PREFIX [--archive-dir VERIFIED_ARCHIVES] [--target wasm32-wasip1]` verifies every crate archive before extraction and the patch/lock digests, then builds offline/locked with private CARGO_HOME. With archive-dir missing, the script may fetch only pinned checksum-verified crate URLs. The script never installs a toolchain, changes rustup or invokes a default Cargo registry download. Target std must match the exact compiler. The toolchain receipt documents verified official acquisition; the supplied installed prefix is trusted caller-owned tooling and is checked for exact version/commit. Source/parser compilation and Arc ownership creation may use infallible Rust allocation; OOM can terminate the process. Session creation/rebinding uses seven fallible cache reservations plus one fallible handle allocation. Match performs zero allocation. Native ordinary panics are caught at C entrypoints, but a host's default panic hook may print before catch; the backend neither logs candidates nor replaces a global hook. WASI panic recovery is unsupported. Handles/leases must be valid, externally synchronized, and used on one thread; forged pointers and direct caller writes are not protected. Native Linux archive link dependencies are taken from Rust1.85.1's `native-static-libs` receipt: gcc_s, util, rt, pthread, m, dl, c. WASI reports libc only. Do not copy the Linux dependency list to another target. `backends/regex/CMakeLists.txt` is a standalone strict consumer harness accepting prebuilt regex/Core archives; it never invokes Rust. Root optional OFF-by-default registration, relocatable install/package targets and platform-specific CI are integrator-owned. No native Windows/macOS binary support is claimed by the Linux receipt. Distribute the applicable notices under `licenses/` with optional artifacts: MIT chosen for alternate-license crate dependencies, Rust MIT/Apache notices and its complete official COPYRIGHT inventory. Root's dependency registry/install notices remain separate registration work. No source Input-family completeness claim follows from this optional matcher slice. --- ## SDL3 compatibility adapter Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/backends/sdl3/README.md # SDL3 compatibility adapter This optional C11 adapter owns an SDL window and an `SDL_Renderer`. It is separate from the SDL_GPU adapter. `cui_sdl3_driver()` reports the renderer selected by SDL; the accelerated capability is set only for a selected driver other than `software`. A detected OpenGL driver does not prove hardware execution rather than a Mesa software driver. Call creation, input polling, rendering and destruction on the main thread. The caller owns the `cui_font` and must keep it alive until adapter destruction. Primary, secondary and middle mouse buttons, stable touch contacts, keyboard modifiers, repeated keys, precise wheel input, UTF-8 text and composition events are translated. Compatibility mouse events generated by touch are suppressed. Window resize/expose invalidates the UI. Quit and window close cause `cui_sdl3_poll()` to return false. The clipboard-only `cui_platform` interface supplies `clipboard_set` and `clipboard_get`; its `poll` and `text_input` callbacks are null. The getter's storage lasts until the next getter call or adapter destruction. Embedded NUL bytes are rejected on set. SDL text input is enabled at creation. The adapter forwards composition/preedit with UTF-8 byte ranges and scopes commits to the original focused control. The focused painted caret updates the host candidate rectangle. See [IME](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/IME.md) for the four tested consumers and remaining physical-device/OS validation. Rendering supports solid fills, rounded rectangles and borders, nested rectangle clipping, source-alpha blending and HarfBuzz/FreeType glyph coverage. Rounded geometry uses one horizontal strip per pixel row; it has no multisample edge antialiasing. Textures persist in an LRU cache with at most 256 entries and 4 MiB of stored grayscale coverage (up to 16 MiB of RGBA texture data). A cache key uses dimensions, coverage hash and byte comparison; texture color/alpha modulation allows reuse across theme changes. Allocation, font and draw failures propagate as `false`. Glyphs that exceed the cache memory budget fail explicitly. Analytic triangle meshes use bounded CPU coverage rasters uploaded as ordered SDL textures. Per frame the adapter permits 256 triangles and 8 million clipped texels (32 MiB uploaded RGBA), plus one triangle scratch buffer of up to 32 MiB; SDL/driver allocations are additional. Unsupported transforms, malformed commands and capacity exhaustion fail explicitly. Mesh preparation occurs before clearing; later draw failures are not whole-frame atomic. Resources are released on failure and the next frame can retry. See [the mesh contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SDL3_MESH.md) for clipping, presentation transforms, limits and recovery. Private-Xvfb software readback tests cover pixels and injected failures; physical GPU and other OS drivers remain separate validation requirements. Use `cui_sdl3_render_capture()` to save a BMP before presentation while framebuffer contents are defined. The lower-level `cui_sdl3_save_bmp()` reads the current framebuffer; do not rely on its contents after `SDL_RenderPresent`. Validation on the development machine: SDL3 3.4.16, Linux Xorg with SDL `opengl` driver, and SDL dummy video with `software` driver. Other platforms and Wayland require their own runtime validation. The adapter does not provide native accessibility bridges, pen translation, GPU resource sharing or image commands. Touch routing and composition have injected SDL service tests; these are separate from real touchscreen and OS candidate-window acceptance. Frame scheduling: call `cui_sdl3_frame_delta()` immediately before each submitted frame to measure monotonic elapsed seconds (first call is zero). Presentation already requests vsync; an additional fixed sleep reduces the achievable refresh rate. When Core has no redraw demand, `cui_sdl3_wait_events(backend, timeout_ms)` sleeps until input or the caller's deadline, retaining the wakeup event for poll. Idle waits reset the frame clock so a newly triggered animation starts at its first frame rather than skipping the time spent idle. Run `cui_sdl3_poll()` after rendering and before an idle wait to apply the latest text-input focus and caret, then again after waking to dispatch input. Keep submitting frames while `cui_needs_redraw()` is true, including animation demand. The examples cap idle waits at 250 ms; applications with external timers should choose their nearest deadline and explicitly invalidate Core when their model changes. Threaded producers can arrange an SDL event wakeup on the main thread. For a daemon-style native host, create the window hidden from its first instant: ```c cui_sdl3 *host = cui_sdl3_create_with_options("Notifications", 480, 320, font, (cui_sdl3_window_options){.initially_hidden = true}); /* Later, on the main thread: */ if (host) cui_sdl3_set_visible(host, true); ``` The option sets SDL's hidden flag in the window constructor; no visible window is created and then hidden. Zero options and `cui_sdl3_create()` preserve visible creation. `cui_sdl3_is_visible()` queries SDL's hidden flag; it does not establish whether a window is occluded or minimized. Visibility operations are main-thread only and the OS may map/unmap asynchronously. The old constructor ABI is unchanged; the new options type does not extend any existing by-value structure. Sokol and SDL_GPU adapters do not own windows: their host must request hidden creation. Bridge and language builder native runners expose opt-in hidden creation through independent window options; see [binding builders](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BINDING_BUILDERS.md). Linux X11/private-Xvfb validation does not establish Wayland, Windows or macOS behavior. ## Opt-in V2 painting The unreleased C query/render route is described in [SDL V2](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SDL_V2.md). It uses bounded shared CPU painting and explicit native transfer; it does not change the V1 renderer table or imply SDL_GPU/foreign-binding support. --- ## SDL GPU renderer Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/backends/sdl_gpu/README.md # SDL GPU renderer The Vulkan/SPIR-V adapter submits mesh commands through a dedicated vertex buffer and premultiplied triangle pipeline. The fragment shader evaluates quadratic coverage from interpolated ST derivatives; it never rasterizes a mesh bitmap. The frame limit is 196608 mesh vertices and 32768 draw records. Invalid meshes or capacity overflow reject the frame before the render pass changes the target. The RGBA8 UNORM target retains the existing byte-domain primitive behavior. Linear premultiplied paint is unpremultiplied, sRGB encoded, and premultiplied by alpha and analytic coverage before ONE/ONE_MINUS_SRC_ALPHA blending. This conversion preserves colors alongside byte primitives; it is not linear-light framebuffer compositing. The native pixel tests require a real Vulkan device and window, and exercise overlap, transformed placement, DPI clipping and curve coverage. Coverage follows the frozen lockfile's `upstream-pre-wgpu 0.3.8` shader function `src/shaders.wgsl::fs_path_rasterization`, including the norm of both S derivatives in its0.001 solid fast path. Intel Vulkan readback checks numeric coverage for ordinary and vertical-S triangles, mixed rectangle/mesh ordering, borrowed vertices, mesh capacity failure and unknown-command rejection. --- ## Deterministic software renderer Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/backends/software/README.md # Deterministic software renderer This adapter allocates an owned, straight-alpha RGBA8 image with dimensions up to 16384 by 16384. Resize is transactional: allocation failure preserves the old image. Pixel pointers remain valid until the next resize or destruction. Each render clears the image, composites solid and rounded geometry, draws rounded borders and intersects nested clipping rectangles (maximum depth 64). Coverage is tested at pixel centers; geometry edges are not antialiased. Alpha composition preserves straight RGB even when destination alpha is zero. Malformed clipping stacks and nonfinite geometry return `false`. With `CUI_HAS_TEXT`, the caller may supply an owned `cui_font` to render shaped grayscale glyphs. Keep that font alive until renderer destruction. Without a font or text support, text commands return `false`; the text capability is unset. Geometry-only compilation requires the C11 standard library and math library, without SDL, FreeType or HarfBuzz. CMake consumers should link the `cui_software` target. Manual source builds must include `src/core/cui_background.c` alongside the Core and Effects sources: the software adapter contains V2 background preparation even when the application uses only its V1 entry points. This is a source-link dependency, not an additional external library. PPM capture exports RGB and discards alpha; it is intended for opaque screenshot frames. No GPU acceleration or native accessibility is claimed. The unreleased C-only V2 route uses `cui_software_query_v2` before composition and `cui_software_render_v2` for bounded transactional rendering; it is separate from the unchanged V1 function table. It supports owned backgrounds, AREA shadows and independently scaled grayscale text with explicit limits. See [the software V2 guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SOFTWARE_V2.md) for query/defaults, failures, resource/font ownership and busy destroy retry. Other adapters/bindings remain pending. The private guard adds8 bytes on measured native/WASM32 objects; V1 field offsets/table/pixels and ordinary allocation call counts are preserved. --- ## Independent Sokol GLCORE renderer Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/backends/sokol/README.md # Independent Sokol GLCORE renderer This adapter consumes CUI draw lists directly through pinned `sokol_gfx.h`. It does not call SDL_Renderer or SDL_GPU, does not include SDL, and does not use `sokol_app`. The separate example uses SDL3 solely to own a desktop OpenGL host. Create a desktop OpenGL 3.3 core context and make it current before calling `cui_sokol_create`. Keep that same context current on the creating thread for all adapter operations, including destruction. The host owns the window, GL context, framebuffer and font. An RGBA8, single-sample framebuffer is required; the pipeline does not use depth or stencil attachments. ```c cui_sokol *renderer = cui_sokol_create((cui_sokol_config){ .font = font, .target = {.framebuffer = 0, .width = pixel_width, .height = pixel_height} }); cui_renderer backend = cui_sokol_interface(renderer); backend.render(backend.user, &draw_list, clear); /* The host presents its window after rendering. */ ``` The target dimensions are physical pixels, while draw-list dimensions are logical pixels. Update the target after resize or DPI changes. Nested clipping intersects in logical coordinates and becomes a physical scissor. Command order is preserved. The adapter clears and owns one complete pass per render; it is not a function to call inside an already-active Sokol pass. By default, the adapter initializes Sokol and commits each successful frame. Only one owner may initialize the process-wide Sokol runtime. Other adapters may set `borrow_runtime=true` to share an existing GLCORE Sokol runtime; in that mode the host performs `sg_commit()` after all its rendering. Destroy borrowers before the owner. Host-owned Sokol must stay alive and provide compatible resource pool capacity. If the host already compiles Sokol's implementation, compile this adapter with `CUI_SOKOL_EXTERNAL_RUNTIME` to avoid duplicate symbols. The adapter changes GL state; host GL code must restore its state afterwards. It resets Sokol's state cache before its pass to accommodate preceding host GL calls. It does not own or destroy external framebuffer objects. Each adapter renders at most once per Sokol frame; rendering it again before the host commits returns `false`. Borrowing requires the exact pinned Sokol API. Solid and rounded fills, rounded borders, rectangular clipping, and source-alpha blending are implemented. Rounded coverage uses a signed-distance fragment shader with derivative antialiasing. Ordinary sharp rectangles retain full coverage even when only one pixel wide. RGB blending uses straight source colors with SRC_ALPHA/ONE_MINUS_SRC_ALPHA, while alpha uses ONE/ONE_MINUS_SRC_ALPHA. Transparent framebuffer readback follows that GPU blend convention; it is not the software adapter's straight-alpha image export. Optional `CUI_HAS_TEXT=1` enables the caller-owned FreeType/HarfBuzz font. Shaped glyph coverage uses immutable GPU textures and a bounded LRU cache: at most 256 entries, 4 MiB CPU coverage, and 16 MiB RGBA GPU glyph storage, plus bounded creation scratch. Glyphs already referenced by the current frame cannot be evicted. A frame exceeding the cache's capacity fails explicitly rather than destroying a texture still needed by that frame. Warm-cache glyphs allocate no new textures and tint/alpha changes reuse coverage. Without a usable font, text commands fail and the text capability is absent. CPU frame staging and the GPU vertex buffer are bounded by `max_quads` (default 8192, maximum 100000). Malformed draw commands, unbalanced clipping, excessive geometry or glyph capacity are rejected before a render pass starts. Shader and resource creation states are checked. Underlying Sokol fatal allocation or GL assertion failures are not a device-loss recovery path. Bitmap image commands use the existing bounded RGBA cache. Gradient mesh paint, shadows, general transforms and non-GL Sokol backends remain unsupported. The unmodified upstream pin and license are in `third_party/sokol/PIN.md`. Build this source with `include/`, a SYSTEM include for `third_party/sokol`, and the platform desktop GL library plus math. Text additionally links `cui_text`. The adapter library has no SDL dependency. The demo links core/components, SDL3, GL and optionally shaped text: ```sh cui_sokol_demo --smoke 3 --screenshot sokol.ppm ``` Verified on Linux Xorg with GL vendor Intel and renderer `Mesa Intel(R) Graphics (ARL)`. FBO readback tests cover blend/order, nested clip, logical/physical scaling, rounded fill/border, glyph coverage, persistent-cache reuse/eviction, bounded frame failure and borrowed-runtime ownership. The same geometric adapter compiles and runs without FreeType/HarfBuzz. Other operating systems, Wayland, GLES, Metal, Vulkan, D3D11 and WebGPU are unverified or not implemented by this adapter. Software OpenGL drivers may run the same GLCORE API; the API name alone does not prove hardware execution. Native mesh commands upload borrowed XY/ST triangles to the bounded vertex stream. A separate premultiplied pipeline computes the pinned quadratic source coverage from screen-space derivatives; meshes do not use the bitmap cache. The existing RGBA8 target stores byte-domain sRGB-like values. Mesh linear premultiplied paint is unpremultiplied, sRGB encoded, then premultiplied by alpha and coverage before blending. This preserves primitive appearance but does not claim linear-light framebuffer compositing. Mesh capacity consumes one quad slot per six vertices (or one final three-vertex slot); overflow rejects the frame before its GPU pass. The coverage equation follows `upstream-pre-wgpu 0.3.8`, pinned by the frozen upstream Kit lockfile: `src/shaders.wgsl::fs_path_rasterization`. The solid fast path tests the norm of both S derivatives against0.001; this matters for vertical curves. Real Intel/Mesa GL readback tests check numeric coverage in both orientations, encoded half-alpha overlaps, mixed primitive/mesh ordering, translated DPI clips, borrowed vertices, capacity failure and unknown-command rejection. --- ## Async URL fetch: optional Linux host example Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/async_fetch/README.md # Async URL fetch: optional Linux host example This example uses an existing synchronous CUI Button `on_click` handler to queue an HTTPS fetch and return immediately. It shows loading, disables duplicate fetches, supports cancellation/retry and applies completions on the UI thread. It adds no event API, scheduler, networking or thread pool to Core. The worker and transport interfaces in this directory are private example code. ## Build and run Supported and tested host: Linux x86-64, POSIX pthreads, glibc 2.44, SDL 3.4.18, libcurl 8.22.0, C11, GCC 16.2.1. macOS/Windows/WASM hosts are not supported by this example's CMake file. Native CUI still has its own broader host support; this example makes no new claim about those hosts or GPU hardware. The standalone build uses the repository's CUI libraries and installed FreeType/HarfBuzz/SDL packages. It downloads nothing and sets `CUI_FETCH_SDL=OFF`. SDL and curl pkg-config versions are checked exactly, with these tested defaults. Supply already installed dependencies matching them; explicit `AF_SDL_VERSION` / `AF_CURL_VERSION` overrides select another exact version and require revalidation. They do not mean untested versions are verified. From the repository root: ```sh pkg-config --modversion sdl3 libcurl cmake -S examples/async_fetch -B build/async-fetch -G Ninja \ -DCMAKE_BUILD_TYPE=Debug cmake --build build/async-fetch \ --target cui_async_fetch test_async_fetch test_async_fetch_curl python scripts/test_local.py --build-dir build/async-fetch -- -R '^async_fetch_' ``` `AF_TEST_FONT` is a CMake file-path override for the offline SDL tests; by default it uses the repository's discovered `CUI_TEST_FONT`. If absent, SDL tests are not registered: inspect the configure output/CTest list instead of claiming they ran. Use a known Latin font such as Noto Sans. Normal use opens a window only when explicitly launched: ```sh build/async-fetch/cui_async_fetch \ --font /path/to/NotoSans-Regular.ttf --url https://example.com/ ``` Choose **Fetch URL** to perform the network request. No request starts at launch. The URL is a command-line value, not a new Input callback API. The example accepts printable ASCII HTTPS URLs up to 2048 bytes (percent-encode other bytes). A success displays received byte count/HTTP status; binary response data is not passed to CUI as unvalidated UTF-8. Failure, including a response exceeding the body limit, displays an error and labels the action **Retry fetch**. Retrying an oversized response may fail again unless the server returns a smaller body. The retry button uses the same existing synchronous handler as initial fetch. Cancel invalidates the request generation and enables a subsequent attempt. If the single pending job slot is still occupied, the UI reports busy and the caller can retry; it never waits for transport in the handler. To build/test without libcurl, while retaining the actual SDL offline example: ```sh cmake -S examples/async_fetch -B build/async-fetch-offline -G Ninja \ -DAF_WITH_CURL=OFF cmake --build build/async-fetch-offline --target cui_async_fetch test_async_fetch python scripts/test_local.py --build-dir build/async-fetch-offline -- -R '^async_fetch_' ``` For only the worker/model tests, with neither SDL nor Core/network dependencies, set both `AF_BUILD_UI=OFF` and `AF_WITH_CURL=OFF` and build `test_async_fetch`. Interactive live fetch is unavailable without curl; the host reports this and requires `--offline-smoke`. All automated tests use injected transport or pre-transfer cancellation, never an external network. ## Ownership and dispatch contract | Boundary | Owner / lifetime | | --- | --- | | Button callback | Synchronous UI thread; validates model and copies URL into the worker's one pending slot. No fetch, wait, join or transport call here. | | Worker transport | One pthread, one active request. Receives its own URL buffer and fixed result storage. Transport userdata remains alive through worker join. | | Completion mailbox | Two fixed slots protected by a mutex/condition variable; body at most 8192 bytes, error at most 159 bytes plus NUL. A full mailbox blocks the worker publisher, not the UI callback. Shutdown wakes this wait. | | Wakeup | Worker calls `SDL_PushEvent` with a registered user-event type and no pointer payload. This is a notification, never a CUI call or render callback. | | UI model | Created and applied on its owning thread. `af_model_start/cancel/apply/drain` reject use from another thread. Only UI code applies completions or calls CUI. | | Shutdown | Signal stop, wake worker waits, request cooperative abort, join, then release curl globals, CUI, SDL host and font. No callback can use app/host storage after join. | `fetch_clicked` in [main.c](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/async_fetch/main.c) is the actual callback wired to `cui_button_options.on_click`; it calls `af_model_start` and invalidates the UI. The returned frame result is not used for a second side-effect path. The callback can affect loading text later in that submission, while already-painted frames remain unchanged. Existing button semantics and callback timing are not replaced or moved to a new queue. The worker never owns a pointer to the UI model. It owns request/result bytes; the UI takes a completion copy before applying it. A copied result can be held and applied later, but matching generation plus current loading state is required. Stale, duplicate and deliberately reordered completions cannot replace the current result. Each accepted start gets a new generation; cancel also advances it. Exhaustion rejects starts before uint64 wrap. Workers execute requests serially: the out-of-order application test deliberately reorders copied completions, not two claimed concurrent network operations. For a removed view, invalidate its generation before omitting it and stop applying that model. Do not free transport/wakeup userdata while its worker can still run: join first, or keep that data in an app-owned object that outlives the view. The sample closes its entire host using the join-first path. Worker functions are synchronized, but callers must stop using a worker before `af_worker_destroy`; a freed worker pointer cannot be reused or destroyed twice. `af_worker_destroy(NULL)` is safe. No arbitrary-thread CUI/destruction support is implied. ## Cancellation, timeouts and waking an idle UI Logical cancellation is immediate UI state/generation invalidation. It **does not** promise the remote server stopped processing a request or that a blocked transport was physically interrupted. The curl progress callback checks atomic stop/generation flags and returns an abort request when curl invokes it. This is cooperative cancellation, not forced thread cancellation. A replacement request can occupy the single pending slot until the old transport returns. The curl adapter permits HTTPS only, verifies TLS peer/host, follows at most three HTTPS redirects, uses a 2000 ms connection timeout and an 8000 ms total transfer timeout, and stops at the 8192-byte body limit. HTTP non-2xx outcomes are failures. It sets `CURLOPT_NOSIGNAL=1` for its pthread and refuses curl builds without TLS and asynchronous DNS: synchronous DNS with NOSIGNAL cannot honor timeouts during name resolution. These are configured transport limits, not a hard real-time shutdown deadline: resolver/backend cleanup and OS scheduling can add latency. Curl cancellation need not run at the instant a DNS/connect operation is blocked. No real network latency, TLS handshake or remote HTTP behavior is claimed tested by the offline suite. The callback-main host can enter its normal `waitevent` idle mode. A published completion pushes an SDL user event; the next UI frame drains the mailbox and renders the result. No event watch/filter renders, applies state or calls CUI. SDL documents `SDL_PushEvent` as thread-safe, but it can fail if filtered or its queue is full. This host installs no filter and leaves the registered event enabled. On a failed push, the worker retries twice after condition-variable waits of 10 ms and 20 ms (three total attempts). Shutdown interrupts these waits; this adds no UI polling, heartbeat or extra thread. Failed attempts are counted by `af_worker_wake_failures`. A transient failure can therefore recover without user input; the offline SDL test injects exactly this case while Core is idle. The delays are configured waits, not a wall-clock scheduling guarantee. If all three attempts fail, the completion remains queued for the next UI event and drain. **There is no unconditional idle-wake guarantee after persistent SDL rejection.** The UI cannot inspect failure counters while asleep, and this sample has no independent fallback timer. A host that adds filters must preserve the completion event. Queue-full traffic provides other events to wake the loop, but a permanently rejecting filter or failed SDL event subsystem cannot be bypassed by retries. Replacing the wake implementation with one that silently drops events violates the host's notification contract. Authoritative behavior references: [SDL_PushEvent](https://wiki.libsdl.org/SDL3/SDL_PushEvent), [CURLOPT_NOSIGNAL](https://curl.se/libcurl/c/CURLOPT_NOSIGNAL.html), [CURLOPT_TIMEOUT_MS](https://curl.se/libcurl/c/CURLOPT_TIMEOUT_MS.html), and the installed 8.22.0 `CURLOPT_XFERINFOFUNCTION(3)` manual. Curl/SDL calls are confined to their documented roles; no new Core dependency is introduced. ## Offline evidence and limits - `async_fetch_worker`: blocked injected transport proves enqueue returns before completion; caller URL mutation leaves worker bytes intact; loading suppresses duplicates; injected failure/retry gets fresh generations; UI state stays unchanged until drain; wrong-thread apply/start reject. Tests logical cancel with a transport that ignores it, cooperative cancel, stale/duplicate/reversed completion application, pending jobs, full mailbox shutdown, bounded results, wake failures and joining an active transport before freeing userdata. - `async_fetch_curl_offline`: exercises the real write callback with binary data, full body/overflow rejection, progress cancellation and cancellation before `curl_easy_perform`. It performs no DNS lookup or network I/O. Curl builds without required features return skip 77; live host initialization also refuses them. Compilation is not a real HTTPS integration claim. - `async_fetch_sdl`: actual CUI button pointer activation starts the injected worker; a loading frame reaches Core idle before completion is released; the real SDL user event wakes the callback runner and the UI applies/renders completion. Saves `async-fetch-smoke.bmp` and checks visible text pixels. - `async_fetch_sdl_wake_retry`: suppresses the first notification attempt, then verifies retry wakes the idle actual SDL runner, applies the retained result on the UI thread and reports exactly one failed/two total wake attempts. - `async_fetch_sdl_pending_shutdown`: closes the actual host while its injected transport is blocked, then verifies cancellation/worker return before host teardown. All native tests use private Xvfb through the repository wrapper. These tests are Linux software/SDL evidence. They do not cover macOS modal loops, Windows, GPU hardware, actual network servers, every SDL filter failure, or arbitrary third-party transports that ignore both cancellation and finite timeouts. Such a transport can delay join indefinitely; it violates the injected transport contract and is not made safe by this example. ## Dependency and license notes No third-party source/binaries are vendored here. Example code uses the repository MIT license. SDL 3.4.18 uses the zlib license (installed `/usr/share/licenses/sdl3/LICENSE`); libcurl 8.22.0 uses the curl license (`/usr/share/licenses/curl/COPYING`). The tested libc/pthreads implementation is glibc 2.44 (LGPL-2.1-or-later); existing CUI/font stack licenses still apply. Redistributing linked applications requires retaining applicable dependency notices and satisfying their licenses; exact static vs dynamic dependencies come from your selected build. This directory does not change repository license metadata or package the optional executable into SDKs. --- ## Avatar activation owner Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/avatar_events/README.md # Avatar activation owner `main.c` is a complete portable model example using `cui_avatar_events`. Its profile-picker owner opens a profile once from the typed callback, copies pointer-free evidence and requests deferred dismissal. The host applies that request after frame completion; the next submission omits the picker. Returned counts are inspected without repeating the action. No callback frees its own userdata or destroys the context. This executable has no native window or renderer. It supplies a synthetic Core accessibility action after semantic registration, rather than claiming a real screen-reader or browser test. To use the same owner with a native host, submit `draw_picker` inside the host's normal frame, consume the returned draw list with its renderer, then apply `dismiss_pending`. The existing native starter documents host/font setup; no new host abstraction or dependency is introduced here. Build the current library, then compile against that library (distribution and SDK regeneration is owned by the integrator): ```sh cmake -S . -B /tmp/cui-avatar-example -G Ninja -DCUI_BUILD_NATIVE=OFF cmake --build /tmp/cui-avatar-example --target cui cc -std=c11 -Wall -Wextra -Wpedantic -Werror -I include \ examples/avatar_events/main.c /tmp/cui-avatar-example/libcui.a -lm \ -o /tmp/cui-avatar-example/avatar_owner /tmp/cui-avatar-example/avatar_owner ``` The executable is portable-only and opens no desktop windows. Registered native checks must still use `python scripts/test_local.py --build-dir `. This example uses initials; photo/icon resources in a real application must remain alive until the renderer consumes their borrowed draw data. --- ## Native control events: a small settings panel Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/control_events/README.md # Native control events: a small settings panel This standalone example uses the shipped `cui_button_events` and `cui_checkbox_events` APIs. It does not use proposed Styled Switch/Toggle event APIs or a new binding facade. All state, CUI calls and callbacks stay on the UI thread of the existing `cui_sdl3_run` callback runner. The panel demonstrates: - **Enable notifications** requests a new checkbox value. The application owner rejects it while **Allow setting changes** is unchecked and accepts it when that permission is checked. Rejection is an owner policy, not an event unconsume/propagation operation. - **Apply settings** increments one application counter from its activation callback. Returned frame counts are inspected and displayed; they do not perform the action again. - **Close settings panel** only records a deferred request. After `cui_end_frame` and rendering consume the frame's borrowed draw data, the host applies that request. The next submission omits the panel. **Reopen settings** restores it. No callback destroys the context, font, host or its own userdata. ## Copy and run Tested host: Linux x86-64, GCC 16.2.1, SDL 3.4.18, installed FreeType/HarfBuzz and the repository's native text/Core libraries. The optional standalone CMake file currently accepts Linux only. No new dependencies or downloads are introduced. SDL's installed version is checked exactly, matching the async-fetch example convention. An explicit `CE_SDL_VERSION` override selects another exact installed version and requires revalidation; it does not establish support for it. From the repository root: ```sh pkg-config --modversion sdl3 cmake -S examples/control_events -B build/control-events -G Ninja \ -DCMAKE_BUILD_TYPE=Debug cmake --build build/control-events \ --target cui_control_events test_control_events_app python scripts/test_local.py --build-dir build/control-events -- \ -R '^control_events_example_' ``` The smoke test uses the discovered `CUI_TEST_FONT`. Override it with `-DCE_TEST_FONT=/absolute/path/to/NotoSans-Regular.ttf` when configuring. If no font is found, the SDL smoke is not registered; inspect the test list rather than claiming it ran. The model test needs no font or window. To explicitly open the interactive example yourself: ```sh build/control-events/cui_control_events \ --font /absolute/path/to/NotoSans-Regular.ttf ``` Only this explicit interactive command opens a normal window. Automated native checks use the repository wrapper's private Xvfb display. There is no desktop fallback. Close the window normally to quit. No network or asynchronous job is involved in this example. ## Callback ownership and timing The actual setting handler in [app.c](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/control_events/app.c) is deliberately small: ```c void ce_setting_request(void *user, const cui_component_check_request *request) { ce_app *a = user; ++a->requests; a->last_request = *request; /* Pointer-free payload: safe owned copy. */ if (a->allow_toggle) a->setting = request->requested; else ++a->rejected; } ``` The Checkbox call supplies a value snapshot rather than a mutable value pointer: ```c result.setting = cui_checkbox_events( ui, CE_SETTING, theme, cui_string("Enable notifications"), a->setting, (cui_checkbox_options){0}, (cui_component_check_handler){ce_setting_request, a}); ``` The control retains its entry snapshot for that call's paint/semantics and all requests. An accepted owner assignment appears in that control on the next submission; the host invalidates after owner changes to submit it. A request callback's return value cannot reject anything: its type returns void. Rejection means the owner leaves its value unchanged. A missing handler is read-only. Handlers and userdata are borrowed for the component call. This sample's app object and Button states outlive every frame and are released only after the runner returns through its quit callback. Request/activation metadata can be copied by value. This sample copies it for inspection; it does not retain a borrowed callback pointer. Frame/index identity is context-local, presence flags must be honored, and a source field is not proof of arbitrary platform input. Result `activation_count` and `request_count` describe that invocation. They are not a queue, accepted-owner count or command to dispatch again. `valid` and `submitted` do not mean an owner accepted a value or that later rendering cannot fail. Legacy Checkbox change fields are zero, so there is no competing handler. The Button likewise uses one side-effect callback path. Do not attach a second legacy handler and then accidentally repeat the action from its result. [main.c](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/control_events/main.c) applies `ce_finish_frame` only after rendering. Omission preserves the app-owned setting for reopening; it is not context destruction or a promise that active callbacks can free resources. Window shutdown remains the runner's normal quit path. This is an example of safe application sequencing, not a new runtime guard against callback reentrancy/destruction. ## Offline verification and scope `control_events_example_model` tests the actual owner callbacks with rejected and accepted requests, copied request independence, activation and deferred close/reopen. It is not evidence of dispatch ordering by itself. `control_events_example_sdl` uses the real scene, native font and SDL renderer. It pushes SDL mouse motion/down/up events to exercise both checkboxes and Button, then explicitly focuses the setting and pushes SDL Space down/up events. The source Checkbox intentionally does not take pointer focus, so explicit focus is part of this deterministic keyboard fixture. The test verifies pointer/keyboard metadata with frame/index/activation evidence, requested-versus-owner values, exact action counts, an intervening frame with zero counts/no duplicate effects, and absence of omitted controls from the following semantic tree. It captures `control-events.bmp` while the actual settings panel is visible and checks ink pixels. Only successful completed rendering precedes omission. These tests establish the listed Linux native paths. They do not establish all component event families, bindings, capture/bubble routing, arbitrary teardown, full accessibility, macOS/Windows live resize or GPU hardware acceptance. The example source is MIT under the repository license; existing SDL/font-stack licenses and pinned dependency notices remain applicable. It vendors nothing. --- ## Application-owned loading semantics and Alert Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/loading_region/README.md # Application-owned loading semantics and Alert This compiling C11 example uses existing CUI APIs. It opens no window and emits Core snapshots as JSON. It demonstrates one meaningful Records region, one polite status while loading/completing, three decorative Skeletons, and a failed operation with a rich Alert, Retry button and controlled Dismiss button. The application owns the operation state; the Skeleton animation is not the operation. `scene.c` is the composition to adapt. The region's `cui_semantic_details.busy` reflects the operation state. Skeletons add no focus stops or semantic nodes. Alert's explicit accessible name summarizes its custom body; arbitrary painted children are not automatically concatenated into that name. Retry is an ordinary button; the application must start its real operation when `retries` changes. Dismissing the failure Alert does not claim the operation succeeded. Stable IDs preserve identity across UI frames. Do not change names every animation tick to force announcements. A visual host must submit the draw list, retain renderer resources as usual, schedule the earliest successful motion result's `next_wake_seconds`, and poll real application completion on the owner thread. This no-window snapshot driver supplies deterministic times instead. It does not run a service or render a complete application. `cui_skeleton_ex` is paint-only; use the existing application region/status pattern when loading has meaning to users. ## Build and focused validation No dependency is installed or downloaded. Use a dedicated build directory; root CMake files are unchanged. The external harness reuses canonical sources but builds only explicitly requested targets. ```sh cmake -S examples/loading_region -B "$HOME/.cache/cui-validation/loading-region" -G Ninja cmake --build "$HOME/.cache/cui-validation/loading-region" --target loading_region test_alert_loading_semantics python scripts/test_local.py --build-dir "$HOME/.cache/cui-validation/loading-region" -R '^alert_loading_semantics$' "$HOME/.cache/cui-validation/loading-region/loading_region" ``` On Linux, the optional native fixture uses only the existing checksum-verified AccessKit cache and installed AT-SPI packages. It creates no SDL window. Run it through the wrapper and existing private DBus/Xvfb runner; never use the desktop accessibility bus. It does not launch a screen reader. ```sh cmake -S examples/loading_region -B "$HOME/.cache/cui-validation/loading-region" -G Ninja -DLOADING_REGION_ACCESSKIT=ON cmake --build "$HOME/.cache/cui-validation/loading-region" --target test_loading_native python scripts/test_local.py --build-dir "$HOME/.cache/cui-validation/loading-region" -R '^alert_loading_(semantics|native)$' -V ``` The browser fixture needs the already installed Playwright 1.58.0 and Chromium 1208 used by repository tests. No package/browser installation occurs. It feeds actual compiled Core snapshots into the production gallery's unchanged `syncSemantics` function, executing the DOM adapter in headless Chromium. This is a transport fixture, not a WASM execution or live-AT test. ```sh python tests/web/test_alert_loading_dom.py --example "$HOME/.cache/cui-validation/loading-region/loading_region" ``` ## Evidence and boundaries Verified locally with strict C11 warnings, `-Werror`, assertions enabled and clang-format 23.1.2: Core fixture and real native fixture passed 2/2 through the private display wrapper, including a separate ASan/UBSan build; headless Chromium DOM fixture passed. The Core fixture checks decorative omission, busy/name transitions, stable parent relationships, nonfocusable Alert/status roots, independent action descendants, hidden subtree omission and reinsertion. The DOM fixture checks the same actual snapshot transitions, stable element identity and removal/recreation. The native fixture captures real `object:announcement` events on a private bus: Alert insertion and changed name use assertive politeness 2; hiding emits no repeat; reinsertion announces again; completion status uses polite politeness 1. Repeated unchanged owner polls produce no duplicate tested messages. It queries busy true/false and the actual platform role. The pinned adapter maps AccessKit Alert to AT-SPI **Notification**, while AlertDialog maps to AT-SPI Alert. This is upstream adapter behavior, not a component role change. The installed AT-SPI client reports cache-signature warnings; direct role/state queries and event payload assertions pass despite those warnings. Source evidence: the checksum-verified AccessKit C 0.23.0 lockfile selects `accesskit_atspi_common` 0.20.0 and `accesskit_unix` 0.23.0. The former's `adapter.rs:add_node` emits named live-node announcements, and `node.rs:notify_property_changes` emits them on name changes; `node.rs:role` provides the Notification mapping. Unix `atspi/bus.rs` serializes the event with message and politeness. The fixture uses those actual linked implementations; it does not inject fake announcement events or require a new Core queue. No audible delivery, interruption/coalescing policy or screen-reader preference behavior is established. Browser role/name/busy DOM exposure does not prove that initial insertion or an aria-label mutation will be spoken. The optional native adapter remains Linux-only; macOS and Windows announcement delivery is deferred. These results justify only the tested transport behavior, not full accessible announcement parity or a new loading-semantics feature on Skeleton. --- ## CUI native source bundle Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/native_bundle/README.md # CUI native source bundle From the extracted bundle directory: ```sh make ./build/native_starter ``` The consumer build needs a C11 compiler (`cc`), GNU make, `ar`, and `pkg-config` with SDL3 >= 3.2, FreeType, and HarfBuzz development packages. It needs no Python, CMake, Rust, network access, or installed CUI library. Python and CMake belong to the repository's producer and validation workflow. Check system prerequisites separately from bundle completeness: ```sh pkg-config --atleast-version=3.2 sdl3 pkg-config --modversion sdl3 freetype2 harfbuzz ``` SDL2 cannot replace SDL3. Install development packages through your system's package manager or explicitly build upstream releases before running `make`. The build performs no downloads. These are dynamically linked system libraries; shipping this source bundle is separate from deploying a binary and its libraries. Running the app requires an X11 display session. Automated Linux validation needs Xvfb (`xvfb-run`) and `xauth`, in addition to the build prerequisites. Each CUI source compiles separately into `build/vendor/`, then into static CUI archives. Editing `app.c` rebuilds `build/app.o` and relinks the executable; ordinary app edits leave CUI objects alone. `.d` files track header dependencies. Use `make CC=clang` to select another compiler in a fresh extraction. If changing compiler or flags after building, use a fresh extraction or remove your build directory explicitly. `sources.mk` is generated from the repository's authoritative source metadata. No implementation macros are required in consumer code. The starter loads bundled Inter 4.1 Regular and Bold before creating its layout. Unmodified official static OTF files and their SIL Open Font License are in `assets/fonts/Inter-Regular.otf`, `assets/fonts/Inter-Bold.otf`, and `assets/fonts/LICENSE.txt`. Keep the license when redistributing the fonts. Defaults resolve relative to the executable (`build/../assets/fonts`), so launching from another working directory works. Keep that directory relationship when moving the app. Override each face explicitly if needed: ```sh ./build/native_starter --font /path/regular.otf --bold-font /path/bold.otf ./build/native_starter --frames 3 --capture frame.bmp ``` Only regular (400) and bold (700) are bundled; CUI does not synthesize other weights or italics. Register additional matching faces before using other styles; an unavailable style falls back to regular. Inter's script coverage is finite: this pair supplies neither universal Unicode coverage nor automatic font fallback. The archive retains font provenance and SHA-256 pins in `assets/fonts/manifest.json`, upstream dependency records in `upstream-dependencies.json`, and checksums for every payload file in `bundle-manifest.json` (excluding that checksum manifest itself). `--frames` accepts positive decimal integers through `UINT_MAX`; only successful renders count. A bounded run fails if the window closes early, layout/rendering fails, a font is missing, or capture fails. `--capture` requires `--frames` and captures the final frame before presentation. Capture paths are relative to the working directory. Without `--frames`, close the window to exit. The button toggles a greeting and demonstrates ordinary pointer/keyboard component interaction. Linux X11 is the supported validated native target. Other platforms and display servers are unverified. Native automated tests must use the repository's invisible Xvfb wrapper (`python scripts/test_local.py --build-dir build`), never the desktop display. Browser tests run headless; virtual-display results do not establish GPU hardware coverage. The default is the existing SDL3 `SDL_Renderer` adapter. SDL chooses an available driver; distribution tests force its software driver under Xvfb. This does not require Sokol, Vulkan, or CUI's separate SDL_GPU adapter. The dependency map is: | Layer | Dependencies and purpose | | --- | --- | | Portable CUI | Clay layout, NanoSVG SVG rasterization, generated icon/theme tables, generated Unicode properties | | SDL3 adapter | SDL3 host window, input, clipboard, cursors, and renderer | | Native text adapter | FreeType font loading/rasterization and HarfBuzz shaping | | Bidirectional text | Vendored SheenBidi, compiled as C with the bundle | | Starter assets | Inter 4.1 static Regular/Bold OTF files, SIL Open Font License | Sokol, SDL_GPU, the Rust regex provider, and native accessibility integrations are outside the default build. Public headers may declare optional interfaces; their presence does not mean those optional implementations are linked. All 78 component manifest entries are retained in `component-manifest.json`, including their incomplete behavior and validation status. Application layout and component calls use public CUI APIs. The starter uses SDL's executable-path helper only to locate its bundled assets. Public CUI interfaces contain no SDL or Clay types. This bundle demonstrates a minimal native integration; it does not claim complete platform or component parity. ## Two application files `main.c` owns fonts, the SDL3 host, event polling, frame boundaries, rendering and cleanup. `app.c` contains `app_frame` and only uses portable public CUI APIs. The host owns the `clicked` value across frames and passes its address into the application submission function. Edit the labels, root box and button in `app.c` then run `make` again. The button toggles the greeting; keyboard Tab and Enter exercise the same component interaction. No implementation macro is needed. To rename the executable or add ordinary C source files: ```sh make APP_SOURCES="main.c app.c" TARGET=build/my_app ./build/my_app ``` `APP_SOURCES` is a space-separated list of relative `.c` paths (subdirectories are supported; filenames with spaces are unsupported). Include the host and all application translation units, but leave vendor sources in generated `sources.mk`. `TARGET` names the linked executable. Keep it directly in `build/` to preserve the default executable-relative font paths; elsewhere, pass explicit `--font` and `--bold-font` paths. A new source set or target links from the selected objects; unchanged vendor objects are reused. Changing compiler or flags requires a fresh build directory. External dependency requirements remain unchanged. ## Mail layout acceptance fixture ```sh make APP_SOURCES="main.c mail.c" TARGET=build/mail_demo ./build/mail_demo ``` `mail.c` exercises three independently scrollable panes, repeated scoped avatars and tags, long clipped subjects, fixed trailing star actions, message selection and a Compose/Discard preview path. The 720×420 host is a desktop fixture; narrower windows clip panes rather than provide responsive navigation. Compose has no editor, storage or delivery. State is process-local. This fixture does not claim a complete mail client or complete component parity. For geometry inspection use `--debug-layout text` or `--debug-layout json`. The first completed frame is exported once to stdout; JSON can be redirected to an application-owned file. Capture remains independent. Core/component reported failures go to stderr with subsystem, operation, bounded message, ID, frame and budget counters; font/SDL initialization and renderer failures retain their own host messages. The exporter covers box nodes rather than individual text nodes. --- ## Native CUI starter Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/native_starter/README.md # Native CUI starter A small C11 app with Home, Projects and Settings, real navigation callbacks, editable local settings, and a demo account menu **at the sidebar bottom**. Follow [Build your first native CUI app](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NATIVE_APP_STARTER.md) for prerequisites, installation, CMake, Make and direct compiler commands. The build consumes an installed `cui-sdl3` pkg-config package; set `PKG_CONFIG_PATH` to its prefix. Copy this folder to start a separate project. ![Actual SDL3 Home window](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/native_starter/screenshots/home.png) - `app.h` defines persistent state, callbacks and stable IDs. - `app.c` submits components and applies actions. - `main.c` manages the native font, window, input, clipboard and render loop. - `test_app.c` verifies component behavior without a native window. Sign-in/out is local demonstration state; no authentication service is connected. On macOS the CMake starter produces `native_starter.app`, including the pinned Inter fonts and their license. Finder launches discover the bundled font; `--font` still overrides it. Set `CUI_MACOS_BUNDLE=OFF` for a plain executable. A copied starter must set `-DCUI_MACOS_BUNDLE_HELPER=/path/to/CUIMacOSBundle.cmake` and `-DCUI_MACOS_FONT_DIR=/path/to/third_party/inter` from the same CUI checkout. Native macOS installs deploy linked dylibs through CMake BundleUtilities by default; set `CUI_MACOS_DEPLOY_DEPENDENCIES=OFF` to manage deployment yourself. Cross builds require a Darwin toolchain, SDK and target dependencies. They package resources without executing target binaries. Dependency deployment is disabled: stage target dylibs, repair install names, and sign/notarize on macOS separately. Keep `CUISignMacOS.cmake` beside the bundle helper when copying the helpers; native dependency deployment applies ad-hoc development signatures after fixing library paths. --- ## Optional macOS Speech recognizer host Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/speech_macos_recognizer/README.md # Optional macOS Speech recognizer host The bounded portable host and private Objective-C transport are implemented. Actual Apple CI compiled and linked both Debug and Release builds and passed all seven injected fixtures in each. Permission dialogs, microphone capture and live on-device recognition remain unverified. This is not a native-recognition support or full Speech parity claim. See [the design and native validation plan](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SPEECH_MACOS_RECOGNIZER.md). `host.h` exposes only C11/CUI types. `host.c` contains the bounded callback pool, permission/session state and transcript normalization. `host_lock.c` privately supplies POSIX mutexes for Linux/macOS. No Core/public framework API changes, recognizer engine downloads, networking, microphone capture or OS permission requests occur in these portable fixtures. ## Contract Create the host with a service vtable, private mutex operations and an optional nonblocking wake. Constructor/query/refresh/available never request permission. `speech_recognizer_host_prepare` is an **explicit user action** that may request Speech consent in a native service; it checks the usage description and allows only one pending request. Microphone permission remains a separate application/SDL-input concern. Native service operations must enforce main/UI thread ownership; generic C11 code assumes one owner for host operations. The service must report support, usage-description presence, locale validity, on-device capability/availability and authorization. The host always passes `on_device=true` to start. No network fallback is accepted. `available` uses the last refreshed service snapshot plus pending-permission and pool capacity. Refresh on the UI timer; start refreshes again. Fixed format is 16000 Hz mono PCM16: service-format mismatch makes available false/start UNSUPPORTED. Mutating the returned provider's format is unsupported; start also checks the CUI state's actual format and returns INVALID if it was changed, even if the independent host's cached available predicate remained true. No conversion is hidden here. Each service operation gets a borrowed endpoint. Retain it before an asynchronous callback stores it; release the lease when its callback/block is destroyed, even if it never fires. `close` releases each opaque service token once. An already retained callback lease may survive close and host destruction. It must never use an endpoint after releasing its own final lease. Endpoints contain no host, CUI sink or independent wake-userdata pointer capture. The fixed allocation has four endpoint slots, each with eight event slots and at most 4095 UTF-8 payload bytes. Oversized/malformed text is converted to a queued terminal error; callback return means the event/error was queued, not that recognition succeeded. Queue overflow and wake failure use a separate terminal latch. Active operations, pending permission and retired callbacks share the four slots. Retired slots are never reused until all leases release; if a service never releases callbacks, capacity stays exhausted rather than allocating replacements or recycling dangling pointers. Closed callbacks are rejected without touching a sink or wake userdata. Detach waits out an existing short wake under the mailbox mutex. Wake must not block, reenter the host, or wait for owner/UI dispatch. Poll the recognizer and optional input host on the owner thread, then call `cui_speech_pump` with monotonic time, including during STOPPING. UI polling has an explicit event budget. It reports READY after task creation, not from an OS callback. Appends copy borrowed PCM in at most 256-sample chunks before the service returns. The service must copy/consume its borrowed span synchronously. Finish sends end-audio once; CUI timeout/cancel/final invokes provider close. Dispose/cancel CUI before destroying its provider host. Host destruction rejects an active CUI session and detaches pending authorization safely. Normalization handles cumulative hypothesis replacement, metadata-ended utterance resets using Unicode codepoint comparison, English punctuation and CJK spacing. Final text commits once; an empty final clears an old hypothesis. Text plus error preserves text as hypothesis and fails, even when marked final. The private Apple no-speech error exception is deliberately unsupported until separate native evidence exists. OS-specific transcription variations remain unverified; these fixtures do not establish full upstream utterance parity. Permission completion failures are observable via `speech_recognizer_host_last_error`; synchronous prepare failures are returned by prepare. The caller must not treat denied/overflow/failure as successful consent. Permission authorization can change later; refresh plus polling fails an active session on revoked authorization/service availability without preventing cancellation or finish cleanup. ## Independent offline validation Use an existing compiler/CMake/POSIX thread implementation; no install or fetch: ```sh cmake -S examples/speech_macos_recognizer -B "$HOME/.cache/cui-validation/speech-recognizer" -G Ninja cmake --build "$HOME/.cache/cui-validation/speech-recognizer" TMPDIR="$HOME/.cache/cui-validation" python scripts/test_local.py \ --build-dir "$HOME/.cache/cui-validation/speech-recognizer" ``` The standalone build sets `CUI_BUILD_NATIVE=OFF` for the wrapper's portable-only policy and compiles only host/base/fixture sources. Linux still uses private Xvfb; no desktop fallback. Six CTest cases cover permission/status gating, transcript revisions/resets/UTF-8, lifecycle/format/PCM copying, queue/text/pool capacity and wake failures, two concurrent result producers with owner-thread CUI delivery, and callbacks after actual host/wake-userdata free. Pending permission destruction and permanently retained leases are injected explicitly. Verified on Linux/GCC 16.2 in strict C11 with `-Wall -Wextra -Wpedantic -Werror`: 6/6 wrapper tests pass. The same six tests pass with AddressSanitizer and UndefinedBehaviorSanitizer, including late leases and final pool reclamation. No full repository/package/skill tests were run for this isolated optional example; integration checks belong to the integrator. ## Native service work remaining Private Objective-C ARC/blocks transport links Foundation, Speech and AVFoundation with deployment target macOS 13.0+. [Apple CI](https://github.com/mattmezza/cui/actions/runs/39396253418) passed Debug and Release, seven fixtures each, at source `4ece99ec`. Linux fixtures independently passed all six portable cases during integration. Real microphone consent/capture, Speech authorization, locale/model availability, on-device recognition and real stop/no-speech behavior remain explicit manual validation. None is executed automatically or inferred from portable tests. ## Private Objective-C transport and injected validation `host_macos.h` adds only opaque C factory/service types. `host_macos.m` keeps Foundation/Speech/AVFoundation objects and ARC callback blocks private. The native factory does not request authorization or open a microphone. Explicit Speech preparation validates the application's nonempty `NSSpeechRecognitionUsageDescription`; recognition rechecks authorization, locale/on-device availability and always configures on-device-only requests, partial results and punctuation. No microphone authorization API is called. `host_macos_private.h` is an ObjC-only test seam. The native service fixture injects Objective-C fake request/task/backend objects into the **actual transport**. It is intended to observe real transport property setters, copied AVAudioPCMBuffer samples, bounded UTF-8 conversion, oversized results, result-plus-error precedence, cancel/end-audio counts and blocks retained beyond host/service shutdown. It does not instantiate SFSpeechRecognizer, request OS permission, create a real recognition task or touch a microphone. The real Apple backend is compiled and linked in the same target but not executed. On macOS the same standalone CMake commands add a `speech_recognizer_macos` library and `test_macos` target with ARC/blocks, deployment target 13.0 and strict warnings. `speech_recognizer_macos_injected` is the seventh CTest case. CI needs the installed Xcode macOS SDK and system frameworks; no new downloaded dependency. Run through `scripts/test_local.py` using the portable-only cache already set by this project. The independent example currently supplies a POSIX mutex and explicitly rejects Windows configuration. The Apple run used Xcode 26.6, macOS SDK 26.5 and Apple Clang 21 with a 13.0 deployment target. It compiled the real backend but executed only injected service objects. This establishes native compilation, linkage and injected transport behavior; it does not establish real permission, microphone or recognition operation. The integration's six portable Release cases passed through the private-display wrapper as well. --- ## Optional SDL Speech input host Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/speech_sdl_input/README.md # Optional SDL Speech input host This independent application-host example feeds existing `cui_speech_input`. It is not a recognizer or a Core/Base API change. Linux still needs an application recognizer. No automated test opens an audio device. ## Bounded ownership decision Use a fixed-capacity single-producer/single-consumer PCM ring, not a timer-only SDL pull queue. Device callbacks are serialized producers; the UI thread polls copied samples into `cui_speech_report_audio`, then calls `cui_speech_pump`. C11 acquire/release indices publish complete PCM frames. Only the callback writes the producer index; only UI poll writes the consumer index. The callback never enters CUI, calls lifecycle methods, or retains the sink. A terminal atomic error is separate from the ring so overflow can always be reported. The fixed bound applies to host-owned PCM, not all SDL/OS capture buffers. SDL's private callback drains converted PCM into a bounded scratch array. If a batch exceeds available ring space it marks overflow; subsequent callbacks clear SDL pending data until owner-thread shutdown. SDL/driver scheduling and internal buffers are outside this example's memory bound. UI starvation causes a visible terminal failure rather than silent speech loss or unbounded host queue growth. The host must poll while a session is active and enforce CUI's STOPPING deadline even without a wake. This example does not promise hard real-time behavior or a bound on every allocation in SDL/the OS. Optional callback wake is a thread-safe, nonblocking notification only. A false return marks input failure; the UI's active-session timer must still poll to observe wake failure. Wakes can be redundant and late; they carry no sink/state pointer. No wake callback may synchronously poll or close the host. The example uses no wake coalescing, avoiding a missed-wake acknowledgement race. ## Lifecycle and injection contract The host allocation and provider live on one owner/UI thread. Device operations are injected behind a portable C11 header. `open` receives requested signed interleaved PCM16 format, a sample/error delivery callback and user pointer. It must serialize callbacks, including any callbacks during `open`. On failure, `open` releases all partial resources and returns no token. On success it returns exactly one token. The provider's close invalidates its accepting flag, closes that token once, and waits for callbacks to quiesce before resetting ring indices. It must not wait for callbacks that are waiting for UI dispatch. The host retains a CUI sink only until provider close. CUI closes capture on stop, cancel, startup failure and dispose. Before freeing the host, first cancel/dispose the CUI state so no provider callback can subsequently use it. Destroying a still-active host is rejected. Closing the device quiesces old callbacks before a new session can reuse the host; generation-tagged CUI sinks also reject previous-session reports while the state allocation remains alive. The raw sink does not permit reporting after freeing state/workspace. Owner polling snapshots whole PCM frames into local scratch before reporting. On ring overflow/device error/wake failure it reports a terminal error and lets `cui_speech_pump` close capture/recognition. On CUI queue capacity failure, stop polling and let pump surface its existing capacity terminal error. Never claim that a dropped batch was recognized. Poll is forbidden during provider callbacks and must not run from event/wake/audio callbacks. ## Validation boundary Standalone external CMake builds only existing CUI speech base code plus this host fixture and optional SDL source, with strict warnings. Injected devices check startup failure, synchronous delivery, PCM ordering, ring overflow, error forwarding, wake failure, stop/cancel cleanup, restart rejection of stale reports and shutdown rejection. Tests use deterministic synthetic PCM and no SDL initialization/device open. A separate unbound SDL stream proves conversion. Run CTest through a local private-Xvfb wrapper; native desktop windows are never opened. Real capture is a separate explicit user action, never an automated fixture. Manual OS consent, disconnect/reconnect, audio hardware and recognizer behavior remain unvalidated. macOS/Windows compilation is deferred until those platforms are exercised. ## Implemented independent slice The signed design checkpoint precedes implementation. `host.h` exposes only portable application-host types; `host.c` depends on existing CUI speech base APIs and standard C11, and `host_sdl.c` keeps all SDL types private. Creation allocates one fixed PCM ring and rejects platforms without lock-free atomic indices/error/acceptance flags. Capacity is **samples**, not frames; leave room for the recognizer's channel count. One additional sample slot disambiguates empty/full. No per-batch host allocation occurs. The private SDL callback accepts at most 8192 converted bytes per initial callback snapshot and uses 256-sample stack chunks. This explicit guard can fail high-rate/high-channel streams even when the ring is large enough. The usual 16 kHz mono speech format is the intended starting point, not a claim that every format accepted by CUI works with every device. Terminal callbacks clear remaining SDL data. The first terminal error wins, even if wake also fails. Provider close detaches SDL's put callback under the stream lock (which waits for an existing callback), then destroys the stream/device. See [SDL's callback lock contract](https://wiki.libsdl.org/SDL3/SDL_SetAudioStreamPutCallback). No device opens in the factory or host constructor. Build and run only these independent fixtures from the repository root: ```sh cmake -S examples/speech_sdl_input -B /tmp/cui-speech-input-build -G Ninja cmake --build /tmp/cui-speech-input-build python scripts/test_local.py --build-dir /tmp/cui-speech-input-build ``` The build uses the installed SDL >= 3.2; it performs no download/install. CUI's existing optional fetched SDL pin is documented in the design proposal; this standalone build does not fetch dependencies. Verified here with SDL 3.4.18, GCC 16.2, strict C11 and `-Wall -Wextra -Wpedantic -Werror`. Four private-Xvfb CTest fixtures pass on Linux: - Injected lifecycle: synchronous start delivery, ring wrap/order, whole-frame polling, malformed frames, full ring, device/wake errors, startup cleanup, CUI queue capacity failure, stop timeout, cancel/restart stale sinks and exactly-once close. Active-host destruction is rejected. - Unbound SDL stream conversion: exact PCM identity, stereo downmix/resampling, counts and signal tolerance; no initialized audio subsystem. - Injected SDL device operations: every init/open/resume/device-close operation is intercepted with linker wrapping; real unbound streams exercise the actual SDL callback, terminal drain and detach code. No real device operation runs. - C11 worker producer: 4096 ordered samples traverse a wrapping fixed ring; recognizer delivery occurs on the owner thread; close joins the producer and rejects late delivery before host destruction. The threaded fixture has a 10-second timeout to expose deadlocks. The Linux-only linker-injection/thread fixtures are not registered on other platforms; macOS/Windows compile, permissions and hardware remain deferred. These tests establish neither recognition accuracy nor microphone operation. ## Application integration and manual capture boundary An application supplies a real recognizer, caller-owned CUI state/workspace, and a monotonic UI-loop timer. In the application's explicit audio-enabled path, initialize SDL's audio subsystem before starting Speech; the SDL provider returns UNSUPPORTED if audio is not initialized. Pass `speech_input_host_provider(host)` as the input to `cui_speech_init`, where `host` was created with `speech_input_sdl_device_ops()` and a bounded capacity. Only an explicit user start action should call `cui_speech_start`; that is the point that can open a microphone and trigger OS consent. Construction and availability checks do not establish permission or prompt for it. While active, arrange a short UI timer (for example 10 ms); each tick calls `speech_input_host_poll(host, monotonic_seconds, budget_samples)` followed by `cui_speech_pump(state, monotonic_seconds)`. Budget and CUI workspace must fit the selected format and expected timer latency. Keep pumping during STOPPING. An optional wake posts a nonblocking UI notification and returns its actual success; the timer remains necessary for wake failure and stop deadlines. UI callbacks must schedule later work instead of reentering poll/lifecycle. Shutdown order is: cancel/dispose CUI state, destroy host (must succeed), then terminate the application's SDL audio subsystem. The host must outlive the state's provider callbacks even when inactive. An injected device implementation must uphold serialized delivery and quiescent close just as the SDL backend does. Never invoke a saved delivery callback after close returned; generation checks cannot make a freed host pointer safe. This slice does not wire SDL audio-device-removal events into application UI. The application must handle those events and cancel the affected Speech state; a stream that stops producing samples does not itself prove disconnection. SDL open failures map to INPUT_ERROR because error strings do not supply a portable permission/absent-device code. macOS usage descriptions/consent, Windows privacy settings, Linux audio service/device access, removal recovery, real recording and OS recognition require separate explicit manual validation. --- ## Optional FFmpeg PCM service proof Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/video_audio_ffmpeg/README.md # Optional FFmpeg PCM service proof This standalone example supplies the existing `video_audio_decoder` interface. It decodes real local PCM audio from muxed video, converts to 48 kHz stereo float, and feeds the unchanged threaded controller. It has no SDL transport, speaker output, video rendering, Core integration, playback-rate control or acoustic clock. Build using existing dependencies, from repository root: ```sh cmake -S examples/video_audio_ffmpeg -B build-audio-ffmpeg -G Ninja cmake --build build-audio-ffmpeg python scripts/test_local.py --build-dir build-audio-ffmpeg ``` Repeat in a separate build directory with `-DVIDEO_AUDIO_SANITIZE=ON` for ASan/UBSan. Linux tests always use the private Xvfb wrapper. They generate small local files using the already installed FFmpeg CLI; no devices, network or installation. The fixture CLI must be FFmpeg n9.0.2. The standalone CMake project requires exact pkg-config versions: avformat/avcodec 63.1.102, avutil 61.1.102, swresample 7.1.102. No root build or dependency manifest is changed. ## Contract and limits Create the service, pass `video_ffmpeg_interface(service)` as controller decoder, and destroy the service only **after successful controller destruction/join**. The controller's sole worker owns seek/read and all demux/codec/resampler state. The owner may interrupt concurrently: its monotonic atomic generation ceiling cancels older operations and does not cancel newer work. The service retains no controller/output/UI pointer. Snapshot reads take only a short stats mutex. Only immutable regular local files are admitted. Paths containing colon or line breaks are rejected; FFmpeg permits only the file protocol and Matroska/WebM/WAV demuxers. `stat` preflight is not a sandbox against path replacement. Callers must not modify/replace a file while the service lives. Known common container origin and audio PTS are mandatory, including for WAV; formats lacking them fail. Nonnegative common origins only are supported in this first slice. The admitted codecs are PCM S16LE/S24LE/S32LE/F32LE, mono/stereo, 8–192 kHz; fixtures prove S16LE stereo at 48 kHz and 44.1 kHz. Compressed priming, skip-sample side data, padding, edit-list interpretation, layout/format changes, missing PTS and large discontinuities fail explicitly. This is not general FFmpeg playback. Audio PTS and the container origin are each rescaled using rational arithmetic to the same 48 kHz timeline. `av_rescale_delta` preserves sample continuity across coarse packet timestamps; tolerance is one stream timestamp tick plus one sample. Sub-tick discontinuities cannot be detected reliably. A leading audio offset up to 250 ms produces intentional timeline media zeros: these correctly advance the controller clock when consumed, unlike underrun padding. There is no independent audio-origin reset. Video packets are counted/skipped, not decoded or presented. Seek reopens and replays from the common origin, preserving the resampler phase, then trims normalized PCM before the exact requested output frame. This proves seek content for the supported fixtures. It is deliberately linear work, with a 10-second default timeline cap, not a fast general container seek algorithm. Targets past EOF return EOF without inventing media. Codec EOF is drained first, then SWR NULL-input flush is repeated until empty. Output chunks remain contiguous and finite, with copied storage and no outstanding FFmpeg buffer leases. Default explicit bounds: 8 MiB packet, 8192 input samples/frame, 65536 converted spill frames, 8192 demux packets, 480000 timeline frames and 12000 leading gap frames. Callers may lower these via `video_ffmpeg_limits`. The controller PCM ring is separately bounded and backpressures decoder reads. Probing is configured with a bounded probe-size hint, one-second analysis hint, packet hint and 16 streams. These hints and post-demux packet checks are **not a total FFmpeg heap bound**: FFmpeg may allocate packet/demux state before the service can inspect it. This is not an untrusted-media hardening layer. Cancellation is checked between work steps and through the AVIO interrupt hook. An OS storage read may still block beyond the hook; no bounded wall-clock shutdown is promised. Destroy joins rather than freeing live worker state. No sleeps, mutexes or decoder calls run in an audio callback here; this slice implements no audio callback. The controller mutex remains unsuitable for a hard realtime claim. ## License and evidence Example sources are MIT. `fixtures/dependency-audit.txt` records FFmpeg version, build configuration, license text and all four exact library versions on every fixture run. The tested n9.0.2 shared package enables `--enable-gpl` and `--enable-version3`, so the actual linked package is GPLv3-or-later; it must not be represented as an LGPL-only distributable merely because SWR headers are LGPL. No binary packaging/distribution is introduced by this proof. See [PROOF.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/video_audio_ffmpeg/PROOF.md) for the measured coverage and deferred integration. --- ## Offline native-video audio controller foundation Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/video_audio_host/README.md # Offline native-video audio controller foundation This optional standalone C11 host implements bounded PCM buffering, a worker with injected decoder operations, and a consumption ledger with an injected output lifecycle. It has **no FFmpeg decoder, SDL output, device access, playback UI or Core dependency**. Native VideoPlayer remains silent. The interfaces here are example-local, not installed CUI public APIs. There is no rate conversion, network loader, permission request or new external dependency. The fixed format is interleaved stereo float32 at 48,000 frames/second. Input is already normalized, finite and contiguous in that frame timebase. Decoder DATA must report the exact next source frame and a nonzero count within the supplied capacity. Other sample rates, channels, arbitrary PTS gaps, codec priming and resampler-delay mapping require a future decoder transport; mismatches are rejected, not guessed. At generation creation/seek, position is the requested source-frame target; subsequent advancement requires consumption evidence. ## Consumption contract for review `video_audio_render` copies PCM and pads starvation with explicit zero samples. It assigns every accepted output frame a bounded ledger entry and returns a `{generation, first_sequence, frames}` ticket. A render is **submission**, not presentation or consumption. The transport must not submit a rejected render. A full ledger rejects the whole render and leaves the destination/ticket untouched. It cannot accumulate an unbounded queue while the owner is stalled. `video_audio_consume` accepts an ordered contiguous prefix of outstanding output frames. Partial acknowledgements are supported; duplicate, reordered, excessive and old-generation acknowledgements reject atomically. Consumption of a media entry advances position to that media frame's end. Consumption of a zero-fill entry leaves position unchanged. The transport reports actual consumption, not requested callback bytes, decoded frame count, submitted bytes, or elapsed UI time. Exact accounting is proved for the injected transport; this is not a claim that an existing SDL API exposes exact hardware presentation time. `video_audio_poll` copies a coherent mutex-protected snapshot. Submission and consumption sequences reset per generation; media/silence statistics are lifetime counts. Silence has separate submitted and consumed counters. Source positions, sequence arithmetic and lifetime media/silence counters reject overflow instead of wrapping; rejection statistics saturate. EOF requires decoder EOF plus no queued or unconsumed media. Trailing acknowledged silence cannot move the clock. An output transport can remain active emitting silence after `ended`; the owner must pause/stop it. There is no self-destruction or device lifecycle operation in an output callback. Pause synchronously quiesces output before freezing effective state. Pending output and its ledger are retained for resume, so the transport must resume that same order. Seek synchronously quiesces/discards output, increments generation, clears PCM/ledger, changes target and schedules worker seek. Seek leaves playback paused until explicit play. Late results from the previous worker generation are discarded. Decoder interruption includes a generation ceiling and must be sticky for that generation; a delayed old interrupt must never cancel a newer seek/read. Decoder callbacks never receive or retain the host pointer. All lifecycle commands run on the creating owner thread. PCM render/consumption and snapshot polling may run on other threads while the host remains live. No arbitrary callback runs under the host mutex. Critical sections have configured frame-count bounds but use an ordinary C11 mutex: **hard realtime scheduling or lock-free callbacks are not claimed**. A decoder AGAIN result retries after a 10 ms condition wait; this retry timer is unrelated to media time. The injected output `stop` is the essential lifetime boundary: success proves all entered callbacks have returned and no new callback can enter until `start`. Discarding stop must also release retained host pointers and queued notifications and report final actually consumed frames before returning. `destroy` refuses to free the host when stop fails; callers retain a live host and can retry. After successful quiescence it signals stop, interrupts decoder operations, joins the worker, then frees storage. Never race unrelated public calls with destruction. Decoder operations must cooperate promptly with interruption; a hostile/blocking service that ignores this contract has no bounded shutdown guarantee. A future physical output adapter must separately resolve device-pending frames, latency, pause retention, discard semantics and safe detach. SDL callback demand and `SDL_GetAudioStreamQueued()` are not sufficient proof of actual consumption. No such adapter is implemented or approved by this foundation. Do not wire this to SDL/FFmpeg or the existing video UI until that contract is reviewed. ## Memory and backpressure For capacity C and decode chunk D (1 <= D <= C <= 65,536), allocations are one 2*C float PCM ring, one 2*D float scratch array, C output ledger entries and the fixed host. The PCM ring and ledger are independently capped: at most C decoded media frames plus C submitted output frames. Each ledger entry stores one media frame index and a media/silence tag; its C padding is included via `sizeof`. Allocation occurs only at create. The worker waits when PCM capacity is full; render never waits for decoder data and ledger pressure rejects rather than expands. A capacity of 12,000 represents 250 ms in each queue. The maximum allowed capacity is not a latency recommendation. Decoder/output implementation memory and OS buffers are outside this host-owned bound. ## Reproduce offline tests No package install or download is performed. The project builds only this host and its fixture, without configuring the framework or opening any device/window. On Linux use the repository's invisible-display wrapper even for these tests. ```sh cmake -S examples/video_audio_host -B "$HOME/.cache/cui-validation/video-audio-controller" -G Ninja cmake --build "$HOME/.cache/cui-validation/video-audio-controller" python scripts/test_local.py --build-dir "$HOME/.cache/cui-validation/video-audio-controller" -V ``` For ASan/UBSan, use a separate directory and add `-DVIDEO_AUDIO_SANITIZE=ON` to configure. The standalone project uses strict C11, `-Wall -Wextra -Wpedantic -Werror` and assertions enabled (MSVC: `/W4 /WX`). Six deterministic fixtures cover known signed stereo samples/counts, submission versus consumption, partial acknowledgement, silence starvation, EOF tail, pause/resume pending output, queue/ledger capacity, reordered/duplicate/stale acknowledgements, repeated seek/restart, ring wrap, malformed/nonfinite decoder results, explicit decoder/seek errors, start/stop failure, wrong-owner commands, blocked read and seek cancellation, successful stale decoder data rejection, callback quiescence before free, and a 257-media-frame stream with concurrent decoding/output/polling. No wall time is used to infer playback position. Bounded waits only detect deadlocks/starvation. ## Remaining implementation Common container A/V timestamp normalization, real audio decoding/resampling, video demux scheduling, physical output, physical presentation clock/latency, owner-thread CUI integration, audible pause/seek behavior, device loss, sample rate changes and platform CI remain deferred. Fixed rate 1 is the only intended initial playback mode; there is no rate API here. Tests do not establish sound output or full native VideoPlayer parity. The Linux GCC and Clang native CI jobs build this optional example separately with ASan/UBSan and run all six offline cases through the invisible-display wrapper. Validation of this checkpoint: all six focused CTest cases passed through `scripts/test_local.py` in normal and ASan/UBSan builds on Linux (GCC 16.2.1). clang-format 23.1.2 and diff checks passed. No other platform compile, hardware latency or physical output result is implied. ## Offline mutex observation fixture `bench_mutex.c` is a separate Unix-only fixture; controller code is unchanged. It measures render-plus-consume pairs using CLOCK_MONOTONIC while the decoder worker contends for the same mutex. Configure a Release build, build normally, then run `scripts/test_local.py --build-dir BUILD -R video_audio_mutex_observation -V`. The fixture checks PCM classes and consumption counters but sets no deadline pass threshold. It is registered with the `benchmark` CTest label. It neither opens output nor simulates a physical-device scheduler. One Linux x86_64 / GCC 16.2.1 Release observation (4,000 pairs, C=12,000, 256-frame output blocks; durations in microseconds): | Decoder chunk | p50 | p95 | p99 | Observed max | Pairs above 5.33 ms | | --- | ---: | ---: | ---: | ---: | ---: | | 256 | 6.211 | 19.160 | 31.041 | 427.163 | 0 | | 4,096 | 4.655 | 19.302 | 31.030 | 105.800 | 0 | The tight loop is deliberately not paced at 48 kHz: it consumed 1,017,536 / 998,592 media frames respectively, with 6,464 / 25,408 underrun-padding frames. Counter checks ensure that padding did not advance media time. These are observations, not an absence-of-dropouts claim. All seven CTest cases (six foundation fixtures plus observation) passed in this Release build and a separate ASan/UBSan build. The instrumented probe's observed maxima were 2.134 / 1.913 ms; instrumentation and scheduling differ, so those values are not directly a performance comparison. No hard realtime, hardware-latency or worst-case bound follows from any run. The next real-adapter proposal, including the explicitly named SDL software-mixer clock and its remaining acoustic A/V limits, is in [the design checkpoint](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/NATIVE_VIDEO_AUDIO_PLAN.md). Actual SDL queue-drain/format/quiescence fixtures must pass before that adapter is added. --- ## Optional SDL software-drain output proof Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/video_audio_sdl/README.md # Optional SDL software-drain output proof This standalone transport supplies `video_audio_output` to the unchanged audio controller. It is not hooked to the video UI or FFmpeg service. Its clock is **SDL software-mixer input consumption**, not a DAC, backend-accepted, hardware presentation or acoustic clock. Native video sound support remains unimplemented. ```sh cmake -S examples/video_audio_sdl -B build-audio-sdl -G Ninja cmake --build build-audio-sdl python scripts/test_local.py --build-dir build-audio-sdl ``` For ASan/UBSan repeat in a separate directory with `-DVIDEO_AUDIO_SANITIZE=ON`. The existing SDL dependency is pinned to pkg-config/runtime 3.4.18 for this restricted proof; no download/install/fallback or Core dependency is introduced. SDL is zlib licensed. Admitting another SDL build requires rerunning the actual stream/dummy probes. The real tests forcibly select `SDL_AUDIODRIVER=dummy` before SDL initialization; no physical device, speakers, windows or network. ## Ownership, pumping and accounting Initialize SDL audio explicitly in the application, open `video_sdl_open`, use its interface in the controller config, and call `video_sdl_pump` on the owner thread regularly while playing. Pump/snapshot/lifecycle are owner-thread only. Controller decode remains on its own bounded worker. SDL receives **NULL callbacks and NULL userdata**: no OS callback captures a controller, sink or application pointer. No callback detach race or retired callback leases exist in this design. Each pump locks the private stream, validates both stream formats (48 kHz, native-endian F32, stereo) and unity frequency ratio, queries remaining input bytes, acknowledges the newly drained ordered ticket prefix, then renders and successfully puts at most one bounded chunk. Only successful puts enter the private ledger. The stream lock excludes concurrent mixer drain across the queue observation/put transaction; host render/consume run under this lock. Nothing holds a controller lock while calling the output lifecycle callbacks. The decoder never acquires the stream lock. Device pause/resume/close always run **outside** the stream lock, avoiding SDL's device-before-stream lock inversion. This uses ordinary locks on the owner, with no hard realtime/deadline claim. For a generation, successful submitted bytes minus exact queued input bytes is the consumed software prefix. Query errors, non-multiples of 8 bytes, counts larger than outstanding successful puts, format changes or invalid ticket acknowledgements fault playback. It is not valid to use converted-byte counts, callback demand, elapsed wall time or a put itself as consumption. Ledger tickets remain ordered even across partial drains. Controller-tagged underrun padding does not advance media time; valid decoded PCM zeros do. Max pending frames and one-pump chunk size are explicit (1..65536). Chunk must also fit the controller capacity, and the transport maximum should not exceed that capacity. Both ledger and scratch storage are preallocated. The maximum queued input is max_frames*8, well below SDL's int clamp. `pending_frames` in the snapshot is successful puts not yet reconciled, not a live queue query. It also includes frames already drained by SDL since the last owner pump. Pause first freezes the logical device, then locks the stream and reconciles its final software-drain prefix. It retains queued input/tickets for resume. Seek or destroy uses discard: it reconciles a trustworthy prefix, clears the remainder without consumption credit, resets its ledger and detaches the controller pointer. Controller destruction joins the decoder before returning. Destroy the output only after successful controller destruction; failure leaves live storage for a retry. SDL stream destruction closes its logical device, with no app callbacks. A put can fail after host render reserved a ticket. That reservation cannot be rolled back through the existing controller API. The adapter therefore faults, attempts to pause, stops all submissions and acknowledges nothing further from ambiguous queue state. It does not fake consumption or resume across the gap. Owner must explicitly seek/reset the controller from its last acknowledged position (or destroy/recreate); successful discard clears both ledgers. Pause, lock or clear failure is not quiescence: controller seek/destroy returns false, keeps live allocations, and can be retried. Never free on a failed destroy. ## Timing and scope limits Owner starvation can cause SDL to exhaust its bounded queue and produce silence. No new media is submitted while the owner stalls, and the controller clock stays at its last reconciliation until the next pump. This is safe bounded buffering, not continuous playback under arbitrary UI stalls. Schedule pumps frequently enough for the chosen chunk and queue horizon; a queue of 256 frames covers only 5.33 ms at 48 kHz, while 12000 covers 250 ms. One-pump work is bounded, and a single call deliberately does not refill the entire queue. The clock advances in mixer-sized bursts, can lead physical audibility by an unknown downstream tail, and can lag software mixing by an arbitrary owner stall. No physical/backend latency bound or sample-exact visual synchronization follows. The selected precondition is a fixed destination format for the whole generation. Observed mismatches fail closed. A transient device-format change and restoration between owner polls cannot be detected by those snapshots; dynamic device migration/hotplug needs a separate reviewed event/format invalidation strategy before physical-backend integration. The source format/maps/ratio stay private and unchanged. Volume mixing and later backend conversion do not turn this into a hardware clock. This slice proves the software boundary on Linux SDL 3.4.18 dummy only. Physical playback, macOS/Windows validation, hardware removal/recovery, video presentation, rate control and combining real demux with this transport remain separate work. See [PROOF.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/video_audio_sdl/PROOF.md). --- ## Optional silent local-video player Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/video_player/README.md # Optional silent local-video player This example decodes **actual encoded video** on a worker using an explicitly optional FFmpeg host dependency. Core/Base/Components remain codec independent. It uses the callback runner, controlled playback requests and borrowed RGBA surfaces. No audio, networking, hardware decoding, subtitles, recording or casting is implemented. Fullscreen is omitted because the present portable window interface does not offer that action. From the repository root, with the audited development libraries already present: ```sh python examples/video_player/build.py --build-dir /tmp/cui-video-example --test /tmp/cui-video-example/video_player /path/to/font.ttf /path/to/local-video.mkv ``` The build helper writes an external CMake harness; it changes no repository CMake/module registration and installs nothing. It requires C11 threads, pkg-config, CMake/Ninja, the existing native CUI dependencies and these audited FFmpeg library versions: libavformat/libavcodec 63.1.102, libavutil 61.1.102, libswscale 10.1.102. Other versions require a deliberate compatibility audit/update; they are not silently accepted. The default test font is `/usr/share/fonts/noto/NotoSans-Regular.ttf`; use `--font /path/to/font.ttf` when it is elsewhere. Native automated tests always run through `test_local.py` on private Xvfb. They cannot fall back to a desktop display. The interactive command above is for an explicit human launch. The helper records complete `ffmpeg -version`, `-buildconf`, `-L` and library versions in `BUILD_DIR/ffmpeg-build-audit.txt`. The audited validation host's binary reports FFmpeg n9.0.2, GCC 16, shared libraries, `--enable-gpl --enable-version3` and GPLv3 or later. It enables many optional external codecs and disables magicyuv decoding. The example does not vendor, download, package or redistribute those libraries. Its MIT source license does not change the linked FFmpeg build's licensing. Choose/review redistribution separately; do not assume every FFmpeg build has the same license or codec availability. ## Clock, worker and frame lifetime The UI owns confirmed timeline/view state. Controls issue requests; the example accepts play/pause/rate and committed seek/skip requests, while begin/update/cancel remain scrub presentation. The timeline uses the host's monotonic SDL delta; paused time does not advance it. The worker opens/demuxes/decodes/converts local files; no decoding, sleeping, event pumping or queue waiting occurs in UI callbacks. Mutex critical sections copy state and manage slots, never decode or convert. FFmpeg protocols are restricted to `file`. This example is not a hardened loader for untrusted media or a network player. Exactly three reusable slots bound RGBA storage, each at most 4096x4096 pixels. Slots transition FREE -> WRITING -> QUEUED -> LEASED -> FREE. The UI acquires the latest due queued frame and may drop older queued frames. One paused lease is retained unchanged, while the worker fills the other slots and waits. Replacement releases the previous lease only after synchronous renderer consumption. Closing with a lease outstanding fails; the caller must release it before joining the worker. A copied already-released lease cannot release a reused slot because source, generation, pointer and revision are checked. Pixel memory is never freed or recycled at surface submission/end_frame. Seek increments model generation before enqueueing the command. Queued old frames are discarded; worker conversion in flight is checked against the command serial before publication. A leased old frame stays valid until release but the player rejects it against the new source/generation. Source identity is fixed for an adapter instance; replacement opens a new instance with a fresh nonzero ID. The worker seeks/flushes and discards frames before the target. Its first frame at or after the requested target may be acquired as a paused seek preview; the host acknowledges the actual timestamp in the confirmed view. This is frame-accurate preview acknowledgement, not sample-accurate audio seeking. At EOF the worker waits for a seek or shutdown. Known-duration playback ends at the timeline bound; unknown duration uses explicit host EOF acknowledgement after its queue drains. The last displayed frame stays leased. Errors are observable and stop this example with failure; a production host can publish an error view and recovery UI. Shutdown signals the worker and joins it, freeing packet/frame, conversion context, codec/container and slot storage. A protocol interrupt callback also observes shutdown. No asynchronous UI callback survives adapter destruction. This simple silent clock has no buffering/rebase policy for a decoder that cannot keep up: it may drop late frames. Audio synchronization, general edit lists, rotation/sample-aspect/color/HDR metadata, variable-rate scheduling accuracy, network cancellation, bounded seek latency and broad format compatibility remain unverified. Conversion currently uses FFmpeg's default SDR RGBA conversion; it must not be called color-managed or HDR playback. ## Evidence and boundaries `make_fixture.py` encodes 20 real 64x32 red/blue frames into FFV1/Matroska using the installed executable. `test_decoder.c` decodes that file, verifies actual RGBA and software-render pixels, pause lease stability, seek generation/content, stale frame rejection, exactly-once release, bounded slots, EOF and missing-file cleanup. `test_native.py` runs the real callback player in private Xvfb, captures presented red, paused red and post-seek blue BMPs and checks decoded interior pixels. Native callbacks never wait for frames. No generated placeholder is substituted for a failed decoder. Portable unit tests separately prove controlled owner rejection, per-event requests, copied callback snapshots, touch cancellation, keyboard seeking, focus, accessible names/normalized ranges, accessibility button activation, SVG loader replacement, responsive button rows, capability gating and omitted hit targets. The legacy Base test also runs unchanged. Browser CUI exports/bindings for the new controls are integrator-owned and are not added by this example. Browser decoding, browser fullscreen permission behavior, and a browser-rendered player remain **unverified**. A later browser host should use actual HTMLVideoElement/WebCodecs output, feed copied RGBA into the same surface, and run headless tests with a real supported encoded clip. FFV1 browser support is not assumed. Native/software proof does not establish browser parity. --- ## Native FFV1 video with PCM sound Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/video_player_audio/README.md # Native FFV1 video with PCM sound This optional runnable CUI example routes actual decoded/resampled PCM to SDL's default output and presents actual FFmpeg video frames against the observed SDL software-mixer media clock. It uses existing controls, callback-main resize, borrowed frame leases, worker decoders and the bounded audio controller. Core has no codec or audio-device dependency. **Supported first profile:** immutable local Matroska with FFV1 SDR video and PCM audio, known zero container origin, duration <=10s. Fixtures prove S16LE stereo 48k and44.1k input, normalized to48k F32 stereo. Requires obtained SDL stream source/destination both48k F32 stereo/unity ratio. The decoder admits additional PCM representations/rates as documented in its own README; they are not newly verified here. Video frame durations must be known and <=1s. Audio/video endpoints must agree within100ms; large mismatch fails explicitly at actual EOF, rather than stretching audio or inventing a wall-time tail. Fullscreen and playback rate controls remain omitted. This is **not general native MP4/AAC/Opus support**. The existing silent video example and browser player remain separate paths. ## Build and automated validation From repository root, with the already installed audited development packages: ```sh cmake -S examples/video_player_audio -B build-video-sound -G Ninja -DVIDEO_SOUND_UI=ON cmake --build build-video-sound --target video_player_audio test_sound test_sound_watch test_sound_output test_sound_legacy python scripts/test_local.py --build-dir build-video-sound -- -R '^sound_' ``` The external project builds only those requested targets and their dependencies; no root CMake or package registration is edited. Omitting `VIDEO_SOUND_UI=ON` builds the19 no-window checks without CUI runtime linkage. Repeat with a separate build directory and `-DVIDEO_SOUND_SANITIZE=ON` for ASan/UBSan. Native automated smoke always requires wrapper-owned Linux Xvfb, software rendering and forced SDL dummy audio; it cannot fall back to a desktop or physical output. Browser tests are unrelated and remain headless. Pins are SDL3.4.18 (runtime and pkg-config), FFmpeg CLI n9.0.2, libavformat/ libavcodec63.1.102, libavutil61.1.102, libswscale10.1.102, libswresample7.1.102. No installation/download is performed. Generated `media/dependency-audit.txt` records versions, FFmpeg build configuration and full license text. Tested shared FFmpeg enables GPL/version3, so its linked package is GPLv3-or-later, not an assumed LGPL-only build. Example source is MIT; SDL is zlib licensed. No binary packaging or redistribution is introduced here. ## Explicit interactive launch The test fixture generator creates a real two-second red/blue video with a quiet generated440Hz PCM tone, plus resampling/offset/error fixtures. After the build/test above, a human may explicitly run this command to open a native window and send sound to their default output: ```sh build-video-sound/video_player_audio third_party/inter/Inter-Regular.otf build-video-sound/media/fixture.mkv ``` That command is for manual use; automated agents/tests do not launch it. No physical listening test was performed during implementation. Use the existing font file or supply another valid font path. This example has play/pause, committed seek/skip and replay, responsive layout and visible failures. Unsupported media/output does not silently switch to successful silent playback. Device invalidation or a partially accepted seek requires closing/reopening the example. For an explicitly chosen local clip, a manual FFmpeg conversion can produce the supported codec profile (larger, lossless files; first8s only): ```sh ffmpeg -nostdin -i local-input.mp4 -map 0:v:0 -map 0:a:0 -t 8 -c:v ffv1 -pix_fmt bgr0 -c:a pcm_s16le -ar 48000 -ac 2 converted.mkv ``` Conversion is not automatic and requires an existing audio track. Its result must still satisfy origin/timestamp/frame-duration/endpoint limits above; arbitrary input edit lists, offsets and unequal tails are not promised compatible. No compressed codec is added to the running sound adapter by this command. ## Clock, preview and failure behavior Media time is exact acknowledged media frames divided by48000. It advances only when the private SDL input queue actually drains, not at render/put, wall time, callback demand or zero-filled underrun. This is **software mixer consumption**, not backend acceptance, DAC time or acoustic playback. Downstream physical tail is unknown; clock observation can lag by the owner-poll interval. Video frames are selected against that observable clock, with late-frame dropping; no speaker-level lip-sync guarantee follows. Audio generation and video generation are explicitly mapped. Pause freezes and reconciles output, then retains the current video lease. A committed seek quantizes its audio target to48k frames and requests both workers. A paused video preview may land after that target; it does not overwrite the audio target. During playback that future preview is hidden until due. A frame borrowed during UI composition survives a seek request in that same composition until the next owner poll, after synchronous renderer consumption. At EOF all audio media must drain, future video tails are validated/drained, and the last valid frame remains. A one-sided seek failure leaves the whole session failed/paused, not rolled back to inconsistent counters. Failed output put receives no fake consumption and requires reset/reopen. Close destroys/joins audio before its service/output, releases the video lease, joins video, and only then permits Core/window/font freeing. A failed close preserves live resources for retry; example shutdown aborts rather than free reachable userdata after unresolved quiescence failure. OS file I/O may delay worker joins; no hard shutdown deadline or total FFmpeg heap bound is claimed. SDL output device added/removed/format-change events set a sticky atomic private endpoint, including output changes unrelated to this stream. The event callback never sees host/UI/sink pointers or calls CUI. Capture-device changes are ignored. The next format/consumption transaction fails closed; matching format later or a seek cannot clear it. Whole output/controller recreation is required. Owner removes/quiesces the watch before its endpoint free using the inspected pinned SDL dispatch/removal mutex behavior. Synthetic tests prove handling/lifetime; real OS hotplug notification reliability remains unverified. SDL initially queues audio enumeration internally until owner polling. The app initializes audio, allows its normal callback-runner poll to dispatch those startup notifications, then creates the guarded output/session. It never resets a sticky flag or nests an event pump to hide later changes. Direct session users must follow the same staging rule. The owner pumps at most one1024-frame chunk per frame into a12000-frame (250ms) queue. Callback-main remains invalidated while playing/loading/seeking. Long UI or native modal-resize stalls can exhaust that bounded queue, producing silence; owner resumes safely but continuous sound through arbitrary stalls is not promised. Workers never paint, manipulate windows or pump events. See [PROOF.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/video_player_audio/PROOF.md) for results and intentionally deferred claims. --- ## Copied activation snapshots Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/ACTIVATION_SNAPSHOTS.md # Copied activation snapshots `cui_event_activation_snapshot` returns copied evidence for an activation already accepted by a submitted control. Query it after `cui_interact` accepts the activation, during ordinary frame composition. Each accepted event retains its own slot even when a frame contains multiple clicks or synthesized touch cancellation reorders the dispatch list. ```c cui_activation_snapshot click; if (cui_event_activation_snapshot(ui, event_index, &click)) { if (click.has_press && click.has_release) { float dx = click.release.x - click.press.x; (void)dx; } if (click.has_key_bounds) { cui_rect anchor = click.key_bounds; (void)anchor; } } ``` The context stores a bounded snapshot beside each existing activation slot. It performs no additional per-event allocation. A pointer press is retained across frames only while the existing primary capture survives. Cancellation, touch gesture takeover, removal and disabled capture clear the retained press. Leaving the window preserves it. A release must match pointer type, contact, device and button before `has_press` becomes true. Existing routing can accept some unmatched releases; those retain release evidence with `has_press=false` instead of borrowing another contact's press. Keyboard evidence contains the previous rendered clipped routing rectangle, even if the current composition moves the control. Accessibility activation has no fabricated press, release or keyboard bounds. Raw pointer click count zero remains zero. First-focusing-click and long-press metadata require separate authoritative host support and are not exposed here. False leaves the output untouched. The query refuses unaccepted/cancelled events, current disabled/modal/accessibility rejection, invalid indices, null output, Core errors, inert/layout-only ancestry, measurement/prepaint and calls outside a frame. Accessibility consumption can invalidate a subsequent query; copy evidence before callbacks that may consume it. A returned value contains no pointers and survives later frames or context destruction. Frame sequence and event index identify only this context/frame, not recreated contexts or sequence wrap. The default retains Enter-down, Space-up, focus and consumption behavior. Core now also supports opt-in activation on key release; see [the bounded release-key policy](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/validation/release-key-activation-sol6.md). Button forwards copied evidence before callbacks; see [Button click evidence](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BUTTON_CLICK_EVIDENCE.md). Signed tab paths and capture/bubble propagation remain separate unfinished capabilities. Standalone Core-only headless tests cover multiple clicks, cross-frame pen capture and leave/enter, raw counts/modifiers/device, unmatched releases, cancellation, previous rendered keyboard bounds, modal/disabled/accessibility rejection, phase guards, output preservation, retained-copy lifetime and synthesized touch event reordering. Native strict C11 and ASan/UBSan/leak checks pass. Actual Zig0.16/Wasmtime49 reports136-byte snapshots and40-byte pointer samples, matching this native host; these are receipts rather than cross-platform ABI requirements. Portable full CTest148/148 passes; the final expanded fixture was rerun separately. WASI assertions remain enabled. --- ## Avatar failure and naming audit Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/AVATAR_FAILURE_AUDIT.md # Avatar failure and naming audit Reference: upstream kit 0.7.1, commit `87d10ae5e1299d1be18670a37570c5402f952e34`, inspected from the local reference checkout recorded in `docs/upstream-baseline.md`. `crates/base/src/avatar.rs`, `Avatar::render`, chooses its optional image slot before its fallback slot. `AvatarImage::render` delegates to `upstream::Img`. There is no Avatar load-state callback, error transition or retry mechanism. The base tests assert image-slot precedence and fallback when the slot is absent; they do not assert fallback after decoding failure. `crates/component/src/avatar/avatar.rs`, `Avatar::render`, always constructs a fallback and adds an image slot when `src` exists. Without `src`, a supplied name selects initials and identity colors; without a name it selects the configurable placeholder icon. This does not establish automatic failed-image fallback or accessible-name behavior. upstream image internals are outside this bounded audit. CUI accepts host-decoded RGBA, validates it synchronously and paints initials when the current source/cache cannot prepare. Preparation failure leaves a prior cache intact; `cui_avatar_ex` gates rendering on the current return value rather than the cache's `ready` flag. A valid source on a later frame recovers. No production behavior change or speculative lifecycle API is needed. `tests/unit/test_content.c`, `image_avatars`, exercises successful rendering, missing and invalid-stride sources after success, preserved cache, initials draw commands, software fallback pixels, full-name image/button and anonymous image semantics, and recovery of the photo without unnecessary cache revision changes. Fallback text commands are asserted independently of the software fill checks, which omit text to avoid a host-font dependency. CUI uses Anonymous for unnamed extended avatars. Semantic names are checked before the next frame starts. This slice does not establish complete Avatar parity. Configurable upstream icon placeholders, identity colors and typography/size variants remain outside this failure-and-naming evidence. There is no host image acquisition, decoder, network retry, screen-reader integration or GPU coverage in these tests. --- ## Avatar style bindings Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/AVATAR_STYLE_BINDINGS.md # Avatar style bindings The retained bridge exposes opt-in Avatar styling in C, Python, Node/TypeScript, Go and Rust. Shared `design_size` currently covers **Button and Avatar only**; other component kinds return an error. This is an incremental binding surface, not uniform styling coverage or full component parity. The existing Button `size` method, convenience variants, defaults and callback behavior remain unchanged. `design_size` on Button selects the same scale; subsequent size calls replace the previous selection. The C `cui_bridge_design_size` typedef aliases `cui_bridge_button_size`, retaining all existing `CUI_BRIDGE_SIZE_*` values. Go `DesignSize` and Rust `DesignSize` likewise alias their existing `Size` type; Python and TypeScript expose named size literals. | Setter | Coverage | Effect | | --- | --- | --- | | `design_size(size)` | Button, Avatar | `inherit`, `xs`, `sm`, `base`, `md`, `lg`, `xl`, `2xl` through `9xl` | | `identity_colors(enabled, hue)` | Avatar | Deterministic CUI identity palette; optional hue selects one of 12 hues, 0..11 | | `anonymous_icon(enabled, name)` | Avatar | Named SVG fallback for an empty person name; empty icon name selects `user` | C uses `cui_bridge_set_design_size`, `cui_bridge_set_avatar_identity` and `cui_bridge_set_avatar_placeholder`. Boolean flags must be 0/1; hue must be 0..11. Placeholder names are validated UTF-8 and copied transactionally, with a 4096-byte limit. Invalid calls preserve the previous settings. Removed handles and closed Apps return the existing handle/lifecycle errors. An App pointer is invalid after `cui_bridge_destroy`, as with every bridge function. Python, Node and Go support configuring an unmounted retained builder and live updates after mounting. Rust supports the App methods and fluent borrowed Builder methods. All wrappers validate component kinds and argument types; invalid Go builder calls retain the existing sticky error convention. ```python person = avatar("person", "Ada Lovelace").design_size("md").identity_colors(True, 4) anonymous = avatar("anonymous").anonymous_icon(True, "user") ``` ```typescript const person = avatar('person', 'Ada Lovelace').design_size('md').identity_colors(true, 4); const anonymous = avatar('anonymous').anonymous_icon(true, 'user'); ``` ```go person := cui.Avatar("person", "Ada Lovelace").DesignSize(cui.MD).IdentityColors(true, 4) anonymous := cui.Avatar("anonymous", "").AnonymousIcon(true, "user") // IdentityColors(true) selects the deterministic hue; at most one hue is accepted. ``` ```rust let person = app.build_child(root, Kind::Avatar, "person")? .text("Ada Lovelace")?.design_size(DesignSize::Md)? .identity_colors(true, Some(4))?.finish(); app.anonymous_icon(person, true, "user")?; // None selects the deterministic hue. ``` With every new option disabled and size inherited, Avatar retains its exact legacy renderer: 40 logical pixels by default, or its existing `visual_size` width. Explicit scale variants take precedence over pixel width and use the native Avatar's 16px rem basis: XS=16, SM=24, BASE=MD=48, LG=80; larger variants follow the shared scale with a 512px bound. Styled inherited pixel sizes are also capped to 512. Clearing the scale, identity and anonymous-icon options restores the legacy renderer, including legacy pixel widths over 512. Positive Avatar dimensions stay fixed even in narrow flex layouts; this slice adds no responsive shrink behavior. Avatar continues to ignore `visual_size` height. Identity colors use the native CUI initials hash and current theme's light/dark palette. They are not a guarantee of another toolkit's identity assignment. Named people keep their initials even when an anonymous icon is enabled. The anonymous icon is decorative within the Avatar's existing Image semantic; it does not add a focus stop or activation/callback API. Icon names resolve via the existing embedded catalog/name/path aliases and context cache, with runtime SVG rasterization. An unavailable icon name paints no icon; it is not a raw SVG string, arbitrary filesystem loader or a foreign icon-state object. This slice omits borrowed `cui_icon_state *`, raw SVG input/custom loaders, bitmap/image-state ownership, custom background/foreground/ring colors, interactivity and AvatarStack. It does not add style setters to other components. Use a matching bridge/library revision; generated SDK/export copies are updated by the integration workflow. Validation includes a portable real-bridge draw fixture covering legacy and styled bounds, palette colors, SVG mask draw commands, accessible Image/name, owned placeholder lifetime, transactional rejection, removal and closed Apps. The fixture includes the portable bridge implementation to inspect its private renderer without exporting a testing hook; compile it with the `cui` target only, not `cui_bridge`. Existing callback/lifetime tests and new language cases cover all five handwritten surfaces, including strict TypeScript negative checks. All CTest runs use `python scripts/test_local.py --build-dir ` on Linux. --- ## Avatar palette, placeholder and metrics audit Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/AVATAR_VARIANTS_AUDIT.md # Avatar palette, placeholder and metrics audit Frozen reference: upstream kit 0.7.1 commit `87d10ae5e1299d1be18670a37570c5402f952e34`. Sources: `crates/component/src/avatar/avatar.rs`, `avatar/mod.rs`, `website/component/avatar.md` and `website/base/primitives/avatar.md`. The base guide describes parent-supplied loading/error fallback content; it does not establish an automatic Avatar error transition. The styled Avatar chooses an image when supplied, initials when a name exists, and a configurable `Icon` placeholder otherwise. Its default icon is User. Initials carry a 12-hue identity palette; photo/anonymous borders remain neutral. Each palette hue is 30 degrees apart in OkLCH. Light palette triples (background, foreground, border) are (0.97,0.032), (0.50,0.145), (0.89,0.05); dark triples are (0.30,0.05), (0.82,0.11), (0.36,0.06). The hue index is selected by private upstream hashing of the short name. CUI must disclose a different stable hash assignment if it does not port that implementation. Frozen metrics are XS=16px with 0.65rem text; Small=24px with 0.75rem text; Medium=48px with 0.875rem text; Large=80px with 1.875rem semibold text. Custom `Size` sets the initials child dimensions to half the avatar dimensions; it does not clearly specify half-size text. Do not claim such typography parity. Additional CUI design-scale sizes must be identified as extensions. Remaining broader differences include upstream Unicode uppercasing/initial selection versus CUI first/last UTF-8 scalar initials, arbitrary upstream style refinements, and arbitrary base fallback children. This audit does not establish complete Avatar or AvatarGroup parity. Implemented opt-in mapping: `cui_avatar_options.design_size` reuses the shared CUI scale. INHERIT retains existing `.size` behavior. Explicit XS/SM/BASE=MD/LG use the frozen preset dimensions above. XL..9XL use twice shared control height, with the overall scale capped at 512 divided by raw variant diameter; typography uses shared font size times 30/18, with semibold weight. The cap scales diameter and text together to preserve their ratio, including 9XL at rem=16. These higher steps are CUI extensions. A positive rem parameter scales presets; zero in options selects 16. Metrics helper rejects invalid inputs without modifying output, while Avatar falls back to legacy metrics for invalid options. Identity colors use the frozen OkLCH triples and theme.dark. CUI deliberately uses FNV-1a over its UTF-8 initials bytes, not an unverifiable upstream hash clone. An explicit 0..11 override supports host-controlled assignment. Explicit legacy background/foreground options still win. Invalid hue overrides retain legacy colors. The identity border applies only to named initials frames. Anonymous SVG rendering is opt-in, with borrowed typed state, then named context-cache lookup, then User as the default. The Icon contract determines lookup/parse failures. A photo or supplied name wins; decorative SVGs add no semantic duplication. Typed-mask lifetime and named-cache bounds stay those of the existing Icon API. No network source acquisition is added. Headless tests in `tests/unit/test_content.c`, `avatar_variants`, check all light/dark palette hues for AA contrast after 8-bit encoding and non-clipped border channels, hash stability across identical initials, rejected hue overrides, all design sizes, explicit metrics precedence, rem scaling, typography weights, legacy metrics/colors, typed/named/default icons, initials precedence, image precedence, absence of duplicate semantics, and software pixels. The targeted content CTest uses the isolated-display wrapper; no GPU or screen-reader claim is implied. Generated SDK/skill metadata remains an integrator refresh step. The scale-cap regression exercises every variant at rem 1, 16, 64 and 512, checks the font-size/diameter ratio against uncapped small-rem metrics, and verifies actual Avatar bounds and emitted text sizes. Large rem values cannot leave oversized initials after the diameter reaches 512. --- ## Unreleased deterministic background preparation Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BACKGROUND_PREPARATION.md # Unreleased deterministic background preparation Maintainer building block only: `src/core/cui_background_prepare_internal.h`. The public sized `cui_render_v2_options` record lives in `cui/cui_draw_v2.h`; query/raster functions and their result record are private, not a stable consumer API. **No software/native/Canvas adapter advertises or consumes V2 backgrounds.** All five consumer integrations, full-list validation, target/upload lifetime, wire exports, foreign authoring and all78 component-part coverage remain pending. See [Core V2 transport](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CORE_DRAW_V2.md) and the [five-adapter plan](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/BACKGROUND_V2_RECORDS.md). The allocation-free helper takes owned draw-by-value, copied options, a logical active clip and caller output storage. It has no context, cache, pointer retention, resource graph, driver calls, target mutation or upload ownership. It uses the existing [pure sampler](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BACKGROUND_VALUES.md) for both models and both spaces. ```c /* PRIVATE declarations, not new installed public CUI functions. */ cui_error cui_background_prepare_query(cui_background_draw_v2, const cui_render_v2_options *, cui_rect clip, cui_background_prepared_query *out); cui_error cui_background_prepare_raster(cui_background_draw_v2, const cui_render_v2_options *, cui_rect clip, unsigned char *rgba, size_t stride, size_t capacity, cui_background_prepared_query *out); ``` Exact options size and SRGBA8_CENTER_V1 output tag are required. Positive finite scales are [1/65536,64], origins [-1e6,1e6], physical viewport sides <=16384. Draw origin follows the sampler's [-1e6,1e6] domain, width/height are [0,1e6]. A finite nonnegative logical clip may extend beyond that domain; it only culls work. Radius values must be finite and independently clamp to [0,half min(w,h)]. Ancestor opacity is finite [0,1]. Invalid active brush values reject even offscreen. Inactive value fields retain the pure sampler's ignore rules. Map original bounds and clip to physical coordinates with double arithmetic, intersect viewport, then floor left/top and ceil right/bottom. Return the integer cover and its inverse logical rectangle. Never replace the gradient frame with this covering/cropped rectangle. Inverse-transform target pixel centers; convert sampler coordinates to float once. Validate the covering rectangle's first/last center extrema against [-1e6,1e6] before any write. This conservative check also rejects out-of-domain covering corners later excluded by the shape mask. Original box edges may extend outside the domain when all covered centers remain valid. No semantic fill is silently cropped to hide domain failure. The CENTER_V1 mask tests centers against the original half-open box and independent logical corner circles; unequal density gives physical ellipses. Outside cells become transparent black. Active clip alpha is **not** baked into the raster; future consumers apply their existing ancestor clip once. No analytic AA/source GPU edge parity or linear-light destination compositing is claimed. Upload at the integer physical cover, without generic IMAGE logical-ceil reraster, stretching, second radius mask or second opacity. Adapter implementations still need review. Shared output conversion takes the sampler's premultiplied linear float RGB/base alpha, unpremultiplies by base alpha, clips straight RGB, encodes sRGB and rounds half upward to bytes. Final alpha is baseAlpha*ancestorOpacity rounded once. RGB remains independent of nonzero ancestor opacity, avoiding a multiply/divide float roundtrip. Exact zero final alpha becomes transparent black; RGB may remain nonzero when a positive alpha merely quantizes to zero, preserving sampler policy. Existing sampler bytes are checked against independently frozen pre-refactor code. Query reports packed minimum stride=width*4 and bytes=stride*height. Raster returns **actual supplied stride** and validated CPU span=(height-1)*stride+width*4, with identical geometry. It does not write any row padding, including last-row padding. The query/result layout is not a wire format and padding has no defined bytes. Empty clip/intersection, zero draw dimension or zero viewport dimension succeeds with every result field canonical zero; raster permits NULL pixels/capacity0 and writes no buffer bytes. Options/brush/alias validation still applies to empty work. All options budgets are explicit nonzero ceilings: <=4M pixels/background, <=8M pixels/frame, <=32MiB each CPU/texture/transfer and <=1MiB metadata. Query checks packed bytes against all three storage envelopes and one nonempty query record against metadata. Raster additionally checks actual padded CPU span against CPU budget and capacity, including overflow. This is per-background accounting; future adapters must separately preflight whole-list aggregate, draw expansion, real transfer alignment and in-flight lifetime before clearing/submitting targets. No total process/driver-memory bound or GPU recovery guarantee follows from it. Options, query output and the whole supplied pixel capacity must be disjoint. Detectable overlap/address-range overflow rejects; arbitrary pointer validity and allocated object extent remain the caller's C contract. Owned draw and clip values are copied. No query output or buffer byte changes on failure. Query/raster return INVALID_ACTION for malformed policy/value/numeric/alias input, CAPACITY for work, byte/stride/span/resource ceilings. Raster recomputes its complete plan and validates all sample-domain and output preconditions before the first write; no data-dependent failure follows it. Retry requires no context reset, rollback or replay. Tests compare prepared pixels against frozen old sampler math plus an independent long-double corner-distance/color reference, not candidate-generated expectations. They cover source/CSS, sRGB/Oklab, transparent stops, one-step opacity, unequal and fractional density/phase, corners, offscreen large extents, conservative domain rejection, empty work, exact quota boundaries, padded buffers, alias/error atomicity and retry. Existing sampler byte goldens and V1 rendering remain separate oracles. The next software building block, `backends/software/cui_software_v2_internal.h`, validates full V2 list structure and active borrowed resources, clip nesting and aggregate known workspace reservations before any target access. Its counted transaction arena is optional and has no V1 call site. A successful private validation plan is NOT a prepared/renderable frame: explicit adapter text/shadow resource preparation remains pending. A [private partial painter](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SOFTWARE_V2_PAINTING.md) now stages shape/image/mesh/background transforms and bounded AREA DROP/INSET shadows, but still rejects text; every public adapter support query/render entry remains pending. See [software checkpoint](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SOFTWARE_BACKGROUND_V2.md). A private [counted text recorder](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TEXT_PREPARATION.md) supplies source-grid glyph coverage and explicit CUI ownership, but is not integrated into an adapter. Opaque new font/dependency temporaries remain outside the transaction byte envelope. The private software validator follows native contextual-text selection: a non-NULL paragraph pointer is authoritative even for an empty paragraph, so inactive raw text fields are ignored. A NULL paragraph with a nonzero length or range remains invalid; active contextual UTF-8 and byte boundaries are always validated. The correction is checked against the immutable original text implementation's empty-context behavior, poisoned inactive raw fields, malformed active contextual UTF-8/ranges, and transactional validator failures. Strict C11 warnings-as-errors and three focused private-Xvfb checks passed; no renderer capability is implied. --- ## Owned background values and pure sampling Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BACKGROUND_VALUES.md # Owned background values and pure sampling Development source only: these APIs were added after v0.1.0-alpha.3 and are absent from its published packages. Use matching headers and implementation. Unreleased C-only API in `include/cui/cui_background.h`. These are independent owned values and allocation-free math. They do not apply paint to elements or provide gradient rendering. All existing V1 commands, boxes and renderers retain their behavior. Full background rendering across software, SDL_Renderer, SDL_GPU, Sokol and Canvas, all78 component coverage and foreign authoring remain pending. The approved transport is an explicit versioned draw/list contract. Unreleased [Core V2 transport](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CORE_DRAW_V2.md) adds mode/storage/setters/emission and the [C software V2 consumer](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SOFTWARE_V2.md) provides actual rendering. The other four adapters and bindings remain pending; [private CPU preparation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BACKGROUND_PREPARATION.md) is the allocation-free building block. A value is either a solid straight-linear sRGB color or a fixed two-stop linear gradient. There are no pointers, borrowed arrays, caches, contexts or resources. Constructors copy active fields and zero inactive fields. Directly authored values are validated on every sample. SOLID ignores model/space/angle/stops; LINEAR ignores solid. Invalid active enums, nonfinite numbers and out-of-domain inputs fail atomically. Failed bool calls preserve output. Constructors accept input values drawn from their output object. Colors have finite straight linear RGB and alpha in [0,1]; hidden RGB at zero alpha is retained in owned values. `cui_background_color_from_srgba8` explicitly decodes encoded byte channels. `cui_background_color_from_source_038_hsla` accepts normalized HSLA and matches the source shader's conversion convention: its resulting RGB is treated as linear, without an extra sRGB decode. These conversions intentionally differ for gray. Neither quantizes to bytes or premultiplies the stored color. The HSLA conversion uses cancellation-free equivalent chroma near black and clips unit-gamut roundoff to [0,1], so every successful result is a valid owned color. This correction does not clamp the sampler's Oklab out-of-gamut output. ```c #include cui_background background; cui_background_color red = cui_background_color_from_srgba8((cui_color){255, 0, 0, 0}); cui_background_color blue = cui_background_color_from_srgba8((cui_color){0, 0, 255, 255}); if (cui_background_make_linear(CUI_BACKGROUND_CSS, CUI_BACKGROUND_SRGB, 90, (cui_background_stop){red, 0}, (cui_background_stop){blue, 1}, &background)) { cui_color midpoint; if (cui_background_sample_srgba8(&background, (cui_rect){0, 0, 100, 20}, 50, 10, &midpoint)) { /* midpoint is straight encoded sRGBA8 {0,0,255,128}. */ } } ``` Angles are finite [0,360] degrees: 0 up, 90 right, 180 down;360 equals0. Stop positions are finite [0,1]; outer colors extend beyond the interval. CSS requires ordered stops; SOURCE_038 also accepts reversed stops. Equal stops switch to the second color at/after the common position. This deterministic equal-stop extension avoids the source shader's division by zero; it is not a source undefined-result parity claim. Neither mode implements multiple stops, repeating gradients, source patterns, CSS parsing, wide-gamut inputs or a CSS framework. CSS uses the gradient line spanning the full box diagonal projection and alpha-premultiplied interpolation in the selected space, followed by unpremultiply before converting back to linear RGB. SOURCE_038 instead rescales the short axis, uses the dominant-axis projection, interpolates straight selected-space channels and alpha independently, then premultiplies linear output. Both select encoded sRGB or Oklab interpolation. A transparent-red/opaque-blue midpoint is blue in CSS and purple in SOURCE_038; unequal rectangles also expose the geometry difference. `cui_background_sample` returns premultiplied linear float RGBA. Oklab excursions outside sRGB are preserved, including negative RGB or RGB above alpha. There is no gamut mapping. `sample_srgba8` unpremultiplies this float result, clips straight linear channels to [0,1], encodes sRGB and rounds half upward to bytes; alpha rounds independently. Exact zero alpha produces transparent black. Byte export therefore cannot preserve out-of-gamut or hidden transparent colors. It is one explicit output conversion, not a future renderer's mandatory framebuffer/color-space policy. Frame x/y and sample x/y are finite in [-1e6,1e6]; frame w/h are finite positive and <=1e6. Samples are logical points with no implicit pixel-center offset, coverage, clip, corner radius, opacity or transform. There is no raster loop or allocation in these functions. Per-pixel callers should decide their own sample positions; physical preparation and GPU upload ownership remain future work. Math is adapted from the already audited Plot transforms, without changing Plot, effects or text-paint implementations. Source evidence is the pinned [0.3.8 shader](https://docs.rs/crate/gpui-pre-wgpu/0.3.8/source/src/shaders.wgsl) and [CSS interpolation](https://www.w3.org/TR/css-color-4/#interpolation-alpha) and [gradient geometry](https://www.w3.org/TR/css-images-3/#linear-gradients). Frozen independent Python reference numbers cover both models/spaces and unequal rectangles. Tests additionally compare the existing source-HSLA Plot sampler and run existing Plot/effects/text oracles. No new browser/native GPU output is claimed. Python/JS/TS/Go/Rust typed exports, bridge/WASM exports and V2 draw support are absent. --- ## Badge Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BADGE.md # Badge `cui_badge_ex` attaches a count, dot or SVG icon to arbitrary child content. Submit it every frame. The application owns the count and child actions; Badge has no retained model. The corner marker does not change the child's measured size or add a keyboard focus stop. A count of zero hides only the marker. ```c #include typedef struct { const cui_theme *theme; size_t unread; bool opened; } inbox_state; static void draw_inbox(cui_context *ui, void *user) { inbox_state *inbox = user; if (cui_button(ui, cui_id_from(ui, "open-inbox"), inbox->theme, cui_string("Inbox"), false)) inbox->opened = true; } void draw_badged_inbox(cui_context *ui, inbox_state *inbox) { cui_badge_options options = cui_badge_defaults(); options.count = inbox->unread; options.name = cui_string("Unread messages"); cui_badge_ex(ui, cui_id_from(ui, "unread"), inbox->theme, options, draw_inbox, inbox); } ``` The defaults select the count variant, medium size and maximum 99. A count above the maximum displays `99+`; setting maximum to zero deliberately displays `0+` for positive counts. Full `size_t` counts are supported without allocation. For a presence dot, set `variant = CUI_BADGE_DOT`. For an icon, set `variant = CUI_BADGE_ICON` and `icon = cui_string("check")`. Icon names and paths use the same configurable theme SVG loader as other CUI controls; applications can supply their own assets. Set `custom_color = true` and `color` to override the marker background, including transparent colors. The four control sizes match the frozen source: icon diameters are 10px for extra-small/small, 16px for medium and 24px for large; the dot is always 6px. Count text is 10px with 2px padding and a 14px minimum width. The number's corner offset changes with the size and displayed digit count. An icon sits at the bottom right with a 1px border in the theme background; count and dot sit at the top right. Ancestor clipping applies. A supplied `name` provides the status semantic name; otherwise count text, “Notification” or “Status” is used. Name, icon and callback data are borrowed during submission. Invalid variant, size or nonempty null strings submit nothing and do not invoke the content callback. The older `cui_badge` draws a standalone text pill. Use it for tags such as “In review”; use `cui_badge_ex` for an indicator attached to content. Headless tests cover first-frame layout, all sizes/variants, overflow text, custom colors, icon draw commands, nonfocusable status semantics, zero-count content preservation and invalid-input callback isolation. Arbitrary child styles remain ordinary Core composition; there is no global text-style scope. ## Configured artwork route (focused C validation, unreleased) `cui_badge_with_icon` is an additive C route for ICON markers. Its `cui_badge_icon_content` borrows an initialized `cui_icon_state` and full `cui_icon_options`, including style, constraints, dimensions, color and affine transform. The shell keeps Badge corner geometry; artwork uses the ordinary Icon painter rather than the legacy named-icon extent-minus-two sizing. Missing inherited text size uses source 14/10/8px fallback; missing inherited color uses white. Explicit artwork configuration wins. Artwork is decorative; the shell retains the Badge STATUS semantic. The descriptor is not modified. Structural invalidity returns `submitted=false` without calling content. Content and shell are submitted before Icon validates/prepares artwork; an artwork error returns `submitted=true` with `icon_error` and keeps that composition. This is not an atomic rollback or a promise that the Core frame succeeded. State masks must survive rendering; collect/destroy only after returned draw lists are no longer used. Options/style/constraints are read synchronously. The default shell maps source `theme.red` to CUI `theme.danger`; custom color remains explicit. ```c cui_badge_options badge = cui_badge_defaults(); badge.variant = CUI_BADGE_ICON; cui_badge_icon_content artwork = { .state = &caller_owned_icon, .options = {.size = CUI_ICON_CUSTOM, .custom_size = 20, .custom_color = true, .color = {240, 120, 30, 255}, .custom_transform = true, .transform = {0, 1, -1, 0, 0, 0}}}; cui_badge_result result = cui_badge_with_icon( ui, badge_id, &theme, badge, &artwork, child_content, child_user); /* Handle result.icon_error separately from Core frame completion. */ ``` The first focused worker C11 strict compile and private-Xvfb test passed. It compared software pixels with an independent ordinary Icon tree and checked frozen old-route scenes and retained old-mask rendering. Descriptor sizes were measured as 136 bytes native/104 WASM32; WASM was a header probe only. The root configured build and expanded headless fixture also pass: nested interactive children, narrow/wide resize, omission/reappearance and resource-error recovery. Exhaustive allocation failures, generated consumers and browser acceptance remain open. Foreign configured Badge authoring is still unavailable; this does not complete the frozen family. --- ## Typed Base Slider (unreleased, C only) Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BASE_SLIDER_MODEL.md # Typed Base Slider (unreleased, C only) Include ``. This additive route owns its fixed-size root, track, fill and thumb boxes. It implements Single/Range double-valued input and plain Base painting, independently of legacy `cui_slider`, `cui_base_slider_events` and their snapshot/callback behavior. The separate [Styled C presenter](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/STYLED_SLIDER_MODEL.md) adds palette/source styling, motion and focus rings. Direct C model/state/result structs are not foreign-language records; the [Python bridge-owned controlled subset](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PYTHON_SLIDER_MODEL.md) exposes copied double Single/Range proposals and explicit receipt acceptance. The [Rust bridge subset](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/RUST_SLIDER_MODEL.md) adds owned copied requests and a restricted callback context; Linux dynamic and matching bundled-static checks passed on1.99.1, with MSRV1.85.1 pending. Native numeric host delivery remains pending. The whole Slider family remains partial. The complete, independently runnable C11 example is [`examples/slider_model_controlled.c`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/slider_model_controlled.c). It defines persistent application/reducer state, the actual `on_request` callback, `compose`, and a headless `main`; there are no undefined callback or userdata placeholders. Initialize once, then call the same compose function from your host's frame loop. The example renders no native window and needs no font. Its two queued Left keys explicitly accept .625 then .5 while both requests keep current=.75. Expected output: `Selection [0.250, 0.500]; accepted 2 requests`. A GUI host consumes the real draw list before the next begin. Use the private Xvfb wrapper for automated Linux execution, including this windowless example. The callback accepts UPDATE into external `confirmed` storage only; it never mutates the active reducer/options/UI. It deliberately does not accept CANCEL: that request can contain the captured pair from an old domain or kind. Initialize state once, not inside each frame. Exact v1 sizes/tags and zero reserved fields are required. The domain and value rules are in [SLIDER_MODEL_VALUES.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SLIDER_MODEL_VALUES.md). No allocation belongs to the model; opting writable semantics into Core numeric capabilities can lazily allocate Core's separately bounded numeric storage. Strings, callback and user are borrowed through the synchronous call. Copies of requests own all fields and survive the context. The callback may mutate external owner/userdata and enqueue application work; it must not mutate active UI/state/options/layout or borrowed strings, recurse, destroy the context or free active storage. `current` is the immutable confirmed entry for the whole call. `requested` evolves in original event order, independently of acceptance: two Right keys from .25 with step .125 propose .375 then .5 even if neither is accepted. Each idle key/numeric command emits BEGIN(previous intention), UPDATE(next), COMMIT(next). Pointer down emits BEGIN and UPDATE; each move/up emits UPDATE, and up then COMMIT. Accept values explicitly; the reducer never writes or rereads the owner. Idle intention is discarded at return. Only an ongoing pointer preview persists. Metadata retains the actual Core target/index/source; lifecycle cancellation without a genuine event has unknown source and no fabricated input. Layout extents are finite positive floats, `cross_extent >= max(track,thumb)` and `0 <= axis_inset < length/2`. Root main extent is length; cross extent is cross_extent. Track is centered across the axis and spans inset..length-inset; thumb centers traverse that same interval. Inset zero permits half a thumb to extend outside root; inset thumb_extent/2 keeps it inside. Vertical values increase bottom to top. Reverse-fill changes only Single fill (endpoint toward maximum), not value mapping, input direction, or Range fill. Only box appearance fields participate: background, border, active border widths/corners and opacity. Caller geometry fields are inactive. Single ignores the entire start-thumb box. Disabled thumbs retain semantic geometry but paint transparently; complete source disabled presentation belongs to the pending Styled route. Input uses the previous completed track/thumb geometry; this call paints actual current geometry after reduction. Current thumb semantics are preregistered, then Core rebinds them to the actual named boxes at end-frame. Root track presses choose the nearest previous visual thumb (exact midpoint chooses END). A newly introduced Range START uses its entry fraction on the previous track. Root capture stays on its original target; the chosen current thumb receives explicit Core focus (`focus_visible=true`). Direct thumb pointer focus retains Core's pointer-focus policy. ROOT-target keys from the original dispatch batch delegate to active thumb (END initially), preserving ROOT in metadata. Home/End and Left/Down versus Right/Up use additive domain steps (or span/100 when step=0), including repeated keys. Logarithmic scale changes visual mapping, not additive keyboard steps. Secondary contacts/buttons and IME-owned keys are not claimed. Numeric capabilities belong only to actual current writable thumbs, never Root or legacy Slider. SET_VALUE uses domain-normalized semantic [0,1], linearly mapped to the domain even when visual scale is logarithmic; the raw double remains in input evidence. Increment/decrement use the same domain step as keys. Claiming input and accepting a proposal are independent. During a pointer gesture the current mask is zero. An own-target numeric event legitimately queued from the prior idle snapshot is explicitly consumed as busy rejection, without request, count or value invention. Foreign, stale, disabled, read-only and modal-ineligible input is not consumed by that shortcut. The real next dragging snapshot publishes cap0, so later enqueue already rejects; tests never fabricate prior capabilities. Same-call down→SET→up tests the busy path: restoring capabilities after up cannot replay consumed SET. Domain/mode changes during a retained gesture emit CANCEL with the unchanged captured pair and captured gesture domain. Following intention uses that pair only if valid in the current kind/domain; otherwise it resets to confirmed entry. Thus domain/mode cancellation can be followed by a real key; SET becomes enqueueable after a fresh idle publication. An INPUT cancel followed by SET is reachable from a prior idle snapshot, and preserves original order. Source-generation-only cancellation keeps captured-start progression when valid. Disabled, read-only, zero span, source replacement, kind/domain/axis change, omission and capture loss end gestures with their typed reason (in that priority order). Missing callback is read-only and silently clears reducer drag. Terminal events in the original batch are processed before final capture-loss detection; same-batch up must not become a synthetic cancel. This route never fabricates physical releases or activation/focus events. Scope Escape remains owned by Core; subsequent capture loss has unknown-input evidence. Input requires `cui_frame_input_snapshot_ready`, ordinary non-inert/non-layout-only composition and existing current/previous modal eligibility. This is prior Core semantic/geometry validity, not renderer or host success. First frame paints geometry without interaction. Existing states submitted during invalid-snapshot recovery paint confirmed geometry but do not renew state frames, consume input or emit requests. A cleared diagnostic cannot revive a failed frame. After a fresh successful geometry frame, the next admitted state frame observes any omission gap and cancels once; geometry-only recovery itself is not an admitted state frame. A callback that causes a diagnostic stops later requests even if it clears it. There is no rollback of already delivered requests/application effects after a later Core failure. Fixed absolute child geometry works with Core V1/V2; this slice introduces no dispatcher or global input policy. `cui_base_slider_model_part_id_v1` returns ROOT=owner and stable TRACK/FILL/ START_THUMB/END_THUMB identities, not presence. Owner zero/unknown tag returns0; Single omits START. Register shadows on emitted named parts after the facade and before end-frame with `cui_element_set_box_shadows`; no glyph or shadow-mask semantics are invented. Invalid admission leaves UI/state/callbacks unchanged; late Core failure is reported separately. See exact ABI/geometry design records in `docs/design/SLIDER_MODEL_ABI_V1.md` and `docs/design/SLIDER_BASE_INTERACTION_V1.md`. The separate [Node/TypeScript bridge-owned controlled subset](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NODE_SLIDER_MODEL.md) also supplies copied requests and explicit full-pair receipt acceptance; it does not bind direct C custom Styled style or motion records. --- ## Owned bridge Icon resources (unreleased) Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_ICON_RESOURCES.md # Owned bridge Icon resources (unreleased) This focused C slice provides reusable app-owned Icon state and copied resource utilities. Worker strict native builds and eight private-display runtime checks passed; native/WASM compile-only layouts preserve all 30 old app offsets and measure an 8-byte app increase on both targets. See the [worker receipt](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/validation/bridge-icon-resources-worker.json). Root strict integration build and 15 targeted headless checks pass, including frozen legacy trace/allocations, old-header consumers and actual owner-thread refusal. All 18 consumer-skill tests and canonical generated checks pass; see [the root receipt](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/validation/bridge-icon-resources-root.json). Configured Badge/standalone configured Icon/Spinner presentation and their five language facades remain pending. Legacy kind 11 text Badge and kind 50 named Icon keep their render paths. All 78 families remain. `cui_bridge_icon_versions()` bit 0 advertises the complete resource group on the existing supported owner-thread build. Default/shared WASM and NO_TLS are not supported; explicit unshared WASM uses the existing Slider opt-in and needs final module validation. `icon_record_size_v1` exposes only LIMITS (3), INFO (4) and BITMAP (5). Future style/options/Badge record kinds return 0; those declarations and Badge capability await their real parser/render consumer, including debug-placeholder. Create an app-scoped slot/generation handle with `icon_create_v1` and an initialized limits record. Zero limits normalize to the C defaults **before** reservation: 256 KiB SVG, 1M pixels, 8 MiB cache, 16 versions. The C ceilings remain 1 MiB SVG, 16M pixels, 64 MiB cache, 128 versions. A lazy pool starts with 8 slots and grows to 128. No pool allocation occurs on old routes; the opaque app gains one appended pointer whose byte cost is measured as +8 on native and WASM32. Native C callers must use the matching app; coincident handles from different apps cannot be distinguished. Foreign wrappers must strongly retain/check app identity before C calls. Limits, info and copied-bitmap records are native-endian fixed-width records with exact size/version 1. No C struct is implicitly a little-endian network wire. Getters require only initialized size/version headers; other prior output bytes are ignored, and success writes canonical zero reserved fields. INPUT reserved words reject. All errors except documented CAPACITY preserve outputs. Strings and SVG are copied strict UTF8 without embedded NUL; name/path <= 4096 bytes, data <=max_svg_bytes. EMPTY calls set_empty; NAME uses C catalog/alias lookup and its canonical loader path; PATH retains its exact supplied key; DATA copies raw bytes. Empty NAME reports EMPTY with exact NOT_FOUND in info and preserves old source; empty PATH/DATA preserve C's empty behavior. No guessed name/path conversion. The C-owned resource-local path map overrides embedded assets, with copied keys and SVG, max 128 entries. Put/remove/clear invalidate preparation and advance the nonzero source revision. No foreign callback, file or network access occurs during Core. Arbitrary deferred C loader callbacks are not exposed. Reload keeps the source and marks it dirty. Prepare returns bridge OK plus the exact Icon error; that includes NOT_FOUND/PARSE/LIMIT/ALLOCATION and does not promise a new bitmap. After a failed prepare the C state can still expose its earlier active mask; callers must check prepare's error before treating a bitmap as new artwork. `icon_bitmap_copy_v1` copies packed straight RGBA8 rows and paint bounds; empty state is canonical zero. No returned pixel pointer borrows native storage. Catalog name/path/default and embedded SVG utilities likewise copy. String required sizes include NUL; bitmap required is pixels only. CAPACITY writes only required sizes (both for catalog), never partial destinations. Known input/output ranges have checked uintptr intervals and pairwise exclusions **before any writes**, including capacity paths. Valid stable readable/writable storage and disjointness from the entire opaque app/resource graph remain caller preconditions; this is not a full validator for arbitrary native pointers. No aliasing model is inferred from JS. Admission reserves sum cache quotas <=64 MiB. Source admission uses sum SVG quotas plus retained copied source/map reservations <=8 MiB. It counts the bridge request copy and the native C source separately; shrinking max_svg never releases a still owned source reservation. PATH/DATA reserve exact native length+NUL; NAME reserves 4097 bytes conservatively for C's canonical path without duplicating alias rules. Replacement checks old+new bridge and native source copies while both may be live; map replacement likewise needs old+new payload headroom. This bounds admitted payload reservations, not parser/document/rasterizer/allocator overhead or total process memory. Native allocation failure preserves prior owned source/map. Caller precondition: serialize all app calls, including existing void destruction, on the original owner thread. New resource APIs reject step/render phases; resource operations hold an owner busy guard. Destroy rejects references; current resource-only clients cannot attach node references yet. Generations advance on slot reuse and retire on wrap. Collect frees inactive masks only after the caller has consumed all prior draws. Source replacement keeps old masks alive. Close makes resource calls CLOSED; final app destroy releases resources once after synchronous bridge rendering has returned. No asynchronous borrowed-list consumer contract is added. `cui_bridge_destroy` during a resource operation is a no-op and must be retried, consistent with retaining the outer operation's storage. Executed focused fixtures cover independent ordinary Icon pixels, copied-source replacement/old masks, catalog authority, map fallback/reload/parse error, zero normalization, actual retained-source shrink and exact 8 MiB boundaries, temporary replacement headroom, stale/refcount/phase/busy/close, allocation failures and known-range aliases/overflow on success and capacity paths. Compile-only native/ WASM app layout compares every old field with frozen `dbfb7945`; C/C++ public record fixtures assert all offsets. Root owns CMake registration and canonical metadata/generation. Worker legacy checks preserve the frozen all-command/ nontext-pixel trace, old-header behavior and four constructor allocation calls (only app bytes+8). Text bytes are compared, not text raster pixels. No complete configured Badge or published-package claim follows from this focused resource result. --- ## Typed semantic part shadows Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_PART_SHADOWS.md # Typed semantic part shadows Development additions after alpha.3: use a matching current source checkout and headers/facades. These APIs are absent from the published alpha.3 packages. The additive target V1 API styles a bounded set of existing component surfaces. It does not expand the old six-root `box_shadows` allowlist, name every component part, or provide a style cascade. Focused portable implementation checks pass; integration remains pending. See the [review checkpoint](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/BRIDGE_PART_SHADOW_AUTHORING.md) for decisions. | Direct bridge node | ROOT | MAIN alias | Additional roles | | --- | --- | --- | --- | | Row, Column, Label, Button, Badge, Input | Existing root | ROOT | None | | Checkbox, individual Radio | Whole label row | INDICATOR | INDICATOR | | Switch | Whole label row | TRACK | TRACK, THUMB | | Slider | Framed label/control | TRACK | TRACK only; no thumb exists | | RadioGroup | Group container | Unsupported | None | | ITEM immediately owned by RadioGroup | Item label row | INDICATOR | INDICATOR | The first target API accepts ordinary Row/Column ancestor paths. A RadioGroup ITEM permits its immediate group parent and Row/Column ancestors above that. Settings-owned fields, other ITEM owners, panel callbacks, portals and unlisted kinds remain unsupported. A semantic handle with the same component name is not proof that its owner uses the direct painter. Query the mounted node's capability. This topology check applies only to the new target operations; old six-root setters retain their existing contract. ROOT never silently selects an indicator. MAIN aliases exactly one physical slot; setting/resetting either spelling changes that same slot. ROOT and each other physical role are independent. Each list copies at most eight mixed DROP/INSET layers and explicit TL/TR/BL/BR radii. Numeric colors are0xRRGGBBAA. Reuse [typed values and canonical CSS/preset factories](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_SHADOWS.md); sigma and CSS blur radius retain their distinct meanings. No radii are inferred from theme or control state. Empty lists and preset NONE explicitly suppress both shadow kinds; reset removes an override and restores defaults. Explicit empty indicator styles still opt into the named C painter. Reset returns standalone Checkbox/Radio to the legacy anonymous indicator route even when a ROOT override remains. ## RadioGroup identity boundary When any ITEM indicator has an authored override, including empty, the group uses one `cui_radio_group_with_parts` call and names **every** current peer indicator. Only authored targets receive overrides. Unstyled peer paint identities and explicit-ID registration/capacity costs change in that opted-in group, while their normal layer defaults remain intact. ROOT-only styles do not activate naming. The last indicator reset or removal returns the group to its legacy anonymous route. Reorder associates styles/derived IDs with stable retained item identity, not array position. No partial-naming C API or per-item interactive Radio reducer is introduced. ## C bridge record With a live bridge node handle in the documented topology, query capability before requesting an indicator override. Values are copied; keep ordinary status handling and check the later frame result independently: ```c cui_bridge_shadow_target_v1 target = {sizeof(target), 1, CUI_BRIDGE_SHADOW_INDICATOR, 0}; cui_bridge_shadow_target_info_v1 info; cui_bridge_status status = cui_bridge_shadow_target_query_v1( app, node, sizeof(target), &target, sizeof(info), &info); if (status == CUI_BRIDGE_OK && (info.flags & CUI_BRIDGE_SHADOW_SUPPORTED)) { cui_bridge_box_shadows_v1 style; status = cui_bridge_shadow_preset_v1(4 /* MD */, 3, 3, 3, 3, sizeof(style), &style); if (status == CUI_BRIDGE_OK) status = cui_bridge_set_target_box_shadows_v1(app, node, sizeof(target), &target, sizeof(style), &style); } ``` A successful query with flags0 is declared unsupported, not a temporarily missing indicator. Reset uses `cui_bridge_reset_target_box_shadows_v1` with the same descriptor. Style count0 is explicit suppression rather than reset. ## Python ```python from cui_bridge import (App, BoxShadow, ShadowPart, ShadowPreset, checkbox, column, radio_group, item) check = checkbox('check', 'Check').part_shadows( ShadowPart.MAIN, [BoxShadow.css(0, 1, 8, rgba=0x00000060)]) choice = item('a', 'Choice').part_shadows(ShadowPart.INDICATOR, []) with App() as app: app.mount(column().children(check, radio_group('g').children(choice))) info = check.shadow_target(ShadowPart.MAIN) # capability, before first paint assert info.supported and info.canonical_part == ShadowPart.INDICATOR app.step() check.part_shadow_preset(ShadowPart.ROOT, ShadowPreset.SM) check.reset_part_shadows(ShadowPart.MAIN) app.step() ``` Python immutable CSS/preset requests normalize through the owning App's selected library during mount/update, preserving the existing provider/revision contract. An unmounted generic ITEM can store a request, but a wrong owner fails mounting with the existing rollback rules. Query requires a mounted node; no implicit App or globally loaded library is created. ## JavaScript and TypeScript ```javascript const {App, ShadowPart: P, BoxShadow, checkbox, slider, column, radio_group, radio_item} = require('@cui/native'); const check = checkbox('check', 'Check').part_shadows(P.INDICATOR, [new BoxShadow(0,1,2)]); const choice = radio_item('a', 'Choice').part_shadows(P.MAIN, []); const app = new App(); try { app.mount(column().children(check, slider('value'), radio_group('g').children(choice))); if (check.shadow_target(P.INDICATOR).supported) app.step(); check.part_shadows(P.INDICATOR, []).reset_part_shadows(P.MAIN); app.step(); } finally { app.dispose(); } ``` TypeScript constructor results restrict roles, so Slider THUMB and RadioGroup MAIN fail type checking. `radio_item` is an ITEM authoring convenience requiring RadioGroup ownership at mount; generic `item` makes no typed indicator promise. Runtime ownership validation still applies. JS retains its existing failed-mount App disposal behavior. ## Go ```go layer, err := app.ShadowCSS(0, 1, 8, 0, 0x00000060, cui.ShadowDrop) if err != nil { return err } check := cui.Checkbox("check").Text("Check").PartShadows(cui.ShadowMain, cui.ShadowStyle{Layers: []cui.BoxShadow{layer}}) if err := app.Mount(cui.Column("root").Children(check)); err != nil { return err } info, err := check.ShadowTarget(cui.ShadowIndicator) if err != nil { return err } if !info.Supported() { return fmt.Errorf("unsupported target") } check.PartShadowPreset(cui.ShadowRoot, cui.ShadowSM, cui.CornerRadii{}). ResetPartShadows(cui.ShadowMain) if err := check.Err(); err != nil { return err } return app.Step(.016) ``` Go copies the supplied slice. CSS/preset factories use the owning App; `PartShadowPreset` requires a mounted node. For an unmounted value use `app.ShadowPreset`, then `PartShadows`. New symbols remain optional for default older-library loads; feature use fails explicitly. Go methods retain fluent sticky-error and existing owner-thread rules. ## Rust ```rust let style = ShadowStyle::new(&[BoxShadow::css(0.,1.,8.,0.,0x00000060, ShadowKind::Drop)?], CornerRadii::default())?; app.part_box_shadows(check, ShadowPart::Main, &style)?; assert!(app.shadow_target(check, ShadowPart::Indicator)?.supported()); app.part_shadow_preset(check, ShadowPart::Root, ShadowPreset::SM, CornerRadii::default())?; app.reset_part_box_shadows(check, ShadowPart::Indicator)?; app.step(0.016)?; ``` Rust typed enums/owned styles and fluent Builder methods use the same wire call; app identity, stale handle and Result errors retain their current rules. ## Capability, errors and lifetime The exact C authority is `include/cui/cui_bridge.h`: target/info records are16 bytes with four uint32 fields; layers/styles remain24/224 bytes. Query reports SUPPORTED and NAMED_INDICATOR flags and a canonical role. Unsupported known roles return supported=false; malformed descriptors or stale handles are errors. Query neither allocates nor reports current paint presence. The initial topology has no internally conditional mapped part, so its CONDITIONAL_SUBMISSION flag is0. Unvisited owners and measurement/layout-only work retain values without applying styles or reporting missing paint. Inert ancestry still paints. A mandatory part missing during actual owner submission, identity collision or renderer/layout capacity failure remains a frame failure. It is not silently treated as normal omission. Such late failure may follow Base input reduction/owner callbacks and does not roll back accepted interaction state. No old bounds or semantic lookup is used to decide admission. Each setter validates and acquires storage before committing its one target; invalid or out-of-memory replacement preserves old C/local state. Separate calls are separate transactions. Node/subtree removal frees storage; slot reuse begins with no part overrides. A nullable extension adds8 idle bytes/node on the measured Linux x86-64 ABI: total73,136 versus73,128 previously. Active payloads are232 bytes for one indicator/track or456 for Switch's two parts, excluding allocator metadata. ROOT reuses the existing224-byte inline field; MAIN uses no extra slot. The matching typed modules are `bindings/python/cui_bridge/shadows.py`, `bindings/node/shadows.cjs`, `bindings/go/cui/part_shadows.go` and `bindings/rust/src/part_shadows.rs` plus the shared style modules. Match source, facade and runtime revisions; installed-skill resources do not upgrade an older app. Existing Core clipping, opacity and renderer budgets remain in [ELEMENT_SHADOWS.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/ELEMENT_SHADOWS.md). Browser/GPU, other compound parts and remaining78-family coverage are separate pending work. ## Validation boundaries The focused C fixture checks actual software part-only paint/reset, unchanged root geometry/semantic counts and queued activation, all64 group peer identities, ROOT-only legacy anonymity, last reset/removal, unsupported topology with old six-root behavior preserved, no-allocation query, failed initial allocation, invalid replacement, reuse/destruction, inert/measurement/layout-only/omission and unexpected mandatory-part failure/recovery. It compares fontless box paint only; text/glyph rendering, browser and GPU proof are not added here. Python, JS, Go and Rust runtime regressions cover owned values, aliases, capability/geometry, callbacks and lifetime/rollback. Python optional-symbol proxies and actual older Go/Rust libraries exercise feature failure without breaking default loads. Strict TypeScript checks cover role restrictions. Reproduce with the same focused build and private display wrapper: ```sh nice -n 19 taskset -c 0 cmake --build "$BUILD" --parallel 1 --target test_bridge_part_shadows cui_bridge nice -n 19 taskset -c 0 python scripts/test_local.py --build-dir "$BUILD" -R '^bridge_(part_shadows|python_part_shadows)$' -j1 nice -n 19 taskset -c 0 python scripts/test_shadow_runtimes.py --build-dir "$BUILD" --parts --old-library "$OLD_BRIDGE" ``` The helper reuses the existing shared bridge and build directory, compiles only the N-API adapter and required Go/Rust facade tests, uses Go `cui_dynamic`, and runs offline/single-job via private-Xvfb CTest entries. Static source-package closure and other platforms remain CI checks rather than extra local CUI builds. --- ## Typed root shadows in language builders Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_SHADOWS.md # Typed root shadows in language builders The additive bridge V1 implementation targets only Row, Column, Label, Button, Input and Badge paint roots. This is two authoring containers and four catalog families. Compound indicators, tracks, repeated items, popup panels, triggers, backdrops and every other node kind remain unsupported. Bundled C headers do not expand that typed scope. Focused Linux portable software and all five facade checks pass for this bounded subset. Integration into a released candidate remains pending. A style owns at most eight mixed DROP/INSET layers and four explicit corner radii. Ordinary layers use Gaussian sigma; the separate CSS factory accepts blur radius and delegates radius/2 conversion to Core. Presets also delegate to Core, with no language-specific preset math. Numeric packed colors are `0xRRGGBBAA`. The typed facades reject nonfinite values, float32 overflow, sigma outside[0,256], offsets/spread outside[-4096,4096], CSS radius outside[0,512], radii outside[0,16384] and more than eight layers. Authoring copies arrays/slices and values before returning, including before mount. No caller-owned layer buffer is retained by the bridge. Successful set replaces the entire list; rejected replacements preserve it. `box_shadows([])` (or an empty typed style) and preset NONE explicitly suppress both DROP/INSET on every following frame. Reset removes the override and restores component defaults. Node/subtree removal and app destruction follow existing stale-handle and disposed-object rules; recycled slots start without an override. The bridge stores 224 bytes per node (73,128 bytes for the complete private node on the validated Linux x86-64 build) and applies the retained value after the owner finishes submitting each real painted frame. Existing component defaults run first. Inert ancestry still paints; measurement/layout-only work does not apply decoration. Style changes neither layout, hit regions, focus, semantics nor input consumption. A missing expected root is a frame error. Radii are explicit; presets do not guess theme/state-dependent component radii. The Core paint, clipping, resource and renderer limits remain in [ELEMENT_SHADOWS.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/ELEMENT_SHADOWS.md). Python values are immutable and sequences are copied: ```python from cui_bridge import (App, BoxShadow, ShadowKind, ShadowPreset, CornerRadii, button, column) radii = CornerRadii(4, 4, 4, 4) layer = BoxShadow.css(0, 2, 8, -1, rgba=0x00000040) node = button("save").label("Save").box_shadows( [layer, BoxShadow(sigma=1, kind=ShadowKind.INSET)], radii) with App(width=360, height=240) as app: app.mount(column().children(node)) app.step() node.shadow_preset(ShadowPreset.MD, radii) node.box_shadows([]) # explicit suppression node.reset_box_shadows() # restore defaults app.step() ``` Python CSS/preset values are immutable requests, normalized through the mounting or updating App's own bridge. They never implicitly load a different default library. Go factory methods require an active App; its loader enforces one library identity. JS uses its one addon/runtime and Rust its linked runtime. Python and Go preserve old default library loads; requesting the new feature against an older library fails explicitly. Match generated headers, facade and runtime artifacts. ABI version1 alone does not prove new symbols exist. JavaScript and TypeScript share the same validated runtime and immutable values: ```javascript const {App, BoxShadow, ShadowKind, ShadowPreset, CornerRadii, button, column} = require('@cui/native'); const radii = new CornerRadii(4, 4, 4, 4); const node = button('save').label('Save').box_shadows([ BoxShadow.css(0, 2, 8, -1, 0x00000040), new BoxShadow(0, 0, 1, 0, ShadowKind.INSET) ], radii); const app = new App({width:360, height:240}); try { app.mount(column().children(node)); app.step(); node.shadow_preset(ShadowPreset.MD, radii); node.box_shadows([]); node.reset_box_shadows(); app.step(); } finally { app.dispose(); } ``` The TypeScript constructor results expose styling only for the six supported kinds; shared Label/Input interfaces do not grant it to derived compound controls. Go factory methods use the creating App's loaded bridge; all mutations stay on its existing owner thread. `BoxShadows` copies the supplied style's layer slice: ```go radii := cui.CornerRadii{TopLeft:4, TopRight:4, BottomLeft:4, BottomRight:4} layer, err := app.ShadowCSS(0, 2, 8, -1, 0x00000040, cui.ShadowDrop) if err != nil { return err } node := cui.Button("save").Text("Save").BoxShadows(cui.ShadowStyle{ Layers: []cui.BoxShadow{layer, {Kind:cui.ShadowInset, Sigma:1, RGBA:0x00000040}}, Radii: radii, }) if err := app.Mount(cui.Column("root").Children(node)); err != nil { return err } preset, err := app.ShadowPreset(cui.ShadowMD, radii) if err != nil { return err } node.BoxShadows(preset).BoxShadows(cui.ShadowStyle{}).ResetBoxShadows() if err := node.Err(); err != nil { return err } return app.Step(.016) ``` Rust uses typed enums and owned safe values, with a separate fixed-layout FFI record. `App::box_shadows` and fluent Builder methods use the same copying bridge: ```rust let radii = CornerRadii { top_left:4., top_right:4., bottom_left:4., bottom_right:4. }; let layer = BoxShadow::css(0., 2., 8., -1., 0x00000040, ShadowKind::Drop)?; let style = ShadowStyle::new(&[layer], radii)?; app.box_shadows(button, &style)?; app.shadow_preset(button, ShadowPreset::MD, radii)?; app.box_shadows(button, &ShadowStyle::new(&[], radii)?)?; app.reset_box_shadows(button)?; app.step(0.016)?; ``` This follows existing setter/callback mutation rules; no new callback phase or notification category is introduced. See the signed V1 checkpoint in [BRIDGE_ELEMENT_SHADOW_AUTHORING.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/BRIDGE_ELEMENT_SHADOW_AUTHORING.md) for exact sizes, offsets, capability query, error precedence and deferred mapping. For agent discovery, read the exact bridge header and typed definition modules: `include/cui/cui_bridge.h`, `bindings/python/cui_bridge/shadows.py`, `bindings/node/shadows.cjs`, `bindings/typescript/index.d.ts`, `bindings/rust/src/shadows.rs`. The consumer skill exports these narrowly selected definitions; inspect the matching checked-out `bindings/go/cui/native.go` for Go value/method declarations; C declarations remain authoritative in the bridge header. Pass `--source /path/to/actual-app-cui-source` on helper reads and use facade sources matching that app's pinned revision. A minimal C SDK snapshot alone is not a foreign authoring implementation. Never substitute the installed skill's newer module when the pinned app lacks that API. ## Focused validation Native tests run through the private-Xvfb wrapper; no desktop session is used. The six-root oracle compares box pixels with TEXT commands excluded from the fontless software renderer. Original text command count, copied UTF-8 content, bounds, font size/style/color, overall root geometry and semantic count are checked independently. It does not claim glyph rasterization or hardware GPU proof. Other checks cover replacement/clear/reset, invalid replacement atomicity, eight mixed layers, slot recycling, nested supported roots, measurement/inert/ layout-only/absent passes, missing-target frame errors and unchanged activation. The Python, JS, Go and Rust tests exercise actual runtime ownership, geometry, callbacks and validation. Strict TypeScript checks reject unsupported constructor results. Python tests cover deferred owning-App factory resolution and optional missing symbols; Go and Rust additionally run against an actual older shared library. No browser shadow renderer or cross-platform parity is claimed. Reproduce in one existing portable Release build directory, with local CPU limits: ```sh nice -n 19 taskset -c 0 cmake --build "$BUILD" --parallel 1 --target cui_bridge test_bridge_shadows test_bridge_core test_bridge_components nice -n 19 taskset -c 0 python scripts/test_local.py --build-dir "$BUILD" -R '^(bridge_shadows|bridge_core|bridge_components|bridge_python|bridge_python_shadows)$' -j1 nice -n 19 taskset -c 0 python scripts/test_shadow_runtimes.py --build-dir "$BUILD" --old-library "$OLD_BRIDGE" ``` The focused runtime helper compiles only the N-API adapter against that already built library, then registers temporary CTest entries inside the same directory. It uses the private display wrapper, Go's `cui_dynamic` tag, offline single-job Cargo and no dependency downloads. The regular Python/Node/Go/Rust CI suites also include these regression files; TypeScript uses its pinned compiler. The original root setter above keeps its six-kind allowlist. The separate [semantic target API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_PART_SHADOWS.md) adds bounded Checkbox/Radio indicators, Switch track/thumb, Slider track and explicit outer ROOT roles in a reviewed ordinary-tree topology. It does not infer every compound/portal part. --- ## Controlled typed Slider through the C bridge Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_SLIDER_MODEL.md # Controlled typed Slider through the C bridge Unreleased C bridge, Python, Node/TypeScript, Go and Rust subsets. Include `` from the same revision as the library. `cui_bridge_slider_model_versions() & 1` advertises this independent schema; old libraries lack this symbol. Foreign loaders must resolve the entire optional symbol group before use. The [Python controlled builder](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PYTHON_SLIDER_MODEL.md) wraps this route; [Node/TypeScript](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NODE_SLIDER_MODEL.md) uses the same copied C records; [Go](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/GO_SLIDER_MODEL.md) owns value copies with explicit acceptance. The [Rust subset](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/RUST_SLIDER_MODEL.md) uses a restricted callback context; Linux dynamic and matching bundled-static checks passed on1.99.1, with MSRV1.85.1 pending. Existing `slider()` builders keep their scalar float precision, autoacceptance and CHANGE timing. Enable the owned request queue once, then create kind81 with `cui_bridge_slider_model_create_v1(app, parent, key, ...)`. Parent and all ancestors must be Row/Column; there is no implicit root. Generic `node_create` rejects81. The normal bridge owns the UI tree, copied key/name, reducer and presentation state. No model pointer or callback crosses this ABI. ## Values, authoring and lifetime Config, queue options and receipts require exact `sizeof`, schema1 and reserved0; all size arguments are bytes. Unknown enums/flags reject atomically. Domains and values retain doubles: Single ignores `start` and copies it as0; Range requires ordered start/end in the complete domain. Log bounds must be positive. Domain step must be finite/nonnegative; zero means continuous. Source math and its numerical limits are in [the value guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SLIDER_MODEL_VALUES.md). `rem` must be finite/positive; fixed `length` must be finite/positive. Parent-fill ignores and canonicalizes length to0. Both orientations use ordinary source flow; vertical parent-fill inside registered scroll remains unsupported. Reverse changes fill, not numeric direction. Disabled uses `cui_bridge_set_disabled`; readonly, request emission, reduced motion and focus-ring visibility are config flags. Config/direct owner replacement/copied name/changed disabled policy revise receipt authority. Configure retains the reducer so an active gesture can CANCEL against its captured old kind/domain. Never automatically accept CANCEL values under a changed domain. The copied queue is separate from all legacy polling. Capacity is1..4096, default 4096. Before each node reduces input, reserve conservatively `3*frame_events+1` free records; CAPACITY leaves that node's reducer, input and callbacks untouched. Drain backlog before retrying. Already emitted records/application effects are not rolled back when another node or a later Core operation fails. ## Poll, decide and accept After a successful step (or from the existing native `after_frame` callback), poll `cui_bridge_poll_slider_request_v1`. Each result owns every byte, including 64-bit identity, frame/index, raw input evidence and a full Single/Range pair. No pointer is borrowed from the application. Records remain readable after the next frame or destroy. Polling does not accept a value or invoke foreign code. Request `current` is the immutable entry owner snapshot. Repeated original-order keys evolve `requested` intent, even if an earlier proposal was rejected. The owner explicitly accepts a complete valid pair using `cui_bridge_accept_slider_request_v1`; it may instead supply another valid pair. Only actual issued receipts in the latest admitted painted state-frame are accepted, in increasing sequence order. This schedules a future repaint: it does not repaint the already completed frame or enqueue CHANGE. Reject by doing nothing. There is no rollback/replay of input or already accepted work. Ordinary subsequent submission, omission, removal/reuse, configuration/source replacement or invalid Core geometry expires authority. A live expired queued record remains readable; polling prunes removed origins. Invalid size preserves queue/output; EMPTY and failures preserve output. Clearing an error does not restore an invalid semantic snapshot. Geometry-only recovery does not renew model state-frame authority. All app access is serialized on the owner OS thread, which stays alive through destroy. Successful enable captures the TLS owner; later normal/typed ready operations reject another thread. No migration/concurrent destruction is supported. Do not nest step/run during native after-frame dispatch. Future foreign callbacks must copy records before calling users, hold no mutable runtime borrow, catch exceptions before returning through C, and preserve existing legacy dispatch timing. This slice adds no foreign callback. App handles and copied receipts stay within the matching loaded bridge image or WASM module instance. Epoch uniqueness is scoped to that image/instance, including all of its apps; independently loaded duplicate libraries/modules have separate counters. Cross-image receipt mixing is unsupported. These checks validate ordinary ownership and issued authority; they are not a security boundary against malicious in-process callers. `get_presentation` copies actual completed render status, absolute accumulated Core time and passive deadline. Hosts coalesce `host_now + max(0, next_wake_seconds - core_time)` with their own deadlines. Part bounds report actual completed geometry, not ID-derived presence; absent parts return EMPTY unchanged. Thumb bounds describe the outer rem-sized interaction/layout box, not the inner `rem-2` surface or outward rings. Disabled thumb paint is omitted, while disabled track/fill bounds remain available. Neither observation certifies renderer/native AT success. The current bridge uses V1 solid presentation; no V2 gradient adapter, typed-part shadow authoring or native numeric AT delivery is added. ## Target policy Native C11 TLS/atomic-flag targets are supported. Default WASM and threaded/shared WASM report versions0 and reject new operations with BACKEND_UNAVAILABLE. An explicit trusted **unshared final module** build may opt in, following the exact [reviewed build and final-memory verification policy](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/BRIDGE_SLIDER_MODEL_V1.md). Compile the actual bridge TU with `-DCUI_BRIDGE_SLIDER_WASM_UNSHARED=1`, without atomics or reentrant/thread flags. Do not distribute an opted-in archive as if unrelated final consumers were already verified. Every final module must pass its normal engine validation and `python scripts/verify_slider_unshared_wasm.py FINAL.wasm` after linking and any transformation. The script inspects memory descriptors; it is not a complete WASM validator or automatic CMake capability negotiation. No shared-Worker TLS claim. The final host must independently check that its actual `Memory.buffer` is not a `SharedArrayBuffer`; repeat verification after relinking, embedding or transforming. Actual C tests compose nested Row/Column Single/Range UIs in both orientations, deliver pointer/keyboard events, and explicitly accept copied requests. The internal test additionally exercises the actual Core typed SET channel; that is not a public bridge SET-injection API or physical AT proof. ## Complete portable example Copy [the complete C program](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/bridge/examples/slider_model.c). It composes a label and real Range UI, delivers a pointer focus and keyboard input, prints current/requested complete pairs, and either accepts UPDATE explicitly or rejects all proposals. It needs no desktop window, renderer or font. With the [C11, CMake and Ninja prerequisites](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DEPENDENCIES.md), from the checkout: ```sh cmake -S . -B build -G Ninja -DCUI_BUILD_NATIVE=OFF -DCUI_BUILD_BRIDGE=ON cmake --build build --target bridge_slider_model_example ./build/bridge_slider_model_example ./build/bridge_slider_model_example --reject ``` These direct executions are windowless. Other native automated checks use `python scripts/test_local.py --build-dir build`; never substitute the desktop display. The example demonstrates this C ABI, not an already implemented foreign builder or native accessibility adapter. ### Binding domain validation Python, JS/TS and Go validate the C domain contract before storing a builder configuration: endpoints and step must be finite, the span `maximum - minimum` must remain finite, and step must be nonnegative. Linear domains allow equal endpoints. Logarithmic domains require `0 < minimum < maximum`. Rejected pending configuration changes leave the prior configuration unchanged; valid domains retain their existing behavior. Rust controlled authoring remains pending. ### Remaining copied-wire checks The matching C producer emits canonical owned records, but malformed-provider rejection is not yet uniform across bindings. Python still lacks some absent input, repeat, coordinate and source-evidence checks; Go and JS/TS still lack the inactive numeric-value check. See the [conformance audit](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SLIDER_BINDING_WIRE_CONFORMANCE.md). These remain explicit follow-up work; existing UI tests do not prove complete wire conformance or native accessibility delivery. --- ## Localized TimeField bridge (focused C proof, unreleased) Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_TIME_FIELD_LOCALIZED.md # Localized TimeField bridge (focused C proof, unreleased) The additive C bridge has passed focused strict C/C++ compilation, headless UI, thread/queue/failure fixtures and matching Linux static example checks. The independent frozen legacy trace matches exactly under private Xvfb. Pinned WASM checks are compile-only. See the [first receipt](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/validation/time-field-bridge-first.json) for initial failures and exact limits. Canonical generation, complete integration and package gates remain pending; this is not released package functionality. The existing tested scalar builders in all five languages remain unchanged; none yet exposes this localized bridge mode. See the [reviewed contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/TIME_FIELD_BINDING_CHECKPOINT.md) and [direct C widget guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TIME_FIELD_LOCALIZED.md). The [complete C program](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/bridge/examples/time_field_localized.c) authors two real TimeFields inside Row/Column UI, English24-hour and Arabic12-hour, with independent state, explicit same-day08:00–18:00 bounds, a summary label, clear-validation, read-only, disabled and bounds-toggle buttons. It queues deterministic host pointer/text input and drains copied changes after step, updating sibling text from application state. Its default backend is windowless. Optional `--native` uses the same authored tree and dispatch through the existing SDL bridge runner, with real host input and no scripted edits. The headless path passed focused compile/runtime checks. Native interactive launch remains untested. When reproducing the focused gate, the intended reproducible invocation is: ```sh cmake -S . -B build -G Ninja -DCUI_BUILD_NATIVE=OFF -DCUI_BUILD_BRIDGE=ON cmake --build build --target bridge_time_field_example --parallel 1 python scripts/test_local.py --build-dir build -R '^bridge_time_field_example$' ``` For an intentional interactive launch after validation, the prepared native path uses the existing SDL/text adapters and an explicit font (no headless fallback): ```sh cmake -S . -B build -G Ninja -DCUI_BUILD_NATIVE=ON -DCUI_REQUIRE_NATIVE=ON -DCUI_BUILD_BRIDGE=ON cmake --build build --target bridge_time_field_example --parallel 1 CUI_TEST_FONT=/absolute/path/font.ttf ./build/bridge_time_field_example --native ``` This is a manual interactive invocation, **not** an automated desktop test. It has not been executed. Automated native validation must remain under the private Xvfb wrapper and needs its own bounded close/input fixture before registration. The native callback drains owned observations and handles real button clicks without nesting step/run. Headless success will not imply native proof. Use existing build directories/caches where possible. CMake, Ninja, Python3 and a C11 toolchain are required; see [dependencies](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DEPENDENCIES.md). The worker used equivalent strict cached-engine compilation to avoid a139-step engine rebuild; the exact CMake target commands remain integrator acceptance. Native automated checks always use the private-display wrapper, never the maintainer desktop. Include `cui/cui_bridge.h`. Check `cui_bridge_time_field_versions()` bit0 and all three size functions before enabling mode. The complete optional group comprises `cui_bridge_time_field_versions`, `cui_bridge_time_field_config_size_v1`, `cui_bridge_time_field_result_size_v1`, `cui_bridge_time_field_change_size_v1`, `cui_bridge_time_field_enable_v1`, `cui_bridge_time_field_configure_v1`, `cui_bridge_time_field_get_config_v1`, `cui_bridge_time_field_get_result_v1`, `cui_bridge_time_field_clear_validation_v1` and `cui_bridge_time_field_poll_change_v1`. Future language loaders must resolve the whole group optionally; existing old-library scalar authoring must remain usable. This document does not provide those future wrappers. Enable once with immutable capacity1–4096 (0 selects4096). Configure an existing kind55 TimeField node to opt in permanently; unconfigured nodes use their legacy rendering and ASCII generic CHANGE payloads. Localized nodes produce a separate typed FIFO, never duplicate generic time CHANGE events. Scalar `set_time/get_time` continue to use their existing records and validation. Owner values outside new bounds are not clamped; precision/domain validation remains the landed widget's contract, rather than a new setter coercion. Configuration is an owned616-byte record, result80 bytes and change64 bytes on the proposed supported target ABIs, pending target measurements. Set exact `struct_size` and version1. All configuration reserved fields and unused bytes are zero. Fourteen explicit tokens (digits0–9, separator, period separator, AM, PM) are strict prefix-free UTF-8, nonempty and at most16 bytes each without NUL. Four segment names are0–64 bytes; empty selects the C name. No locale registry, normalization or automatic case/space guessing exists. Bounds are same-day and inclusive; inactive bound values are canonically zero. Minute precision requires seconds0 in active bounds and valid model values. Complete formatted TEXT is limited to160 bytes independently of the bridge's4096-byte queue-text bound. Configure copies every token/name byte; temporary caller buffers can be released after return. Bridge owns state and time. Keep nonzero `edit_generation` stable for identical owner echoes, increment it for locale/name/domain replacements that must reset unfinished input on the next ordinary writable submission. Cycle, precision or changed owner time also follows the existing C widget reset rules. `clear_validation` changes only transient validation: it does not alter time, pending/digit state or the independent owner-invalid flag. Direct borrowed C widget state/options are not foreign records. Drain changes between steps. Every configured live localized node reserves one possible observation before time advancement, native polling, Core begin or input mutation, including disabled/detached/omitted nodes. Insufficient free capacity returns CAPACITY without consuming input or changing values/drafts. Configure rejects a live-node count greater than capacity; increasing capacity requires a new app, not an implicit queue resize. Removed records are pruned when polled; slot reuse cannot redirect an old observation to a replacement node. A change is one copied **applied aggregate** previous/final pair, not an owner proposal to accept again. Net-zero edits produce no change. Result `changed` is net value difference, `rejected_count` counts rejected original input events and `queued_change_count` is0/1 queue production, not foreign callback invocation count. Result `status` describes the widget operation; `validation` describes edit rejection. `frame_status` records final bridge step status after rendering. A later frame failure retains already applied changes with non-OK frame status; it does not prove paint succeeded or undo model/input effects. Explicitly poll even after step errors if those observations matter. Latest-result getter returns CORE_ERROR after failed submission and cannot be revived by clearing diagnostics or a geometry-only recovery; it requires a healthy ordinary widget state-frame. Ordinary omission makes a formerly current result unavailable. Output getters/poll require initialized exact size/version; other previous output bytes are ignored. Failure leaves the output unchanged. Poll copies and consumes only on OK; retaining that copy after app destruction is safe. No borrowed C view may cross application callbacks. Callbacks are application dispatch after step, not inside Core. The example's local C dispatch function illustrates this boundary; Python's later typed dispatch will require its own teardown/exception tests. Successful enable opts the app into the existing private owner-thread check, without enabling Slider. Owner OS thread must remain alive through destroy, all calls serialized; destroy is unchecked/void, not concurrent-safe. Native NO_TLS and default/shared-memory WASM are unsupported. Explicit unshared WASM reuses the existing trusted assertion plus **final-module** verification recipe; no new shared-memory guarantee is implied. Public support remains unvalidated here. Still required: matching C target/runtime/failure/legacy proof, Python delivery with complete actual UI and optional-symbol fallback, then JS/TS, Go and Rust; direct foreign Base/Styled state/style bindings, IME/clipboard integration, source one-root focus parity and physical native accessibility remain separate. ## Source packaging and portable closure (audit, not validation) The new private `src/bridge/cui_bridge_time_internal.h` is included by the bridge translation unit. It is a tracked `src/` file: `scripts/generate_go_sdk.py` includes it automatically in both Go and Rust SDK snapshots and their SHA256 manifests. No new portable engine module or standalone `.c` source-list entry is needed. The Go bridge wrapper includes the bridge TU; matching Rust packaging compiles that same TU against its staged SDK. This does not expose localized APIs through those language builders. Regenerate SDKs only at the authorized canonical gate; currently committed SDK copies intentionally remain stale relative to this draft. Python/Node source package snapshots include tracked `src/`, `include/`, tests, examples and CMake files, and their source manifest hashes every copied file. The new header and fixture/example paths must be committed before generation or packaging; untracked files are intentionally omitted. Go/Rust package staging runs SDK `--check` and therefore must not claim closure before regeneration and matching-source checks. Provenance remains generated, not edited by hand. Bridge is separately compiled/linked and is not an amalgamation module in `cmake/sources.json`. Do not add this private helper to the distribution umbrella or claim a standalone header-only bridge. The landed localized widget's portable sources are already in the canonical module list; source bridge tests link that actual implementation, rather than introduce another state/layout copy. Prepared durable checks: `bridge_time_field_source_closure` exercises actual SDK snapshot and Python/Node source-copy producers on a bounded temporary tracked-file fixture and checks the real private-header bytes/hash. CMake registers source header C++11 consumers in both include orders when C++ is already enabled. `bridge_time_field_example_static` separately links the actual bridge TU and C example with the engine on Linux, without SDL; it is not Go/Rust installed-package proof. Native ILP32 ABI remains an explicit target probe, not inferred from LP64. The intended pinned WASM compile-only probe is: ```sh python tests/fixtures/time_field_bridge/portable.py --zig /absolute/path/to/pinned/zig --build-dir build ``` It checks Zig0.16.0 and compiles ABI plus actual bridge TUs for default, asserted unshared and atomics/shared-unsupported policies, sequentially with strict C11 warnings. It does not link/run, verify final memory or claim shared-memory support. The worker ran the closure fixture, both C++ orders, Linux static example and all four pinned WASM compile objects. Native ILP32, installed SDK rebuild and final unshared module verification remain pending for this new route. The optional `bridge_time_field_frozen_wrapped` CMake test requires `CUI_TIME_FIELD_FROZEN_LEGACY_EXECUTABLE` and `CUI_TIME_FIELD_FROZEN_LEGACY_LIBRARY_DIR`; it uses the committed comparison runner inside the private wrapper. Worker equivalent scratch registration passed; the integrator must validate the durable CMake registration. ## Geometry and deterministic headless input A newly mounted localized field needs ordinary host frames to establish current layout and an admitted input snapshot. Its latest-result getter can return INVALID_STATE before that readiness; bounds alone do not prove input admission. The complete examples warm ordinary frames and check the public latest result before injecting deterministic pointer/text input. Keep such synchronization bounded in tests; do not add sleeps, replay input or bypass the C reducer. The node bounds describe the compound field, including separators. A center click can land on a noneditable colon in minute precision. Target an actual editable segment when writing synthetic interaction tests. The supplied examples use the first text region and verify applied English/Arabic values plus copied callback outcomes. Native applications use the ordinary host loop and real input; this test setup does not authorize a new dispatch or focus policy. One-root Tab and IME acceptance remain explicit separate gaps. --- ## Buttons Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BUTTON.md # Buttons `cui_button` keeps the default primary style and controlled disabled flag. `cui_button_ex` adds primary, secondary, outline, ghost, destructive and link variants; XSmall/Small/Medium/Large sizes; loading and selected presentation; explicit or growing width; leading/trailing text; and a presentation-content callback. Every variant uses `cui_base_button` for capture, keyboard activation and focus. The content callback should draw presentation without nested interactive controls. At the default 16px theme font, XS/S/M/L heights are 20/24/32/32px, with 12/14/14/16px labels and horizontal padding of 4/8/10/12px. Medium and Large intentionally share a height in the frozen upstream source. These metrics scale with `theme.font_size / 16`; the legacy generic `theme.control_height` and `theme.padding` do not override button size metrics. Text uses a 1.25 line height and the content row is centered vertically without vertical padding reducing the available label space. Set `.icon = cui_string("close")` to add a real SVG icon. With `.icon_only = true`, the button is square and hides the visible label while retaining `name` for accessibility. For example, a Small close button uses a 24px target and a 14px icon. Dialog and sheet close controls use this path. The theme's `icon_loader` can replace that artwork; custom content callbacks remain available for other compositions. ```c if (cui_button_ex(ui, save_id, &theme, cui_string("Save changes"), (cui_button_options){.variant = CUI_BUTTON_OUTLINE, .size = CUI_CONTROL_SMALL, .loading = saving})) { begin_save(); } ``` Loading suppresses activation and focus, draws an animated SVG loader, and exposes an accessible description. Disabled text/background preserve theme contrast; hover/pressed states tint enabled surfaces and keyboard focus has a distinct border. Selected is application-owned presentation; it does not imply a semantic pressed state. For value toggling use `cui_toggle` or the controlled toggle group. With `custom_colors`, `pressed || selected || open` selects `colors.active` (or `outline_active`); otherwise hover selects `hover`, then `normal` is the fallback. A selected/open button therefore keeps its active background while hovered or pressed. Disabled painting takes precedence over those states. Use a custom interactive row when selected, hovered and pressed need independent colors; see [Interaction](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/INTERACTION.md#custom-clickable-rows). Component variants and theme palettes are different enums. Primary maps to `CUI_THEME_BUTTON_PRIMARY`; secondary/danger/warning/success/info map to their namesakes; default/outline map to `CUI_THEME_BUTTON_DEFAULT`. Ghost uses secondary active, accent hover and a transparent normal background; its pressed background comes from default active. Link uses `link`, `link_hover` and `link_active`. There is no `CUI_THEME_BUTTON_GHOST` palette. Set `custom_colors` on a component for a local override instead of copying the theme. Headless tests exercise all nine variants, four sizes and four themes, measured bounds, adornments, content callbacks, semantic names and ordinary push-button state and keyboard suppression while loading. SVG icons, custom palettes and animation are separate pending capabilities; a text adornment does not implement the Icon catalog family. Buttons additionally support warning, success, and info intent variants and extra-small density (`CUI_CONTROL_XSMALL`). The `outline` flag combines with an intent to use its theme color for the border and label on the surface background. The original standalone `CUI_BUTTON_OUTLINE` remains available. Semantic intent foreground tokens are used for filled labels, including `on_danger`. `selected` controls presentation only, matching the frozen reference. It no longer mislabels an ordinary push button as checked; use the separate toggle control for toggle semantics. Full upstream button parity, including independent explicit toggle metadata and richer icon/tooltip/animation options, is still under audit. Tests exercise all variants/densities across four themes plus colored-outline painting, pointer activation and disabled keyboard suppression. ## Bounded paint handlers Use [Button styles](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BUTTON_STYLES.md) for additive instance, hover, active, selected, disabled and focus paint refinements. Explicit masks preserve zero values; callbacks are borrowed pure calculations and cannot change geometry or dispatch input. Legacy submission remains available. --- ## Typed Button artwork Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BUTTON_ARTWORK.md # Typed Button artwork Button can borrow an Icon, Spinner or ProgressCircle descriptor through `leading_artwork`. `loading_artwork` accepts an Icon descriptor. Existing string icons and zero-initialized options retain their behavior. `leading_content` takes priority over both typed slots. The rules come from pinned v0.7.1 `button/button_icon.rs` (`ButtonIconVariant`, `ButtonIcon::render`): loading replaces an ordinary Icon with a Spinner, using its custom loading Icon when provided. An explicit Spinner or ProgressCircle remains that artwork while loading, and ignores the loading replacement. A custom loading Icon rotates with the existing 800ms quadratic Spinner cycle; reduced motion leaves it static. This API does not add menus, progress ownership, or a complete Button source parity claim. ```c static bool save_button(cui_context *ui, cui_id id, const cui_theme *theme, cui_icon_state *mark) { cui_button_artwork leading = { .kind = CUI_BUTTON_ARTWORK_ICON, .icon = mark, .icon_options = {.custom_color = true, .color = {25, 160, 80, 255}} }; return cui_button_ex(ui, id, theme, cui_string("Save"), (cui_button_options){.leading_artwork = &leading}); } ``` Initialize the caller-owned `mark` with `cui_icon_state_init`, then check `cui_icon_set_name(mark, cui_string("check"), NULL, NULL)` before composition. Destroy it with `cui_icon_state_destroy` only after all rendering has completed. The caller owns Icon state and its bounded retained masks. Use `cui_icon_set_limits` to constrain memory, and `cui_icon_state_collect` only when prior draw lists have finished rendering. Button does not collect or release caller resources. ProgressCircle borrows caller-provided RGBA storage, its state, and any optional motion state. No Button artwork heap allocation is introduced. Underlying Icon preparation can allocate within its configured limits; the default Spinner uses the existing bounded context resource cache. Button's resolved artwork size wins over descriptor dimensions: legacy/design size, numeric `pixel_size`, and then explicit `icon_size` determine the slot. Custom Icon color, opacity and nonloading transform are retained. Spinner rotation replaces the transform while animated. ProgressCircle diameter is resolved by Button; its fraction, color, clock, motion and raster scale remain caller-controlled. A Spinner's default Loader is selected when its `icon` is null. An ordinary Icon requires an initialized caller-owned Icon state. A standalone Button copies descriptor values before accepted click callbacks. Group copies its child option structures but borrows artwork descriptors: callbacks must not mutate those descriptors until `cui_button_group_ex` returns. Referenced render-resource states remain mutable for painting and must live through renderer completion. Descriptor/result/resource objects must not alias; known overlapping result ranges are rejected. Contained pointer targets are not copied. Neither API freezes arbitrary caller mutations to resource storage. Optional result outputs report local Icon preparation failures (including the exact `cui_icon_error`) or ProgressCircle raster/argument/capacity failure. The failed slot remains the resolved size and paints no stale image. Invalid structural descriptors reject the Button without callbacks or result writes. A zero-progress fraction is valid. Only the selected artwork descriptor receives a result; ignored descriptors retain their previous output. Result outputs do not certify Core command, layout, frame-arena, renderer, or GPU success; check those APIs separately. Inert composition still paints and can update visible artwork resources or request animation redraws, while preserving Button interaction state and suppressing callbacks, hover notifications and tooltips. Layout-only composition reserves the same slot but does not prepare artwork, change resource/result state, or request redraw. Measurement and prepaint callbacks cannot compose Buttons. Loading still disables activation independently of artwork kind. The focused fixtures cover all 14 design sizes plus four legacy sizes, both densities and both joined axes, custom color, computed/explicit size, replacement and retained artwork, passive state/resource invariants, and bounded resource failures. Native Noto and Chromium WASM fixtures exercise actual font/layout and Canvas pixels; injected CDP touch is not physical-device validation. Failure fixtures exercise configured Icon limits, ProgressCircle storage capacity, and a full context resource table. They do not force a physical allocator failure. --- ## Button activation evidence Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BUTTON_CLICK_EVIDENCE.md # Button activation evidence `cui_button_click_event` now appends `has_evidence` and `evidence`, a copied `cui_activation_snapshot`. The existing release-derived fields retain their behavior. In particular, legacy `click_count` normalizes a pointer count of zero to one, while `evidence.press.click_count` and `evidence.release.click_count` preserve the raw host counts, including zero. ```c static cui_button_click_event last_click; static void remember_click(void *user, const cui_button_click_event *event) { (void)user; last_click = *event; /* No contained pointers; usable after the callback/frame. */ } static bool compose_button(cui_context *ui, cui_id id, const cui_theme *theme) { return cui_button_ex(ui, id, theme, cui_string("Save"), (cui_button_options){.on_click_event = remember_click}); } ``` For each accepted event, standalone Button copies the evidence before invoking legacy `on_click`, then invokes `on_click_event` once with the frozen payload. Legacy callback consumption of that accessibility event cannot erase the already accepted notification. Multiple accepted events retain input order and separate evidence; repeated keys and cancelled activations remain rejected. Callback-driven changes to later events still follow existing cooperative consumption and current-semantic validation rules. This is not capture/bubble propagation and does not restore consumed events. Styled ButtonGroup prepares each child's payload before its legacy callback, then forwards it through the existing post-legacy event-index hook. Its bounded transient forwarding records require no heap allocation or public workspace extension. Existing child callback counts remain unchanged. Group `on_change` continues to override both child notifications and their preparation hook, including the existing source-pointer-only versus explicit all-activations policy. This does not change borrowed artwork descriptor lifetimes. Base Group appends an optional `prepare_click_event` hook. It receives a borrowed, const copied Core snapshot before legacy/post-legacy callbacks. Copy it during the hook if it must be retained. Preparation is excluded from `cui_button_group_result.callbacks`, which counts action notifications. The old `on_click_event(user, ui, event_index)` remains compatible and still runs after legacy notification even if legacy consumption makes a later Core query fail. The evidence is forwarded unchanged from Core. A matching retained capture can provide press and release samples across frames, including mouse, pen or touch. An accepted unmatched release has release evidence without a fabricated press. Keyboard bounds describe the previous rendered clipped routing rectangle, which can differ from this frame's relaid-out Button. Accessibility evidence contains no fabricated pointer samples or key bounds. `has_evidence` reports successful copying; callers should inspect the individual `has_*` flags. The payload can survive later frames or context destruction. Target/frame/index identity remains local to the originating context and cannot identify recreated contexts or a complete frame-sequence wrap. The callback pointer itself is borrowed only until that callback returns. Refer to `ACTIVATION_SNAPSHOTS.md` for Core rejection and capture lifetime details. Pinned v0.7.1 uses `Button` click listeners (`button/button.rs`) and the `upstream-pre=0.3.8` MouseClickEvent/KeyboardClickEvent contracts audited in `validation/button-event-contract-next33.md`. First-focusing-click and long-press metadata, source key-up focus-generation policy, signed tab paths and event-local capture/bubble propagation remain separate gaps. This slice forwards supported evidence and does not certify whole Button-family parity. The focused headless fixture also reruns the existing callback contract suite. It covers repeated clicks, cross-frame contacts, leave/re-entry, mismatched release, cancellation, raw versus normalized counts, modifiers, old keyboard bounds after relayout, accessibility consumption by legacy callbacks, retained copies, Group multiplicity/override and the old Base index hook. Noto and actual WASM/Chromium fixtures exercise font layout and genuine mouse/keyboard/CDP touch input. Injected CDP contacts are not physical-device or OS adapter validation. --- ## Button built-in state painting Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BUTTON_STATE_REFINEMENT.md # Button built-in state painting This slice corrects built-in Button painting against upstream kit 0.7.1 commit `87d10ae5e1299d1be18670a37570c5402f952e34`. It adds no public API. The broader [state refinement audit](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/BUTTON_STATE_REFINEMENT_AUDIT.md) still describes proposed work, including callbacks, focus rendering, shadows, compound hover and theme fidelity. This slice does not complete that parity row. For Ghost, pointer hover uses the accent foreground and accent fill; dark mode halves the fill alpha. Pressed uses the default active fill and normal Ghost foreground. Selected/open uses the secondary active fill and normal Ghost foreground, suppressing pointer hover and pressed changes. Outlined selected Ghost uses the default active fill instead. These are distinct source states, even when a theme happens to give them the same colors. Outlined selected Link and Text retain their normal foreground. Filled selected Link uses active link ink; filled selected Text uses foreground alpha 0.7. Outlined Ghost/Link/Text retain outline border geometry with transparent built-in borders, matching the source's orthogonal outline construction. Explicit custom palettes keep their own background, border and foreground values; selected remains the custom active background. Disabled wins over selected/open and loading. Filled intent/custom borders use alpha multiplied by 0.15; Secondary uses 1.5, clamped to 255. Outlines use 0.5. The existing built-in Default rule remains half-alpha input background and input border. Ghost/Link/Text keep transparent disabled backgrounds and muted foreground at half alpha. Loading keeps its normal or selected/open colors, suppresses pointer styling, and fades the whole control to 0.8 unless also disabled. Returning to an interactive state restores normal hover paint. Source evidence: [Button render and variant resolvers](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/crates/component/src/button/button.rs), particularly render lines 703–733, outline selected lines 1274–1283, and variant disabled lines 1316–1376. CUI resolves these formulas using its existing solid-color palette. CUI theme defaults, RGB token derivation and source OkLab/non-solid backgrounds remain separate limitations. Focus-ring behavior is unchanged. Activation reduction, callbacks, aggregate bools and sizing are unchanged; selected/open still do not implicitly set toggled semantics. `tests/unit/test_button_state_refinement.c` checks both themes, all variants, custom translucent colors, outlined/filled disabled borders, Ghost hover and pressed/selected/open combinations, disabled plus selected/loading, loading fade and recovery. It asserts semantic inertness/busy/presentation separation, text and border draw colors, and actual software-rendered blank interior pixels. Text commands are checked directly and omitted from software pixel rendering because the portable test has no font backend. Loading icons remain in the rendered list; pixel samples avoid their slot. Validation used strict portable C11 warnings (`-Wall -Wextra -Wpedantic -Werror`) and a private CMake build rooted in the isolated worktree. The new fixture was registered only in that private build's CTest file. Seven tests passed through `python scripts/test_local.py --build-dir /tmp/cui-button-state-build`: the new fixture, Button behavior, passive lifecycle, activation blocker, callback events, click event and click snapshot. Root integration must register the new fixture in canonical CMake and refresh owned consumer guidance/generated resources. No native windows were opened. --- ## Bounded Button paint styles Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BUTTON_STYLES.md # Bounded Button paint styles Include `cui/cui_button_styles.h` for `cui_button_styled_ex` and the passive `cui_button_styled_paint`. These additive APIs use the existing Button paths. Zero styles preserve legacy pixels and results. Activation callbacks, input, semantics, sizing and slots retain their contracts. There is no event-facade or group bridge. This bounded API does not complete arbitrary Styled parity. The record is named `cui_button_style_paint` because the proposed name `cui_button_paint` conflicts with the existing legacy C function, which keeps its name. It contains initialized root box and foreground values. The dropdown caret retains its independent normal-ink rule. This real C11 owner example is compiled by the CMake consumer fixture: ```c #include "cui/cui_button_styles.h" typedef struct { bool selected, disabled; unsigned saves; cui_color hover, selected_fill, disabled_fill; } save_owner; static void save_style(void *user, const cui_button_style_info *info, const cui_button_style_paint *current, cui_button_paint_patch *out) { const save_owner *owner = user; (void)current; if (info->phase == CUI_BUTTON_STYLE_INSTANCE) { out->fields = CUI_BUTTON_PAINT_RADIUS; out->paint.root.radius = 0; } else { out->fields = CUI_BUTTON_PAINT_BACKGROUND; out->paint.root.background = info->phase == CUI_BUTTON_STYLE_DISABLED ? owner->disabled_fill : info->phase == CUI_BUTTON_STYLE_SELECTED ? owner->selected_fill : owner->hover; } } bool save_owner_draw(cui_context *ui, cui_id id, const cui_theme *theme, save_owner *owner) { bool activated = cui_button_styled_ex(ui, id, theme, cui_string("Save"), (cui_button_options){.selected = owner->selected, .disabled = owner->disabled}, (cui_button_styles){.instance = save_style, .hovered = save_style, .selected = save_style, .disabled = save_style, .user = owner}); if (activated) ++owner->saves; return activated; } ``` Each handler receives a stable submission snapshot and zeroed output patch. Only `fields` grants presence: transparent black, zero opacity, zero radius and zero corners are valid explicit values. Missing bits preserve preceding paint. Supported fields are background, border color, foreground, radius, corners and opacity. CORNERS copies `custom_corners` plus radii, including false to restore uniform radius. OPACITY always enables the supplied value, including zero; it does not require a `custom_opacity` flag in the patch. Handlers are synchronous borrowed pure paint calculations. Functions, `user` and owner data survive submission; nothing is retained across frames. Temporary `info`, `current`, `out` must not escape. Do not call CUI, queue/consume input, submit children, mutate owner/options/styles, or reenter submission. The callback has no context parameter. Update the owner after activation returns or through existing activation callbacks, never in a style calculation. Resolution follows Component caller-instance replay: 1. Normal defaults, then instance callback; capture its patch once. 2. Eligible active or hover defaults and callback. Pressed suppresses hover. 3. Selected/open defaults and selected callback, then replay instance values. 4. Disabled defaults and disabled callback, then replay instance values. 5. Loading multiplies resolved root opacity by 0.8 unless disabled. 6. Existing focus paint, then focused callback when focus-visible and ring shown. Selected/open, disabled and loading suppress pointer callbacks. Selected runs once when either or both flags are true. Loading can retain selected paint, does not invoke disabled, and composes explicit opacity (0.5 becomes 0.4). Disabled skips loading fade. Instance is called once even when replayed twice. An explicit instance background wins over selected/disabled background patches; leave its background bit absent to allow those layers to choose different colors as the example does. This intentionally differs from Base/Checkbox semantic-state-over-instance order. Loading composition is a documented CUI rule, not a claim about every upstream arbitrary opacity conflict. Focus geometry is unchanged and its existing gates still apply through state transitions. All root geometry is inspection-only. Width/height, padding/gap, border thickness/edges, clipping, alignment/offsets, input/semantic flags and every other unlisted member are ignored in patches. Radii change decoration, not rectangular hit testing. This keeps paint placement, hit targets, semantic bounds and content measurement aligned. Fonts, child layout, shadows, gradients, private compound content styling and unrestricted upstream modifiers are outside this API. A callback does not intercept or manufacture activation. Unknown mask bits or invalid present numeric values discard the whole patch without setting a Core error; later eligible callbacks still run. Present radii/corners must be finite and nonnegative; present opacity finite 0..1. Invalid values in unselected or inspection-only fields are ignored. Presence is never inferred by diffing values or treating zero as unset. The passive API paints an independently registered Button without semantics or input reduction. Existing registration and frame-resource lifetimes still apply. Style lifetimes end at submission return; text/image renderer lifetimes remain unchanged. The standalone fixture compiles this exact example and checks zero/no-op pixel equivalence, mask presence, replay/eligibility, invalid patches, protected geometry, software pixels and pointer/keyboard/AT callback order. Its checks stay active under NDEBUG. Software comparisons omit text rasterization in portable builds; text colors and placement are checked from real draw commands. ```sh cmake -S tests/fixtures/button_styles -B /path/to/private-build -G Ninja \ -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_FLAGS='-Wall -Wextra -Wpedantic -Werror' cmake --build /path/to/private-build --target test_button_styles button_styles_guide python scripts/test_local.py --build-dir /path/to/private-build -- -R '^button_styles$' ``` Root owns canonical registration, metadata and SDK/distribution/skill refresh. Consumers adopting this header must rebuild CUI and bindings from matching headers/source; there is no promise of compatibility with an older library. Worker validation: strict Release build and eight affected Button tests passed through the private wrapper. The new fixture also passed AddressSanitizer plus UndefinedBehaviorSanitizer with leak detection enabled, and the header passed strict C++11 syntax checking. The test compares legacy descriptor mutation and per-event callback multiplicity as well as passive zero-style equivalence. ## Shadow-aware Button surface facade Development additions after alpha.3: use a matching current source checkout and headers/facades. These APIs are absent from the published alpha.3 packages. `cui_button_surface_ex` and passive `cui_button_surface_paint_only` are separate additive C APIs in the same header. Existing styled records, signatures, numeric rules and callbacks keep their behavior. The surface facade adds an owned fixed array of at most `CUI_BOX_SHADOW_MAX` (eight) mixed DROP/INSET layers. It adds no builtin/default shadow and does not add gradients, fonts, border styles or source focus rings. Complete source state-style refinement remains incomplete; see [the source audit](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/BUTTON_STYLE_COMPLETION.md). Prepare typed layers outside the pure style callback: ```c #include "cui/cui_button_styles.h" typedef struct { cui_box_shadow elevation; } raised_button; static void raised_style(void *user, const cui_button_style_info *info, const cui_button_surface_paint *current, cui_button_surface_patch *out) { const raised_button *owner = user; (void)current; if (info->phase == CUI_BUTTON_STYLE_HOVER) { out->fields = CUI_BUTTON_SURFACE_SHADOWS; out->value.shadow_count = 1; out->value.shadows[0] = owner->elevation; } } bool raised_button_draw(cui_context *ui, cui_id id, const cui_theme *theme, raised_button *owner, cui_button_surface_status *status) { if (!cui_box_shadow_from_css(0, 3, 8, -1, (cui_color){0, 0, 0, 64}, CUI_BOX_SHADOW_DROP, &owner->elevation)) return false; return cui_button_surface_ex(ui, id, theme, cui_string("Save"), (cui_button_options){0}, (cui_button_surface_styles){.hovered = raised_style, .user = owner}, status); } ``` `cui_button_surface_paint` contains initialized scalar `paint`, `shadow_count` and owned `shadows`; patch scalar bits are the existing six bits, with scalar values under `out->value.paint`. Root geometry stays inspection-only. `CUI_BUTTON_SURFACE_SHADOWS` grants complete-list presence: absent inherits the preceding phase, present zero count clears both DROP/INSET, present nonempty replaces rather than appends. Zero scalar values remain explicit values. Every submission recomputes defaults; no callback or list persists next frame. Phase eligibility/order is the existing styled order above. Disabled clears the shadow list before its callback, then replays the captured instance patch. Consequently an explicit instance list (including empty) wins selected and disabled lists, while an absent instance list allows their own lists. Instance runs once even if replayed twice. Pointer color defaults leave the list alone; loading fades the complete root; the focused callback runs after existing focus paint. Final root corners determine the shadow shape. This does not change the existing rectangular hit targets or claim complete source focus-ring parity. Callbacks follow the same borrowed pure-calculation rules above. The facade copies descriptors before accepted action callbacks, and copies each returned patch before later phases/content. Do not call CUI from a style calculation; construct presets/CSS layers beforehand. Content callbacks retain their normal submission rules. Root decoration encloses actual custom-slot geometry without submitting children twice or recoloring arbitrary child paint; the caret keeps its independent normal-ink rule. The NEW facade bounds present radii/corners to finite `[0,16384]`, opacity to finite `[0,1]`, count to eight, sigma to `[0,256]`, offsets/spread to `[-4096,4096]`, with valid DROP/INSET kind. A nonempty list also requires the effective options-derived root radii to fit the shadow bounds. Unknown bits or invalid present values discard the whole phase patch, preserve preceding paint, and continue later eligible callbacks. Unused layer entries, absent values and inspection-only geometry writes are ignored. Existing styled radius rules remain finite/nonnegative without this new upper bound. CSS blur radius `[0,512]` converts explicitly to `sigma = radius / 2` as described in [ELEMENT_SHADOWS.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/ELEMENT_SHADOWS.md). The optional status output is cleared on entry, even when no submission occurs. Each rejected callback patch sets `1u << phase` in `rejected_phases`; this reports authoring errors independently of the ordinary bool activation result. Passing NULL suppresses this report. Rejected phase patches do not poison the Core frame; ordinary frame/renderer failures still follow their existing error paths. The passive API paints an independently registered owner without reducing input or adding semantics. It does not manufacture action callbacks. Decoration uses the existing Core copied-layer path and its frame/resource, clipping, opacity and rendering limits. Layout-only work allocates no shadow paint. A later named-element setter replaces the list, and a retained bridge root override is applied after owner paint and also wins. This C facade has no event/group overload and no Python/JS/TS/Go/Rust phase authoring binding. Those builders' existing static root shadows remain their separately bounded API. Focused tests freeze 60 pre-change old-library command/software/event-state triples across six legacy routes. New tests cover phase replay, explicit clear, transactional rejection, options-derived shape, eight mixed layers, copied lifetimes, movement/resize, ancestor clips/opacity, ordinary-only independent software pixels, passive behavior and descriptor mutation during real accepted callbacks. Text command content is checked separately from fontless software paint. Linux portable software proof does not establish hardware GPU, browser or complete source paint parity. --- ## Button tab ordering Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BUTTON_TAB_ORDER.md # Button tab ordering The frozen upstream-component source commit is `87d10ae5e1299d1be18670a37570c5402f952e34`. Component Button fields and defaults in `crates/component/src/button/button.rs` are `tab_index: isize = 0` and `tab_stop: bool = true`; methods at lines 472 and 480 update them independently. Render chains `track_focus`, `tab_index`, `tab_stop` at lines 816–818. Base Button in `crates/base/src/button.rs` follows the same independent defaults and mapping. The pinned upstream registry dependency is `upstream-pre` 0.3.8 (Cargo.lock checksum `d7f0bc3ebba070f8981b3f8e905a12f47d27794a30d029e59cdb9edf7a4b3360`). Its `src/tab_stop.rs` compares signed group paths lexicographically, then submission order. These exact sources were inspected in `/tmp/cui-upstream-reference` and `/tmp/upstream-pre-0.3.8`; see Core's `TAB_ORDER.md` for traversal evidence. CUI Button maps `.custom_tab_index = true, .tab_index = index` onto Core's explicit signed ordering, and `.skip_tab` independently onto tab-stop eligibility. For example index -1 remains a traversable ordered value when custom_tab_index is true and skip_tab is false. No sentinel interpretation is applied to that explicit index. Zero-initialized Button options preserve existing defaults and legacy semantic index 0/-1 for existing skip_tab users. Wrap Button submissions in Core's begin/end_tab_group calls to form nested paths. Button does not create a group of its own. Content, hover, and accepted activation callbacks compose with the copied Button descriptor. A callback changing the caller's options cannot retroactively change the current Button's submitted index, eligibility, or copied activation callback. Core snapshot publication preserves these values for the next frame's Tab traversal. Disabled/loading still suppress interaction. skip_tab preserves pointer and programmatic focus eligibility; Core's no_focus suppresses all focus eligibility. The frozen Button exposes no no_focus property, so this change does not invent one: applications can refine submitted Core semantic details when needed. Focus scopes and modal filtering remain Core behavior. Pointer-focus prevention and focus-ring presentation remain separate existing Button options. Supported scope: Button option mapping, signed hierarchical traversal through Core, and existing copied accepted-event behavior. This does not claim all upstream focus handle lifecycle, retained paint replay, accessibility adapters, or platform isize range parity; CUI indices use portable C int and bounded Core groups. --- ## Calendar selection and view behavior Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CALENDAR_BEHAVIOR.md # Calendar selection and view behavior Include `cui/cui_calendar_behavior.h` and rebuild with matching headers/library. The independent value-only record leaves existing picker and presentation structs unchanged. Zero behavior preserves the existing Calendar path; unknown enum values independently fall back to their zero values. ```c #include "cui/cui_calendar_behavior.h" cui_calendar_result reservation_calendar(cui_context *ui, const cui_theme *theme, cui_calendar_state *state, cui_date_selection *selection, cui_date host_today) { return cui_calendar_with_behavior(ui, 100, theme, state, selection, (cui_calendar_options){.range = true}, (cui_calendar_presentation_options){.month_toggle = true, .today = host_today, .neighboring_days = true}, (cui_calendar_behavior_options){ .range_transition = CUI_CALENDAR_RANGE_RESTART_EARLIER, .year_destination = CUI_CALENDAR_YEAR_OPEN_DAYS, .recenter = CUI_CALENDAR_RECENTER_SELECTION_START, .range_validation = CUI_CALENDAR_VALIDATE_RANGE_ENDPOINTS}); } ``` Initialize caller-owned state with `cui_calendar_init` once and submit inside an active frame; the host supplies its current civil date. The four independent policies are: - `RANGE_LEGACY` uses `selecting_end` and swaps reversed endpoints. `RANGE_RESTART_EARLIER` infers phase from the live valid endpoint shape on activation: empty/completed ranges start again; a pending earlier date restarts; a pending same/later date completes. It updates `selecting_end` only on acceptance. This includes supplied partial ranges whose flag disagrees with their endpoint shape. Merely changing policies or rendering does not synchronize phase or edit values. - `YEAR_OPEN_MONTHS` retains year→month→day selection. `YEAR_OPEN_DAYS` preserves the displayed month and returns directly to days after an eligible year activation, without changing selection. It clamps the civil cursor's day for the new year (Feb 29→28), prefers that enabled date, or searches that month's dates. With no enabled date in that month it keeps a valid civil cursor and focuses the year header, even if another displayed month is enabled. - `RECENTER_LEGACY` keeps existing conditional visible-window behavior. `RECENTER_ACTIVATED_DATE` always puts the accepted date's month first. `RECENTER_SELECTION_START` always puts the resulting start's month first, including incomplete starts and swapped ranges. Explicit modes focus the canonical anchor. If that retained anchor is disabled, they choose the first enabled visible canonical date (at most 93 civil dates), or keep a valid anchor cursor and focus the year header when none exists. A selected endpoint outside the anchored window remains selected but does not become an invisible focus target. - `VALIDATE_ACTIVATED_DATE` retains the existing live check of the activated date. `VALIDATE_RANGE_ENDPOINTS` also checks both endpoints of a completed candidate against current bounds/predicate before committing endpoints and phase. A newly disabled old start rejects completion atomically. Incomplete starts still validate the activated date. Interior disabled dates are allowed. Single selection ignores both range policies. Queued targets retain the outer call's original grid/date-and-panel identity; earlier recentering cannot reinterpret a cell index as another date. Transitions use updated selection/phase and current pure policy checks for each activation. Accepted incomplete changes report `activated`; `changed` compares final endpoints, including a net-zero queue. Recenter and year navigation alone do not create selection changes. Explicit recenter reports navigation when its month/cursor/focus destination changes. No synthetic activation, new dispatch architecture or global keyboard listener is added. `cui_calendar_reduce_with_behavior` and `cui_base_calendar_with_behavior` provide reduction and Base composition; Styled also paints. Split callers reduce with behavior then call `cui_calendar_submit_ex` with the same presentation options. Policy records contain copied values and are not retained. Keep locale strings, disabled predicate/user resources, state and selection alive under their existing submission/frame-consumption contracts; predicates must not mutate active UI or recursively submit. Render/paint callbacks are not action hooks. Existing typed CHANGE wrappers still call legacy operations once and keep their original callback timing and phase-only/navigation silence. There is no behavior/presentation observer wrapper in this slice: use the returned result. Language builders do not accept these options. DatePicker forwarding is available separately through [DatePicker Calendar options](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DATE_PICKER_CALENDAR.md), preserving its existing final-queue close behavior. The API supports CUI's bounded Gregorian months, year range and keyboard contract; it does not claim full Calendar styling, locale, event or browser parity. See [presentation options](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CALENDAR_PRESENTATION.md) for occurrence IDs and paint/lifetime limits. --- ## Calendar presentation opt-ins Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CALENDAR_PRESENTATION.md # Calendar presentation opt-ins Include `cui/cui_calendar_presentation.h`. The `_ex` Calendar functions accept a separate value-only record; zero preserves the legacy draw, semantics and reduction paths. Rebuild with matching headers and library when adopting these symbols. The unpublished presentation record now includes `neighboring_days`; mixing earlier record layouts with the new library is unsupported. No binding support is implied. ```c #include "cui/cui_calendar_presentation.h" typedef struct { cui_calendar_state calendar; cui_date_selection selection; } appointment_calendar; void appointment_calendar_init(appointment_calendar *app, cui_date initial) { app->selection = (cui_date_selection){.start = initial}; cui_calendar_init(&app->calendar, initial); } cui_calendar_result appointment_calendar_submit(cui_context *ui, const cui_theme *theme, appointment_calendar *app, cui_date host_today) { return cui_calendar_ex(ui, 100, theme, &app->calendar, &app->selection, (cui_calendar_options){.locale = cui_date_locale_builtin(CUI_DATE_LOCALE_IT)}, (cui_calendar_presentation_options){.month_toggle = true, .today = host_today, .neighboring_days = true}); } ``` Call initialization once and submission inside each active frame. The host supplies its local civil date; the core reads no clock or timezone. Invalid/zero `today` omits decoration. Today uses theme accent and accent foreground, selected cells use the existing primary paint, and disabled cells retain muted foreground. Today never changes selection or date eligibility. Configure fonts for the labels and consume draw/semantic data before the next frame. With `month_toggle=true` and one displayed month (`months` zero or one), separate localized month and year headers open their respective grids. Activating an open header closes it; Escape returns to days and focuses that grid's header. Selecting a month returns to days and focuses its first enabled date. Year selection retains the legacy transition through the month grid. Header semantics expose selected/expanded state. The month header ID is `cui_calendar_month_toggle_id(root)`; the year header retains navigation part 5. Multimonth calendars ignore the month-toggle option. Existing arrows, Home/End, PageUp/Down, Enter/Space and policy checks remain in the same reducer; this adds no global key listener. `cui_calendar_reduce_ex` and `cui_calendar_submit_ex` retain the split reducer/submission contract; Base performs both and Styled also paints. Locale strings and disabled predicate/user resources are borrowed and must remain valid through use and frame consumption. The presentation record contains no retained pointer. Predicates must not mutate or recursively submit active UI. Omission of the widget is allowed after its outer call and frame consumption; persistent application state remains caller-owned. Navigation reports `navigated`, never `changed` or `activated` by itself. Existing typed CHANGE wrappers are for legacy Calendar options; there is no extended observer wrapper or event-facade bridge in this slice. Use the returned aggregate result for this API. Existing callback ordering is unchanged. `neighboring_days=true` paints and submits valid outside-month cells as selectable dates. Muted unselected neighbors retain ordinary eligibility checks; selected/range, disabled and today paint use the precedence above. Neighbor occurrences have date-and-panel IDs; in-month cells retain `cui_calendar_day_id`. Only the canonical cursor is a sequential day tab stop. A neighbor can still receive pointer/programmatic/AT focus and Enter/Space activation. Selection focuses the canonical occurrence, retaining the displayed window when that date is in another visible panel or rebasing to its month otherwise. Existing CUI range endpoint swapping is preserved; frozen upstream instead restarts an earlier second endpoint and recenters on range start. This slice does not change that established CUI selection model. `cui_calendar_cell_resolve(root, first_month, first_weekday, panel, cell, &info)` returns a copied date, ID and neighboring flag for Base layout, automation or host inspection. A valid first month is normalized to day 1; weekday is modulo seven. Panel must be 0..2 and cell 0..41. It does not test whether the panel was submitted or the date is enabled. Invalid inputs, unrepresentable year-edge cells and zero-derived occurrence/canonical IDs return false and zero the output; NULL output returns false. Keep ordinary root-scoped ID collision discipline: no guarantee is made across unrelated caller roots. Repeated visible dates intentionally have distinct neighbor IDs. Queued input resolves against the outer call's original displayed grid and applies current policy per activation; preceding navigation cannot reinterpret the same ID as a different civil date. This implements independent month access, host-supplied today paint and opt-in neighboring cells under CUI's one-to-three-month/six-row bounds. Arbitrary item styling and unrestricted month counts remain outside this API. Seven builtin locale tables and custom tables already exist; this is not an OS locale engine, arbitrary date-pattern parser, non-Gregorian calendar or RTL layout implementation. Frozen upstream source does not define a dedicated Calendar arrow-key contract; CUI's existing traversal contract is preserved. Legacy DatePicker keeps zero presentation options; the additive [DatePicker Calendar API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DATE_PICKER_CALENDAR.md) forwards this record through its existing popup composition. The cell helper and presentation calls do not allocate or retain per-cell pointers; frame data and borrowed locale/policy lifetimes remain as described above. The legacy range, year-view and recenter defaults above can be selected independently through [Calendar behavior policies](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CALENDAR_BEHAVIOR.md), including optional completed-endpoint validation. These are separate value-only options and APIs; they do not resize the presentation record or change legacy calls. --- ## Carousel Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CAROUSEL.md # Carousel The module follows the frozen upstream kit 0.7.1 Carousel state, content, item, scroll mask, navigation controls and pagination contracts. Its pure base model requires only its source and `libm`; styled rendering uses existing Core, Theme, Icon and Tooltip components. There are no persistent allocations. Initialize `cui_carousel_state` with caller-owned geometry storage for 1–1024 items. The state and storage must remain valid through `cui_end_frame`. `count` may be zero; the selection is then `CUI_CAROUSEL_NO_SELECTION`. The initial nonempty selection is zero. Styled rendering synchronizes the model count to its supplied descriptor count on each call. Programmatic count/orientation/looping setters cancel interaction; count changes clamp selection, and an empty-to- nonempty transition selects zero. `cui_carousel_set_selected` clamps silently. User selection and navigation emit `on_change` only for a valid, different index. Callbacks execute synchronously; their user pointers remain application-owned. The callback may inspect state, but must not re-enter a render or replace its geometry workspace during a call. The drawing-free geometry API accepts finite, positive, sorted nonoverlapping item bounds along the primary axis. It validates the entire input before writing state or storage. Viewport extent is positive. Nonlooping snaps align item starts and clamp to the scrollable extent. Navigation skips items that share the same clamped snap, while explicit controlled/user selection can still select them. Nearest-snap ties choose the earlier logical item. The cycle includes a trailing gap matching the first inter-item gap. Runtime looping requires more than one item and a cycle at least as large as the viewport; a short cycle falls back to ordinary bounded navigation. Before geometry is available, configured looping supports logical wrapping, as in source. The styled root is a focusable, named Region with a clipped frame and optional controls/pagination callbacks. Each logical item renders exactly once every frame, including offscreen items. Item wrappers expose Group semantics, an accessible label and position/set-size metadata. Looping repositions the one instance of each item around the visible cycle; it never duplicates callback state, child control IDs or content. Adjacent first/last navigation targets the neighboring cycle and silently rebases after settling, without another change callback. Long active drags periodically normalize their coordinate so the workspace and animation distance remain bounded. `cui_carousel_default` supplies growing width, a 200px frame height and 16px leading item padding. The root has a 16px gap between composed parts. This is an explicit C layout default; source content height is supplied by its host layout. Item `extent=0` fills the frame along the primary axis and includes the leading padding. A positive extent is the complete outer item size, including that padding, and must exceed `gap`. Custom item appearance comes from `box`; primary/cross dimensions are controlled by its extent and the frame. Arbitrary callbacks do not receive an automatic intrinsic-size measurement pass. Hosts translate source variable widths/heights into explicit extents, or use the pure geometry API for separate presentation. This boundary is deliberate and is not a claim of arbitrary upstream style/layout parity. Frame bounds are retained through `cui_track_bounds`. Growing width starts with a 300px estimate until the first completed layout; fixed width uses its declared value. A changed measured frame schedules a follow-up frame and recalculates snaps. Geometry changes cancel active gestures and align the current selection. The host drives frames until `cui_needs_redraw` clears. `now_seconds` is an explicit monotonic host clock; backwards motion timestamps hold their last value. The default movement spring has a 280ms response, damping .85 and settling precision .5px. Styled rendering uses Theme `spring_move` response/damping; reduced motion or disabled travel settles immediately. Critical and overdamped settings also have an analytic solution. Settled motion does not request frames. Pointer processing happens before child callbacks using Core's previous-frame logical scope ownership and the measured slide-frame bounds. Navigation and pagination controls outside that frame never start a drag, so clicking them during spring motion cannot first snap to a different slide. A tap retains ordinary child press/release/activation. Movement greater than 2px locks to the dominant axis; ties lock to the Carousel axis. A stronger cross-axis move cancels the drag so ancestors can handle it, and suppresses that sequence's click. A locked release selects the nearest snap. Both locked drags and cross-axis cancellation cancel only their pending release activation, leaving the release and capture cleanup available to the child. Controls can be clicked normally again after the gesture. Primary-axis pointer motion/release are cooperatively consumed; unrelated controls and overlays keep Core hit priority. Disabled navigation cancels gestures and ignores keys/wheel; host callbacks remain responsible for disabling any child controls they own. Wheel delta signs match Core and Scroll: a positive delta moves backward, negative forward. A discrete wheel burst steps once and remains owned until 28ms silence; a burst beginning at an edge belongs to its ancestor. Diagonal wheel motion uses its dominant axis, with ties vertical. Precise input uses `scroll_precise` and `scroll_phase` to maintain a gesture-wide dominant-axis lock and continuous pixel offset. Started/Moved gestures retain ownership at an edge, including overshoot. Ended snaps once; Cancelled restores the original offset and emits no change. Zero-delta Ended/Cancelled still finish an active gesture. Moved-only streams settle after 28ms silence. Host adapters must supply reliable precise/phase metadata where available; SDL/DOM wheel inference is not provided by this module. Scroll handoff is cooperative. Pair a parent `cui_scrollable_begin` with `cui_scrollable_end_ex` and its mutable state, so end-phase reduction receives child-deferred events, avoids replay, and updates the same frame's layout offset. The tests cover this actual styled Scroll composition as well as an independent ancestor reducer after children. The older const-state `cui_scrollable_end` cannot revisit a dynamically deferred quiet-burst event. Carousel still observes a raw-hit edge event already reduced by the parent begin phase so a reversed delta in that same burst remains deferred rather than selecting a slide. Arrow keys navigate only the configured orientation. Home/End select the first or last item. Children process input before Carousel navigation, so a consuming text editor or inner component retains its key handling. Changed navigation consumes the key; an invalid boundary action remains available to ancestors. The root and controls preserve ordinary Tab stops. A pointer activation of a navigation/pagination control focuses the root and suppresses its focus ring; a keyboard activation preserves control focus. Root pointer focus keeps arrow navigation without drawing the ring; losing focus restores it. The ring can be hidden explicitly. Navigation controls default to Medium 32px round outline buttons with real 16px Chevron icons, chosen for axis/direction. They sit 16px outside the frame and use fixed dimensions immediately, or retained/estimated growing width. A growing frame's first placement is provisional and corrects after layout. `size` selects XS/Small/Medium/Large (20/24/32/32px); their icons are 12/14/16/24px. Custom uses `custom_size` and a 75% icon dimension; `custom_box` and `content` replace presentation. Previous/next disable themselves when no distinct reachable snap exists. Optional caller-owned Tooltip state/options compose the real delayed Tooltip; its host viewport must be supplied. Labels default to “Previous slide” and “Next slide”; hosts can provide localized/accessibility labels. Pagination items default to XS 20px compact buttons with selected metadata. They deliberately have no invented dot/number content: applications provide `content` and `custom_box` to match their chosen pagination presentation. Invalid indices disable the item. The default accessible label includes the slide number. `cui_carousel_pagination_begin/end` supplies the source named Group and an 8px-spaced, centered row, with an optional custom box. All callback arrays, strings and Theme pointers are borrowed for their call. Wrapper IDs must be unique and differ from IDs submitted by callback-owned controls. Captured touch scrolling uses `cui_carousel_touch_scroll`: precise pixel deltas retain their dominant axis and live offset until an explicit ended/cancelled phase. Pauses between finger movements do not trigger the 28 ms wheel-burst timeout. Styled Carousel selects this path for Core events whose pointer type is touch. Hosts using the headless model must deliver a terminal phase or call `cui_carousel_cancel` on capture/focus loss. Mouse wheels and ordinary precise trackpad bursts retain their documented timing policy. --- ## Charts Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CHART.md # Charts `cui_chart_render` rasterizes into caller-owned, straight-alpha RGBA8 pixels. Allocate at least `width * height * 4` bytes and keep the buffer alive through renderer completion. `cui_chart` renders the bitmap itself on each frame, including the first Candlestick frame and subsequent datum revisions. Call `cui_chart_render` directly for base-only use or explicit raster control; a matching cache key avoids duplicate raster work when both APIs are used. Set `logical_width` and `logical_height` to render at a higher pixel density than the chart's logical size; hit coordinates use logical size. A fresh styled state starts the source one-second appear animation automatically and advances it from the core frame clock. `disable_appear` (including a gallery animate toggle set to false) or reduced motion draws it complete; an explicit `cui_chart_render` before styling preserves caller-supplied reveal progress. Calling `cui_chart_render_animated` before `cui_chart` in the same frame reuses the raster when the visual input matches; changed dimensions, options, or datum values are rendered again. A nonzero `data_revision` enables a cache: increment it whenever a datum, series, link, or fill callback's user data changes in place. Zero disables caching. State, input arrays, strings, and output pixels remain caller-owned. Styled `cui_chart` and `cui_chart_render_animated` automatically measure Sankey label margins when all four margins are zero. For base-only rendering, call `cui_chart_measure_sankey_margins(ui, &options)` and assign the result to `options.sankey_margins` before rendering; this reserves source-style left, right, top, and bottom space. Use the same options for layout, raster, and hit testing. Set `custom_sankey_margins` to retain explicit zero margins and the compact graph. For an outside value axis, styled `cui_chart` and `cui_chart_render_animated` measure the tick-label gutter automatically when `value_axis_gutter` is zero. Pure base callers can call `cui_chart_measure_value_axis_gutter(ui, &options)` after choosing the tick formatter and assign its result to `options.value_axis_gutter` before rendering. Use the same options for raster and hit testing. The helper follows the source minimum of 32px plus a 4px label gap; zero uses the source 32px minimum for Line/Area and vertical Bar. Candlestick has no vertical value-axis gutter in the pinned source. Horizontal Bar uses a fixed 32px bottom gutter. The adapter covers seven chart families. Line and area accept natural, linear, and step-after curves and up to seven additional series; each extra series can select its own curve, stroke, and area/radar fill. Bars support top, bottom, left, and right alignment, including negative values. Two-stop base-to-tip gradients, a per-pixel bar fill callback for chart-aware gradients or patterns, uniform or individually controlled rounded corners, and explicit reveal progress are available; set `reduced_motion` to draw a complete bar immediately. `cui_chart_render_animated(ui, state, options)` drives all seven families from the core frame clock using the source one-second ease-out-quart timing, replays when `appear_key` changes, and honors `cui_reduced_motion(ui)`. `appear_duration` overrides one second, and `disable_appear` draws immediately. Direct `cui_chart_render` remains deterministic with caller-supplied progress. Their band geometry spans the full category dimension, apart from an outside value-axis gutter. Vertical value ranges use the source 20px category-axis gap when shown and the 10px/12px far-end clearance without/with bar-value labels; horizontal outside value labels reserve 32px below the bands. Band geometry uses the source defaults for inner/outer padding (0.4/0.2) and a 30px maximum width; caller options can change padding, width cap, unfinished band count, minimum length, and value-label formatting. `cui_chart_bar_bounds` exposes the same geometry used by the raster and hover lookup. Pie supports donut radius, a default outer radius of 40% of pixel height, slice padding, and optional outside labels with leader lines. `cui_chart_pie_labels` computes caller-owned overlap-adjusted positions and omits slices below 0.5 degrees; label text fades in after 70% of the sweep. Candlesticks validate OHLC, scale the price domain to observed lows and highs, and use the source full-width band scale (0.4 inner/0.2 outer padding, 30px width cap) with 0.8 body width, a 10px price headroom and 20px x-axis gutter, four source grid guides at quarter-height intervals, no implicit vertical axis, and bullish/bearish colors. Their hover band springs between candle centers and covers the plot above that gutter. `cui_chart_candle_bounds` exposes wick/body geometry; `candle_body_ratio`, `max_bar_width`, and `pie_outer_radius` allow overrides. Sankey computes an acyclic graph's longest-path layers and proportional node/link widths, then uses six weighted bidirectional relaxation passes by default with collision resolution, source post-relaxation column centering, and 0.15-height staggering of equal-height single-node runs; `sankey_iterations` overrides the pass count; `cui_chart_sankey_layout` exposes the caller-owned node geometry and rejects cycles before changing output. `cui_chart_sankey_link_bounds` exposes per-end ribbon centers and widths after stable source/target sorting; each side fills its node height even for imbalanced flows. The raster draws source-style cubic ribbons with source-to-target color gradients, a 0.3 opacity, and a 1px minimum link width by default. Sankey node text is opt-in, matching the source builder default; rounded nodes, value labels, font size, and label gap are configurable. Radar accepts the same additional series, a pinned maximum/outer radius, translucent fill, and optional vertex dots around dimension spokes. The theme helper fills absent colors, and the styled adapter draws category/value labels, simple legends and structured hover rows as CUI text over the bitmap. Default hover rows include swatches, muted labels, and right-aligned values; Bar tooltip swatches use the first gradient stop when configured, matching the source; Candlestick rows use Open/High/Low/Close labels with the direction color on the swatch; numeric values retain foreground unless `tooltip_value_color` overrides them. Set `tooltip_content` to draw caller-defined CUI tooltip content for the hovered datum; it replaces the default title and rows and runs once while hovered. Numeric label and hover formatting callbacks write into bounded buffers. `cui_chart_hit_test` returns a point or slice, a radar dimension, or a Sankey node. For Line and Area, grid ticks, value-axis labels, and pointer hit testing cover the full plot height while the value scale retains its top/bottom headroom; tick values extrapolate at the plot edges as in the source. A Cartesian `tick_count` of one clamps to two like the source value/y tick setters; Radar accepts one ring and defaults to four rings. Default Cartesian tick labels follow the pinned formatter: whole numbers without decimals and other values to one decimal place. Unformatted tooltip and value-label numbers use the shortest fixed decimal that round-trips within the bounded C buffer; extreme magnitudes fall back to scientific notation. The source uses its host number formatter for those extremes. The 38 named upstream kit theme presets now carry their eight pinned Chart colors: five series colors, bullish, bearish, and grid. `cui_chart_theme` uses `chart_2` for Line, Area, Bar, and Pie, cycles `chart_1` through `chart_5` for Radar and Sankey, and honors caller color overrides. The four independent CUI built-in themes provide their own chart-token defaults. This remains partial against the pinned upstream kit source. The method audit below lists the remaining gaps in labels, fills, axes, Sankey options, and hover effects. Outside value-axis gutters can be measured before rasterization with the helper above. `cui_plot` remains available for independent scales, ticks, pan/zoom, and clipping. ## Frozen source method audit This maps the public builders in the pinned upstream kit seven-chart sources to this C adapter. A C datum array replaces source `new`, `x`, `y`, `value`, and OHLC accessor closures. `cui_id` replaces `id`. Every family uses `noninteractive`, `cui_chart_render_animated`/`appear_key`/`disable_appear`, and `tooltip_content` for custom content; `tooltip_format` formats numeric rows. `tooltip_title`, `tooltip_label`, `tooltip_value`, and `tooltip_value_color` customize default hover content independently; `tooltip_content` takes precedence when set. Default tooltip content appears in a measured, at-least-150px portal beside the pointer, flipping horizontally and vertically at the plot midpoint; the portal can extend beyond the chart clip like the source's deferred tooltip. Custom `tooltip_content` can pair with `tooltip_measure` to size the portal from intrinsic content dimensions plus 8px padding on each side, with the source 150px default minimum width. Measurements must be finite and between 0 and 16368 per dimension; invalid or larger results, or no measure callback, use the legacy 150×64 size. The portal uses the source 120ms cubic-bezier enter/exit opacity, retaining the last datum as it fades out, and reduced motion snaps its opacity. Line/Area hover draws a point-aligned crosshair from the chart top to the x-axis gutter (or full height when the axis is hidden), plus per-series halo dots using the same pure point geometry as the raster. Their pointer positions follow a 120ms critically damped spring and their mark opacity enters/exits over the source fast tier; reduced motion snaps immediately. Bar draws an 8%-foreground translucent band across the source value extent (starting at the top for bottom bars or below the axis gutter for top bars) and fades other bars by up to 45% according to distance from its springing center; Pie springs the hovered slice's outer radius outward by 6px and fades other slices by up to 35%; Sankey fades unrelated links by up to 70%, retaining the last node during exit fade. Reduced motion snaps all three to their targets. All hover marks share the source tooltip's cubic fade; custom content must supply its natural size through `tooltip_measure` for a content-sized portal. | Source family | Covered builder methods | Implementation detail or remaining gap | | --- | --- | --- | | Line | `stroke` → `series[0]`; `natural`/`linear`/`step_after` → `curve`; `dot` → `show_dots`; `grid`/`grid_dashed` → `hide_grid`/`grid_solid`; `grid_columns`, `reference_line(s)`, `tick_margin`, `x_tick_count`, `point_count`, `x_axis`, `y_axis`, `y_axis_label_placement`, `y_domain`, `y_tick_count`, `y_tick_format` → corresponding options; `name` → semantic name. | `custom_y_padding`/`y_padding_top`/`y_padding_bottom` map source headroom; hiding the x-axis returns its 20px gutter to the plot for marks, ticks, and hit-testing. The point scale starts after the measured left value-axis gutter and ends at the chart right edge; an unfinished `point_count` keeps leading data at the same slots, and `x_tick_count` selects labels across all reserved slots rather than just populated data. Pure base callers can measure the outside value-axis gutter with `cui_chart_measure_value_axis_gutter(ui, &options)` and assign it to `value_axis_gutter` before rasterization; zero uses source 32px for Line/Area and vertical Bar. The crosshair and per-series halo dots glide at the source 120ms fast tier; their opacity uses the shared source cubic-bezier hover fade. The source 4px/2px dashed guide uses a bounded 1×4096 RGBA context resource by default; charts taller than 4096 logical pixels use a solid 1px fallback. Set `state.hover_guide_pixels` and `hover_guide_capacity` to caller-owned RGBA scratch of at least `ceil(logical plot height) * 4` bytes to avoid context allocation or support taller guides (up to 16384 logical pixels); that scratch must remain alive through draw-list consumption. | | Area | Line's axes, curves, point count, grid, reference, names, and tooltip controls; up to seven extra `y` series in `extra_series`. | `primary_fill` and each extra series `fill` override the derived solid fill; `area_radar_fill_pixel` provides caller-defined chart-space gradients or patterns; source Background objects are represented as pixels. Per-series stroke/curve are available in `cui_chart_series`. `custom_y_padding` controls top/bottom headroom; measured outside gutter uses the shared pre-render helper. | | Bar | `alignment`, `band_count`, `band_tick_count`, `corner_radii`, `fill`, `fill_gradient`, `grid`, `grid_dashed`, `max_band_width`, `min_length`, `padding_inner`, `padding_outer`, `tick_margin`, `value_axis`, `value_tick_count`, and `value_tick_format` map to bar geometry, fill callback/two-stop gradient, and shared options. `label`/`label_color` map to `show_bar_values`/`bar_label_format`/`bar_label_color`; `label_axis` maps to `hide_x_axis`, and `value_axis`/`value_axis_label_placement` map to `show_y_axis`/`y_axis_inside`. | Source's arbitrary Background object is represented as pixels. `bar_label_color_fn` supplies per-datum label colors; the pre-render gutter helper sets a measured outside gutter; horizontal outside value-axis labels use the source 32px bottom gutter and follow the value scale along x. Grid ticks run from each alignment's far value edge toward its baseline, omitting that baseline; the category-axis stroke follows zero rather than a fixed chart edge. Styled `cui_chart` and `cui_chart_render_animated` measure horizontal gutters automatically unless `custom_horizontal_bar_gutters` is set. Base-only callers can call `cui_chart_measure_horizontal_bar_gutters(ui, &options, &category, &value_end)`, then set `custom_horizontal_bar_gutters`, `bar_category_gutter`, and `bar_value_end_gutter` on the options used for rasterization, hit-testing, and painting. It measures the widest visible category plus 4px and the widest formatted bar value plus 4px, or reserves the source 8px end gap without values; a hidden category axis uses zero category gutter. The helper leaves outputs untouched on invalid or empty geometry. Category and bar-value labels use measured text bounds; categorical labels sit beside the horizontal zero line or on the empty side of each vertical zero line by sign and alignment; `cui_chart_bar_band_center` keeps zero-length category labels on the same source band scale. | | Pie | `color`/`value` map to datum color/value; `inner_radius`, `outer_radius`, `pad_angle` map directly. | `pie_inner_arc_radius_fn`/`pie_outer_arc_radius_fn` expose the source arc value, start/end angles, and pad angle to per-slice radius callbacks, including leader-line edge geometry; legacy `pie_inner_radius_fn`/`pie_outer_radius_fn` remain available with datum/index/default-radius inputs and yield to arc callbacks when both are set; zero-value arcs do not invoke arc callbacks; `pie_label_line_color_fn` sets per-slice leader colors; outside `label` text uses datum labels measured and placed on the matching side of the leader anchor, and global `pie_label_color`/`pie_label_line_color`/`pie_label_gap` cover the related styling methods. Pie `name` uses the chart name and per-datum `tooltip_name` maps to `tooltip_label`; the default value includes percentage share. `pie_tooltip_value` receives the source value and percentage share and overrides the row text; shared `tooltip_value` remains available as a lower-precedence fallback. | | Radar | `dot`, `grid`, `grid_levels`, `max_value`, `outer_radius`, and `stroke` map to shared/radar options; text `label` uses datum labels; extra value series are supported. | Solid `primary_fill`/extra-series `fill` are available; `area_radar_fill_pixel` supplies gradients or patterns; hovered dimensions draw source-sized vertex marks for each series, with coordinates available from `cui_chart_radar_vertex`; `radar_label_color` and `radar_label_gap` style dimension labels. Set both `radar_label_measure` and `radar_label_paint` to replace text with caller-owned CUI content at each measured label anchor; invalid measured sizes skip that label. | | Candlestick | `open`, `high`, `low`, `close`, `bullish`, `bearish`, `body_width_ratio`, `grid`, `tick_margin`, `x_axis` map to datum/options; default tooltip has OHLC rows. | `max_bar_width` overrides the source 30px default; `tooltip_value_color` can style each OHLC row; more complex row layouts use `tooltip_content`. | | Sankey | `iterations`, `node_align`, `node_padding`, `node_width`, `min_link_width`, `node_color`, `node_label`, and `tooltip_value` map to graph/options, datum colors/labels and formatter. Sorted link endpoints and cubic ribbons use source geometry. `sankey_value_scale` offers linear/square-root layout while node throughput stays raw; `sankey_link_opacity` overrides the source 0.3 default. | `sankey_node_corner_radius`, `sankey_font_size`, `sankey_label_gap`, `sankey_show_labels`, `sankey_show_values`, and `sankey_value_format` cover simple label/node methods; `sankey_labels` overrides simple lines with up to 16 styled text lines per node, taking raw throughput; `sankey_label_measure` and `sankey_label_paint` instead render arbitrary caller-owned CUI content without a line-count cap; measured labels follow source first-column-left, terminal-right, and middle-above placement without the former 64-node cutoff; source-style measured graph margin reservation is available through `cui_chart_measure_sankey_margins`, which leaves all margins zero when every custom label measures empty; the bounded text-line callback caps at 16, while measured/painted content supports arbitrary nested lines; D3 middle-out collision, per-pass alpha/beta weights, targetTop/sourceTop slot relaxation, and neighbor link reordering are implemented with bounded adjacency arrays; the graph now uses the source extent directly at measured margins, with no implicit 8px inset; `tooltip_name` and `tooltip_value` map to `tooltip_label` and `tooltip_value` callbacks; when `tooltip_value` is absent, the default row inherits `sankey_value_format` as the source inherits `value_label`. Link color defaults to a source-to-target gradient; an explicit link color overrides it. | All seven source families expose `appear`, `appear_key`, `id`, and `interactive`; the shared mapping above applies to each. Source builder methods for category/value accessors map to caller-supplied `cui_chart_datum` fields rather than callback registration. Line, Area, and Radar hovered marks use the source 8px filled dot, 1px background stroke, and 20px fill-color halo whose diameter and opacity follow hover progress; Radar retains its last marks during the exit fade. Horizontal Bar releases its category-label gutter when `hide_x_axis` is set and reserves it on the appropriate side for Left or Right alignment. Styled rendering measures horizontal label widths per frame like the source; pure base rendering uses explicit preflight or the fixed 24px and 12px fallback. The explicit representation and paint differences above remain partial despite the available chart type names; this audit does not claim verified full source parity. Cartesian line and area outlines use a 2px stroke by default, with round segment ends and coverage-based edge smoothing. Set `cui_chart_options.line_width` in bitmap pixels to customize it; positive values are capped at 16px, while zero, negative or nonfinite values select the default. The width participates in the render cache key. Grid/axis strokes keep their previous dimensions. Natural, linear and step-after curves share the same stroke painter. ## Shared Sankey solver Chart Sankey topology/relaxation and end-width calculation now delegate to the pure Base model in [PLOT_MODEL.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PLOT_MODEL.md#shared-base-sankey-graph-model). The Chart API keeps its existing policies: zero node width selects 10px, zero padding selects 16px, zero iterations selects six, and margins define the usable extent. This differs deliberately from standalone Plot's 24px/8px defaults and explicit-zero behavior. Node `throughput` still reports raw max(incoming,outgoing) flow, including when heights use sqrt-scaled values. Zero-flow alignment also keeps Chart's older summed-flow policy: zero-valued edges do not anchor Justify/Center alignment, while source-default Plot treats all edges structurally. The adapter selects the explicit Base compatibility option. Chart's existing input, label, margin and capacity validation remains in the adapter. `cui_chart_sankey_link_bounds` uses caller-supplied node positions directly; it does not run topology or move nodes. Unranked/cyclic projected geometry remains usable for this width-only operation. It retains independent end widths and neighbor-y ordering with input-index ties. The shared Base helper validates finite ordered y coordinates and endpoint/value data without requiring graph ranks. No second Chart solver remains. Builds compiling Chart Base directly must also link `src/base/cui_plot.c`; public Chart types and defaults are unchanged. Exceptionally large linear Sankey link values are uniformly normalized only for shared-solver geometry, including endpoint breadths. This preserves finite raw node throughput and layout ratios without requiring `long double` to have a wider exponent range than `double`. Raw node sums beyond `DBL_MAX` still fail; the pure Plot solver retains its strict overflow policy. Ratios too small to represent after normalization may vanish in geometry. ## Frozen source axis audit (87d10ae5) The styled Chart reference lives in `crates/component/src/chart`; its shared axis implementation lives in `crates/base/src/plot/axis.rs` (there is no `crates/base/src/chart` directory in the frozen checkout). Line/Area category labels now match `build_point_x_labels`: the first label aligns left, the last aligns right, and intermediate/single labels center on their ticks. These alignments also follow the logical bounds of a scaled bitmap. Value-axis text uses host measurement rather than a fixed 48px box. Outside vertical labels align their right edge four pixels before the measured gutter; Line/Area labels clamp within the plot vertically. Inside labels start two pixels from the plot's left edge and sit above their grid line, except the top label sits below it. Horizontal Bar labels center at their value tick and sit six pixels below the reserved 32px outside axis gutter, or 12px above the bottom edge inside. Value labels and category labels both honor `hide_axes`. Every configured value tick is measured and painted up to the existing 1000 tick validation limit; the former silent 32-label subsampling is removed. `custom_x_tick_count = true` distinguishes an explicit `x_tick_count = 0` (no category labels) from the legacy zero/default stride behavior. This field is appended to the options structure: earlier field offsets and zero-initialized source behavior remain unchanged, but binary consumers must rebuild for the larger options structure. Mixed-sign domains spanning `-DBL_MAX` to `DBL_MAX` use the shared scale's overflow-safe inverse/map for horizontal tick values and category zero-line placement. The frozen seven Chart families expose no legend builder or composition. `hide_legend` and the CUI extra-series text legend are adapter additions, not source parity evidence; the existing legend still has fixed text placement and no swatch/layout API. This audit verifies the axis behavior with headless geometry and formatter assertions, including 65 ticks, explicit-zero selection, inside/outside bounds, scaled category endpoints, and extreme finite domains. It does not certify full Chart-family parity: tooltip portal layout, animation trajectories, shape rasterization, and arbitrary source Background paint remain separate validation gaps. Generated `dist/cui_chart.h` must be regenerated by the integrator after merging these public-header changes. ## Frozen source tooltip and hit audit `cui_chart_update_hover(state, options, x, y)` exposes the existing retained selection model to headless and external hosts. Coordinates are chart-local logical pixels, just like `cui_chart_hit_test`; the function returns that hit and updates `hovered`, `hovered_value`, and the cursor anchor. An outside or nonfinite point clears active selection while retaining the last visual/cursor for the styled exit fade. Noninteractive options also clear the anchor so re-enabling interaction cannot revive a stale tooltip. Styled Chart calls the same helper for pointer movement and refreshes a stationary active hit each frame; Sankey tooltip values therefore follow changed raw throughput without requiring another pointer event. Pie hit selection now follows the pinned `Arc::contains`: select the original start-inclusive/end-exclusive angular interval and then test the slice radii. The original interval includes a painted `pad_angle` gap, which does not carve out a separate hover hole in the source. A donut's center and points beyond its outer radius remain unselected. Angle/radius calculations avoid intermediate `2*pi*value` overflow and squared-radius overflow for extreme finite values. The source tooltip has 8px content padding, including custom content: both the measured and legacy custom-content paths now paint callbacks inside that inset. An empty custom value string retains its source row, label and swatch and still invokes the value-color callback; a custom content renderer bypasses default rows and formatters. Pie default values use the shared raw round-trip formatter plus one decimal percentage, instead of rounding the value to three significant digits. Pie/Sankey swatches match the raster's datum-index palette when datum color is unset. The per-datum Pie palette is an existing CUI representation choice: the frozen Pie source defaults all slices to `chart_2` without a color accessor, so palette agreement does not imply that default-color parity. A source-shaped formatter callback receives datum, index, series and raw value: ```c static size_t tooltip_value_with_unit(const cui_chart_datum *datum, size_t index, size_t series, double value, char *buffer, size_t capacity, void *user) { (void)datum; (void)index; (void)series; const char *unit = user; /* e.g. " USD" */ int written = snprintf(buffer, capacity, "%.2f%s", value, unit); return written > 0 ? (size_t)written : 0; } ``` Set `options.tooltip_value = tooltip_value_with_unit` and `options.tooltip_user = " USD"` (include `` for `snprintf`). This exact callback is compiled and exercised by `tests/unit/test_chart.c`; a separate capture callback verifies stationary Sankey revisions. It returns the number of bytes written; the chart bounds accepted text to its fixed formatter buffer. The same tests exercise empty value/label/color callbacks, measured custom-content padding, source Pie pad/donut boundaries, extreme equal-half Pie values, logical-scale selection, leave/disabled/re-enable behavior, precise default values and matching swatches. Remaining limits include bounded 48-byte value formatter storage, legacy custom content's fixed 150x64 fallback when no valid measure callback is supplied, source Background paint represented as pixels, and animation trajectory/portal z-order validation beyond these headless assertions. This is a focused tooltip and hit audit, not full Chart-family parity certification. --- ## Tabs and toggle groups Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CHOICE.md # Tabs and toggle groups `cui_choice.h` contains allocation-free, caller-controlled Tabs and ToggleGroup behavior, plus themed composable renderers. Every item has a stable nonzero ID, label and disabled flag. Tabs selection uses an ID so reordering the caller's array does not select a different panel. ```c cui_choice_item choices[] = { {21, cui_string("Account"), false}, {22, cui_string("Profile"), false}, }; cui_id selected = 21; /* persistent application state */ cui_tabs(ui, 20, &theme, choices, 2, &selected, (cui_tabs_options){.variant = CUI_TAB_UNDERLINE}, draw_panel, application); ``` `draw_panel(cui_context *, size_t index, void *)` runs synchronously only for the selected enabled tab. Invalid or disabled selected IDs are retained as caller state and display no panel. Applications decide how to recover when removing a tab. Hidden panels and their children are not submitted, so they cannot remain in the focus order. Tabs support horizontal Left/Right or vertical Up/Down navigation, wrapping, Home/End, disabled-item skipping, click/Enter/released Space selection and automatic or manual activation. Manual mode moves focus using arrows and requires activation to select a panel. Default, underline, pill, outline and segmented styles derive colors and metrics from the supplied theme. The underline variant draws a bottom line independently of the focus outline. `options.render` paints a custom body for each tab, retaining its accessible label and interaction. It can compose icons and content within the theme's control height. `prefix` and `suffix` callbacks add application controls before and after the tab list in its orientation. Those controls retain their own IDs and behavior and do not select a tab automatically. Headless tests exercise custom bodies and both controls in all five variants and all four themes, including disabled semantics and ordered keyboard selection. As in upstream kit's documented closable-tab example, a custom tab body can compose a separate small close button beside its label. Give the close button a distinct stable ID, a meaningful accessible name/description and the tab's disabled state. Record the requested tab ID during the callback and apply removal after `cui_tabs` returns; the callback borrows the array. Applications own which neighbor becomes selected and where focus returns. A close button activates independently of the tab and can also be focused and activated with Enter. Tests remove an unselected tab without changing selection, reject a disabled close button, remove a selected tab by keyboard, verify withdrawn child semantics and apply an explicit empty selection policy when only disabled tabs remain, across all variants and themes. ToggleGroup accepts a caller-owned boolean per item. Options choose single or multiple selection, whether the final selected item can be cleared, orientation, and group disabled state. Arrow/Home/End traversal moves focus without selecting; activation applies the selected-state rule. Return values report selection changes. Callers should initialize state consistent with their selected options; externally supplied multiple selections are not silently normalized. The base functions paint nothing. Styled functions call those base functions and submit theme-dependent boxes, which permits an independent design system without forking keyboard behavior. Tabs expose tab, tab-list and panel roles with selected state and bidirectional trigger/panel relationships. The focused (or selected, or first enabled) tab is the group's single Tab stop; arrow traversal updates it. ToggleGroup exposes a group and buttons with pressed state through checked. OS accessibility bridges remain unfinished. The tab list ID is the container ID XOR `0xcda0312561f50cab`; a panel ID is its tab ID XOR `0x691a17db80e22f45`. These IDs must not overlap application children. Labels are frame-copied by the core, and callbacks must not retain draw-list strings. `tests/unit/test_choice.c` covers actual pointer activation, keyboard modes, orientation, wrapping, disabled controls, ID-stable reorder, invalid selection, toggle selection rules, and all five tab variants in all four themes. This is a portable C11 vertical slice. upstream kit's overflow menu, drag reordering, built-in close-button policy, maximum label width/ellipsis, and gallery stories remain pending. Composing those controls beside this tab list is possible, but is not claimed as equivalent built-in support. Full family parity is not yet verified. ## List, Select and Menu `cui_dropdown_button` composes two adjacent, independently focusable actions: a primary button and a caret trigger backed by the hierarchical menu reducer. The result reports primary activation and menu-item activation separately, and the caller receives the selected menu action ID. Shared primary, secondary, outline, ghost and danger variants, three sizes, selection, outer disabled state and custom primary content apply to the joined control. `action_disabled` and `action_loading` affect only the primary half, so alternate menu actions remain available. Callers provide distinct stable container, action, trigger and popup IDs. `cui_base_dropdown_button` exposes the same split behavior without paint. The menu trigger owns expanded/controls semantics and restores focus after menu activation. The primary half never opens the menu, and menu activation never reports primary activation. Tests cover every variant, size and built-in theme, joined geometry, accessible names, independent pointer/keyboard activation and disabled/loading behavior. The same header also supplies flat selectable lists and anchored popup controls: ```c cui_choice_popup popup; /* persistent application state */ cui_choice_popup_init(&popup, 80); /* once; unique popup/scope ID */ cui_select(ui, 79, &theme, cui_string("Account"), cui_string("Choose account"), choices, count, &selected, &popup, (cui_choice_popup_options){.viewport = {0, 0, width, height}, .dt = dt}); ``` `cui_list` accepts an application-owned `cui_list_state`. Activation updates the selected item ID; moving the active cursor does not commit selection. Up/Down, Home/End wrap through enabled options. Incremental typeahead matches label prefixes with ASCII case folding and byte-exact matching for other characters; a repeated single letter cycles matching labels. Pass elapsed seconds as `dt` to reset search after 750 ms of inactivity. No locale-dependent global state is changed. Select and Menu use the same base list behavior with distinct semantic roles. The trigger has an accessible name, expanded state and a controlled popup ID; Select displays the committed choice label or the supplied placeholder. Menu returns true for every action activation, including repeated activation of the same command. Select returns true only when the selected ID changes. Applications dispatch menu commands themselves. Opening with click, Enter, released Space or Up/Down moves focus into the popup. Selection closes it synchronously and restores the enabled trigger. Escape and outside clicks dismiss without changing selection. The popup is a floating portal, so a clipping parent does not cut it off. Placement flips/clamps against the explicit logical viewport; the width defaults to 240 and fits that viewport. The modal focus scope prevents Tab from reaching background controls while open. A flat empty popup renders an explicit empty state and remains dismissible. For long lists, only a bounded window of options is submitted and painted. Arrow navigation, Home/End and typeahead bring the active item into that window in the same frame. Wheel events inside the list or popup move this window in row units, carry fractional deltas across frames, clamp at both ends and respect modal scope ancestry. Scrollable listbox semantics expose physical row-height offsets and maximum offsets, preserving selected-set and label relationships. The core routes wheel events to the deepest eligible list; an inner list at its boundary allows its enclosing scroll region to receive the next wheel event. Base-only callers must provide the receiving semantic ID as `scroll_target`, its bounds and scroll metadata; styled lists supply these automatically. They do not commit selection. If the focused option leaves the window, focus moves to the first enabled visible option; Combobox keeps input focus while moving its active suggestion. Disabled lists ignore scrolling. This provides paging without allocating or registering thousands of offscreen controls. It is separate from the retained variable-height VirtualList model. Callers rendering a standalone list can set `visible_count` and `visible_begin`; `state.first_visible` returns the window after cursor navigation. List and popup options accept a `render(ui, item, index, user)` row-body callback. It replaces the default label painting while retaining the item's accessible name, disabled state, selected state, keyboard behavior and primary pointer activation. The callback can compose icons, descriptions or other content within the fixed theme control height. Multiple selection still paints its check indicator. The index refers to the displayed array, including filtered Combobox arrays; use the stable item ID to look up source data. The callback must not alter the borrowed arrays or add separately activatable menu actions. The popup ID is reserved for its scope and floating root; its internal list ID is that ID XOR `0xd1bc905ee4216f11`. Item IDs must be globally unique and not overlap trigger, popup or internal IDs. The API borrows all arrays and state for the call; labels follow the core's frame-copy lifetime. Initialize state once, not per frame. The headless choice test verifies selection, repeated menu dispatch, clipping escape, synchronous focus restoration, outside/Escape dismissal, empty lists, ASCII typeahead and keyboard paging over forty items with disabled endpoints. Scroll tests cover all six single/multi List/Select/Combobox paths, fractional wheel deltas, both clamps, out-of-bounds and nonfinite events, idle retention, disabled input, skipped disabled rows, focus transfer and subsequent selection. All six paths also test wheel+Enter, Enter+wheel and stale pointer activation in one event batch. Hierarchical descriptors and multiple selection are documented below. Remaining list gaps include touch dragging, variable-height item delegates, searchable Select, Unicode normalization/case folding and OS accessibility adapters. Tab currently stays in the open popup rather than dismissing and advancing to the next background control. These are tracked parity gaps; rendering and keyboard selection of the implemented subset are real. ## Combobox `cui_combobox` combines a single-line `cui_edit`, an input with textbox semantics, and an anchored suggestion list. `cui_base_combobox` supplies the same editing, filtering and keyboard behavior without drawing. The query editor, choice array, filtered scratch array, committed selected ID and popup state all belong to the application. Allocate filtered scratch for at least the full item count; insufficient capacity returns `CUI_EDIT_CAPACITY` before changing query or selection. Typing opens suggestions and filters label substrings using ASCII case-insensitive matching (other bytes match exactly). The input keeps focus while Up/Down and Home/End move the suggestion cursor; Enter commits that cursor. Disabled options are skipped. Pointer activation commits a suggestion and restores input focus. Escape or outside clicks dismiss without committing, and an empty filtered result renders an explicit message. Single and multi Combobox reuse the Input painter after reducing editor events once. The query shows a measured caret and selected text, clips long content and retains horizontal scrolling. Primary pointer presses and drags map to UTF-8 byte boundaries using the previous painted viewport and scroll offset; keyboard select all, replacement and undo continue to use the editor. Tests cover both modes in all four themes, selected colors, Unicode drag ranges, one-time text insertion, undo and pointer mapping after horizontal scrolling. Queued text and Enter events retain their queue order. Text followed by Enter commits from the newly filtered suggestions. Enter followed by text commits the previous active suggestion, then applies the query and leaves its new suggestions open. This matches separate frames while allowing platform adapters to submit an input burst without changing which value is committed. The query remains independent of the committed ID; selection does not overwrite the query or destroy its undo history. Callers may replace/select editor text using the editor API when their product needs that. The tests exercise actual text events, filtering, focus retention, committed versus query state, disabled/no-match cases, capacity errors, pointer selection and Up/Down plus Enter in one event batch. List, Tabs, ToggleGroup and Accordion also have batched navigation-plus-activation tests using the core's validated per-event activation reports. Two same-frame Collapsible activations both take effect. Combobox supports single and multiple selection. Remote query delegates, query/label synchronization policies, Unicode collation, IME, and the OS accessibility bridge remain incomplete. The current suggestion reducer applies edits before filtering for the frame; interleaving text edits with commits in a single batch remains an ordering gap. Wheel navigation and keyboard commits are reduced in event order; a pointer activation against the previous layout is discarded if scrolling moved the window earlier in that batch. ## Multiple selection `cui_base_list_multi`, `cui_list_multi`, `cui_select_multi`, `cui_base_combobox_multi` and `cui_combobox_multi` use a caller-owned boolean per source item. Multi Select and Combobox keep their popup open while toggling choices. Each visible option exposes its selected state and a checked visual indicator. Standalone and popup listbox roots expose `multiselectable`, vertical orientation and the popup's relationship to its labelled trigger/input. Escape/outside dismissal preserves the selected set. Selected values render as pill buttons; activating a pill removes that enabled choice and returns focus to the trigger/input. Disabled choices cannot be selected or removed by interaction. Multi Combobox additionally takes a `bool *filtered_selected` scratch array with the same capacity as its filtered item array. Filtering preserves selected choices outside the current query, and toggling a filtered option modifies only its source item. Query text and committed values remain independent application state. There are no implicit string concatenations or hidden allocation limits on the source set; visible popup windows are bounded as for single selection. List options can supply a synchronous `on_activate(item_id, user)` callback. It runs for every validated activation in input order, including repeated activation of one item in a frame. Multi reducers use this ordered callback so two queued activations toggle twice. Do not change the borrowed item arrays or their count inside the callback. A true return value reports an activation even when two toggles return the selected set to its prior value. Tests cover repeated toggles, selection of multiple enabled items, accessible selected flags, persistent popup state, removing chips, query filtering that hides selected choices, pointer toggling of filtered suggestions and focus restoration. The chip ID is its source item ID XOR `0x45f2b82e6c9bf447`; the chip container is the trigger/input ID XOR `0x97c22bb751e0d56a`. Multi Select's outer container uses `0x471d50d3bf973ac9`. Reserve those IDs as with other component internals. ## Hierarchical menus `cui_menu_tree` renders actual menu descriptors instead of limiting entries to the flat `cui_choice_item` array. Initialize `cui_menu_tree_state` once with a unique popup ID; the application owns descriptor arrays and check/radio values. ```c cui_menu_entry commands[] = { {.id = 101, .label = cui_string("Open"), .shortcut = cui_string("Ctrl+O")}, {.id = 102, .kind = CUI_MENU_SEPARATOR}, {.id = 103, .label = cui_string("Show sidebar"), .kind = CUI_MENU_CHECK, .checked = &sidebar_visible}, {.id = 104, .label = cui_string("Export"), .kind = CUI_MENU_SUBMENU, .children = export_commands, .child_count = export_count}, }; if (cui_menu_tree(ui, 100, &theme, cui_string("File"), commands, 4, &last_action, &menu_state, (cui_menu_tree_options){.popup.viewport = {0, 0, width, height}})) { dispatch_command(last_action); } ``` The reducer runs before painting. Normal actions, checked items, mutually selected radio items, noninteractive section labels, separators and nested submenus have real behavior and distinct visual treatment. Check/radio values are modified before the activated action ID is returned. `keep_open_checks` keeps the menu open for these actions; ordinary actions close the whole tree and restore the trigger. The semantic roles distinguish normal, checkbox and radio menu items; checked state, submenu expansion, controlled child menu IDs and semantic parent links are reported independently of styling. Up/Down and Home/End skip labels, separators and disabled entries. Right or activation opens a submenu; Left returns to its parent. Escape closes the innermost focused submenu before the root. Keyboard navigation and activation are processed in event order, so Right followed by Enter in one batch activates the first child rather than the submenu trigger. Per-level ASCII prefix search follows the list behavior. Hovering a submenu opens it, and parent entries remain clickable while children are open. Secondary pointer buttons do not dispatch ordinary menu actions. Nested menus are separate floating portals with increasing paint layers. They place beside their parent item and flip/clamp against the supplied viewport. Each level paints a bounded keyboard window and exposes one active Tab stop. The root focus scope traps background focus while child scopes preserve parent hit testing. An empty submenu or one with invalid child storage is disabled rather than opening an unreachable empty scope. Tree depth is bounded by `CUI_MENU_DEPTH_MAX` (16 levels). Attempting a deeper submenu leaves the existing tree open and sets `state.depth_limit`; there is no unbounded recursion or allocation. Descriptor trees must be acyclic and all IDs must be globally unique. A child scope ID is its parent entry ID XOR `0x4b64d23e91a738c1`. Arrays and pointed-to values must remain valid for the call. The state stores stable IDs and metrics, not borrowed descriptor pointers. The tests run check/radio mutations, repeated toggles, labels/separator/disabled skipping, three-level navigation and Escape restoration, batched child activation, real pointer hover, parent clicking with a child open, typeahead and the 16-level depth limit. Theme metrics supply menu density; text icons and shortcut hints are caller-provided and do not install key bindings. Entry `render` callbacks can paint custom row bodies synchronously while retaining the entry's accessible label and interaction. They must fit the fixed row height; they do not add independent menu actions. `checks_on_right` places checked-item glyphs after the label and before shortcut hints. Popup options choose the preferred anchor side; placement still flips and clamps. URL dispatch, kinetic gesture scrolling, arbitrary item heights and a native OS accessibility bridge are still parity gaps. The frozen submenu triangle/grace behavior is itself an upstream TODO. ## Context menus `cui_context_menu` attaches the same descriptor tree to an already submitted box ID, including a noninteractive receiving area. Call it after drawing that area. A secondary pointer press inside its previous-frame bounds opens the menu at the pointer without activating primary controls. Primary clicks keep their usual behavior. The modal scope guard prevents a receiving area behind an unrelated modal from opening; reanchoring its own open popup remains permitted. Opening inside the current parent modal is permitted. The menu root has the supplied accessible name. Check/radio, submenu navigation, Escape and action dismissal use the same reducers as the button menu. Dismissal restores the previously focused enabled control, including after reanchoring. `cui_context_menu_open` also provides explicit application-controlled opening with an anchor rectangle and a restore-focus ID. The application must draw the context menu each frame after opening it. Touch long-press and an automatic keyboard context-menu gesture are not implemented. Headless tests cover secondary press/release routing, primary activation, coordinate placement, reanchoring, nested action dispatch and focus restoration, as well as custom row drawing, right-side checks and preferred popup placement. ## DropdownButton property inheritance and ghost surface `inherit_action_variant` and `inherit_action_size` mark the corresponding outer property as unset. Both halves then use `action_variant` and `action_size`. With these flags false, the outer `variant` and `size` take precedence, including when explicitly set to the zero-valued defaults. Existing zero-initialized options retain their original defaults. A ghost pair surfaces both enabled halves when either half is hovered and retains that surface while its menu is open. The hovered half receives the stronger hover color. Escape restores the transparent resting appearance when the pointer has left. Disabled pairs remain transparent. Headless tests inspect the draw list after real pointer movement, menu activation and Escape, and verify inheritance and outer overrides. The two halves use independent outer-corner radii and border edges. `hide_action` or `hide_menu` omits that half from rendering, semantics and focus registration. At least one half must remain visible. Hiding the menu half closes an existing menu and clears submenu depth. The remaining half retains pointer and keyboard activation. The base function accepts a zero action or trigger ID for the same omission; both zero is invalid. Headless tests cover menu-only action dispatch, action-only pointer and Enter activation, absent semantic nodes and changing to action-only while a menu is open. DropdownButton `anchor` selects the popup corner: top corners open below the trigger, bottom corners open above it, and right corners align the right edges. The default is top right. Popup placement flips vertically and clamps against the viewport when the preferred corner cannot fit. The menu's `popup.side` is superseded by this explicit corner. General menu trees can independently request right-edge alignment through `popup.align_end`. Four-corner pointer-opening headless tests verify the resulting popup rectangles. Set `tooltip_id`, `tooltip`, `tooltip_state` and `tooltip_options` to retain an action-half tooltip alongside the split menu. The tooltip shares the existing Tooltip delayed hover/focus lifecycle and Escape suppression; its trigger is set internally to the action ID. Loading, disabled or omitted action halves and an open split menu suppress it. State remains application-owned. Tests cover real hover delay, painted tooltip text, Escape, keyboard focus and loading/menu suppression. This reuses the Tooltip component rather than introducing a second hover state machine. ## Tab label width `max_width` caps long built-in tab labels and appends a measured Unicode ellipsis. Short labels keep their natural width. Label prefixes end at UTF-8 codepoint boundaries, and the semantic name keeps the full original label. The five tab variants share this behavior. Custom `render` callbacks own their body layout and are not truncated, so nested close buttons retain their composition contract. Drag reordering uses application-owned requests described below. UTF-8 truncation preserves codepoints but does not promise grapheme-cluster boundaries. ## Bounded tab scrolling Provide an application-owned `cui_tab_scroll_state` and positive `bar_extent` to clip the tab strip to that width (or height for vertical tabs). Wheel input inside the previous viewport scrolls along the tab axis: horizontal wheel deltas for a horizontal strip and vertical deltas for vertical tabs. One wheel unit moves 32 pixels. Off-viewport, modal-blocked and disabled scrolling is ignored, and the offset clamps to the current content extent. Prefix and suffix slots remain outside the translated viewport. Manual scrolling survives selection and label changes; applications can set `offset` directly to reveal an explicit target. No automatic selection reveal is imposed. Accessibility exposes the current offset and maximum. The base reducer consumes wheel input and suppresses pointer activation against pre-scroll geometry in a scrolling event batch. Standalone base users provide the state's viewport, receiving ID and maximum themselves. Built-in labels have immediate measured extents; custom bodies use previous-frame tab widths. Tests cover both axes, translation, fixed slots, selection preservation, clamps, disabled and off-viewport input and removing tabs while scrolled. Optional native-painted scrollbars are described below. ## All-tabs overflow menu Initialize `cui_tab_overflow` with `cui_tab_overflow_init`, unique popup/trigger IDs and application-owned scratch `cui_menu_entry` storage with capacity at least the tab count. Set its popup options and pass its address as `overflow` alongside a bounded scroll viewport. The fixed menu trigger appears when content exceeds `bar_extent`. It lists every full label, skips disabled tabs and changes the stable selected ID before tab painting and panel rendering. Standard menu keyboard navigation, dismissal and focus restoration apply. Fitting all tabs or insufficient scratch capacity hides the trigger and closes an existing menu; capacity is checked before any scratch writes. The implementation allocates no per-frame descriptor storage. Menu item IDs derive from tab IDs XOR `0x8322717be8bd65e1`, and must remain globally unique. Tests open the overflow menu through real pointer input, inspect full labels, select an offscreen enabled tab through batched Down/Enter, assert same-frame selected semantics and panel, restore trigger focus and close the popup when the bar expands. Insufficient-capacity storage is also checked. ## Tab drag reorder requests Pass a persistent `cui_tab_drag_state` as `drag` to enable pointer reordering. A primary press on an enabled tab starts a candidate; moving four pixels starts an active drag. The styled strip paints an insertion marker at the hovered tab's midpoint-selected boundary. Dropping emits `requested`, `moved` and `before` as stable IDs (`before == 0` means append). Apply the array change after the frame; CUI never mutates the application's item storage. Selection remains the same ID and panel routing follows that ID after reordering. `requested` clears on the next submission. Ordinary clicks below the threshold retain selection behavior. Escape, removing/disabling the source, disabling the strip, lost capture and scrolling cancel the candidate. Drops outside the tab bounds or scroll viewport and no-op insertions emit no request. Nested controls do not start a tab drag. Tests cover both axes, insertion painting, append requests, application-applied reorder/panel stability, Escape, disabled tabs and ordinary pointer activation. Cross-strip drag/drop, autoscroll and keyboard reordering remain unimplemented. DropdownButton rounds the action's left corners and trigger's right corners, leaving their joining corners square. The action owns the shared seam border; the trigger omits its left border, avoiding a doubled seam. Focus border widths follow the same ownership. Per-corner/per-edge core primitives carry this shape through renderer adapters. As upstream does, these half-specific corner rules also apply when a half is omitted. Draw-list tests inspect all corners and border edges across all five variants, four sizes and four supplied themes. Built-in tab ellipsis finds a fitting codepoint prefix with binary search rather than remeasuring every shorter prefix. A 4096-byte label test instruments the configured font measurer and asserts fewer than 64 total measurement calls while verifying the capped width and rendered ellipsis. Width search assumes monotonic prefix advances; advanced grapheme/bidi truncation remains a text-layer gap. DropdownButton also supports `CUI_DROPDOWN_BUTTON_XSMALL` with the frozen 20-logical-pixel control height. `outline` is independent of primary, secondary or danger style: it uses a low-opacity variant-colored surface, stronger hover/selected surfaces, variant-colored text/border and muted disabled styling. The existing OUTLINE variant remains available for the neutral outline. Tests cover the fourth size across all theme/variant pairs, plus real hover/action activation and selected/ disabled outline surfaces. All named upstream Button variants are now exposed. `action_selected` preserves an inner action button's selected appearance and surfaces both halves, combined with outer `selected`. `action_outline` preserves an action-only outline; outer `outline` applies to both halves. Visual selection is presentation only: it does not set checked, selected or toggled accessibility state on these action buttons. The menu trigger reports its actual expanded state independently. Tests inspect inherited appearance, independent foregrounds, outer outline precedence and expanded/unchecked semantics after pointer opening. Set scroll-state `reveal_id` to request revealing a stable tab ID on the next submission. The request uses measured content geometry, leaves selection alone, and clears once applied; an unknown ID clears without moving. Oversized tabs align their leading edge. Custom-body requests wait until a previous-frame width is available. `reveal_selected` optionally reveals selection changes after base input reduction and before painting, so keyboard/overflow activation reveals its new tab in the same frame. The default keeps manual scrolling independent of selection, matching the upstream explicit scroll-handle contract. A selection that stays unchanged never resets manual position. `cui_tab_scroll_reveal` also provides the portable headless geometry operation directly. Tests cover clamps, invalid geometry, explicit stable-ID reveal, default preservation, same-frame keyboard reveal and unchanged-selection/manual-offset preservation. Set Tabs `scrollbar` with a bounded scroll state to show a six-pixel track over the viewport's trailing cross-axis edge when content overflows. Thumb size follows the visible/content ratio with a 16-pixel minimum. Primary pointer drag retains the grab position inside the thumb; track presses center the thumb at the pointer. The scrollbar supports axis arrows, Home/End and PageUp/PageDown, participates in focus order and exposes role, orientation, range, value and controlled viewport. Wheel input over the track uses the same bounded strip reducer. Cancel/Escape, disabling or removing overflow ends dragging. Painting and input remain portable CUI operations; this does not claim a platform-native OS scrollbar. Tests cover both axes, painted thumbs, primary capture/drag to the end, semantic ranges, keyboard paging, disabled input, wheel routing over the track, input cancellation and removal when the tabs fit. The track overlays the last six pixels of the tab viewport and first uses previous-frame viewport geometry. Dropdown Button also provides warning, success and info filled variants using the theme intent and corresponding on-intent tokens. Danger uses `on_danger`. Orthogonal outline uses each intent color for the label/border and translucent background; selected intent buttons retain their intent. Tests cover all four themes, filled/outline labels and actual action/menu activation across eight variants and four sizes. Default, Link, Text and Custom Dropdown variants complete the named presentation choices. Default uses its configurable theme Button palette, Link uses its normal/hover/active theme Link colors with a measured underline, and Text uses a transparent background with a slightly faded resting label. Link/Text stay transparent on hover and selection. Custom accepts portable `color`, `foreground`, `hover` and `active` colors shared by both halves; selection and held pointer/Space capture use active. Custom normal uses color with .2 opacity; hover and active use the corresponding supplied colors, including when outlined. A custom content callback owns its label decoration; built-in Link action labels are underlined, while the caret retains its icon presentation. Custom shadows and rich gradient backgrounds remain unfinished. Link refines both halves to the Link semantic role while retaining the split action and menu activation contract. Custom active color survives held capture across frames and reverts after release/cancellation; pressed colored outlines use the selected alpha level. Tests verify roles, pointer cancellation and Space release activation in all themes. Link decoration reserves each half ID XOR `0xc8134e39119b750d` and `0xc8134e39119b751d` for its label group/underline. Hierarchical Menu now routes wheel scrolling to the semantic menu scope under its pointer, including independently scrollable child popups. Fractional wheel steps accumulate per level; row windows clamp at both ends and expose pixel scroll offsets/ranges. If the active row leaves the window, the first enabled visible row becomes active and retains menu focus. Scrolling a parent closes its child panels, avoiding anchors to removed rows. Keyboard traversal still reveals the active row; wheel-then-release batches cannot activate stale rows. Tests cover child/root routing, disabled/separator skipping, clamp/fractional movement, Home/End reveal, outside/disabled input and stale-release suppression. Touch inertia and a visible Menu scrollbar remain gaps. The frozen source's submenu hover-out grace handling itself has a TODO; no full Menu parity is claimed. Opt-in Menu `drag_scroll` lets primary-pointer drags move the scrollable level where the press began. Movement beyond four pixels starts the gesture; fractional row travel accumulates, and the release cannot activate a menu row even across frames. Cancel, disabled/closed menus and disabling the option clear gesture state. Ordinary clicks below the threshold retain activation. The gesture also works for touch adapters that produce the same pointer events; CUI currently has no device discriminator, so this is not a claim of native touch inertia or multitouch. Tests cover parent/child gestures, held state, cancellation, sub-row movement, stale release and ordinary clicking. Re-entering an already open submenu trigger preserves its child scroll window and active row instead of rebuilding that level. This also retains deeper open paths; changing to another parent or scrolling a parent still closes/replaces the affected child. A pointer test verifies re-entry after child wheel scrolling. Dropdown now consumes `theme.buttons` independently configurable filled and outlined normal/hover/active backgrounds, foregrounds and borders for each intent and Default. OUTLINE selects the Default outline palette. Default and outlined buttons draw borders; filled intents follow the reference borderless appearance. Link uses its three theme foreground tokens; Text uses .9/1/.7 foreground opacity for normal/hover/active. Ghost pair hover/menu-held idle surface uses half-opacity accent while the hovered half uses full accent, and selected uses the secondary active surface. Disabled styles derive opacity from the normal tokens, and loading preserves normal color with .8 opacity while blocking action activation. Arbitrarily distinct palette tests prove that hover, held active, selected, outlined and disabled states use the configured values without deriving their RGB colors from another state. Custom normal/outline-normal mixing toward transparent uses .2 alpha and outline border mixing uses .4 alpha, matching the source factor-first convention. For a fully transparent target, premultiplied Oklab mixing preserves RGB, so these alpha operations are equivalent. Rich backgrounds and custom shadow painting remain explicit gaps. Tab `max_width` now caps custom-rendered bodies as well as built-in labels. The core natural-width constraint leaves short bodies untouched on the first frame and clips long bodies without a measurement flash. Custom callbacks still own text ellipsis/decoration inside their body. Scroll range/reveal calculations use the capped tab width. Headless tests cover short/long custom content from the first frame across all variants, retained scroll geometry and actual selection. Optional per-item `cui_tab_parts` arrays (`parts`/`parts_count`) provide prefix, suffix and icon callbacks. Declare positive `prefix_width`/`suffix_width` to reserve their full widths while the built-in middle label absorbs truncation. Callbacks receive the effective disabled item and remain inside the tab; suffix controls can handle their own activation without selecting the tab. Slot user pointers are borrowed. With zero/invalid widths slots fit naturally, but automatic intrinsic width reservation under a cap remains unfinished. Icon mode replaces the normal/custom body, reserves a theme-height-based icon area and exempts the tab from max_width, as in the reference icon-only behavior. Scroll/reveal extents include declared slots and icon exemptions; intrinsic/custom bodies use retained geometry. Tests cover every variant, prefix width, suffix placement, ellipsis, custom body composition, slot clicks, effective disabled propagation, array bounds and icon exemption. Slot wrappers reserve tab IDs XOR `0xacf7823ab98e17d0`, `0xacf7823ab98e17e0`, `0xacf7823ab98e17f0`, `0xacf7823ab98e1710`. List offers `on_confirm(item, secondary, user)` after the existing activation callback, and `on_cancel(user)` for focused Escape without changing selection. Both use `activation_user` and preserve input order. `secondary_modifiers` selects the portable host policy (zero defaults to CTRL|META); modified Enter and primary click confirmation expose that flag. Optional `track_secondary` paints an independent context-click highlight without committing/confirming. A later confirmation, Escape, removed/hidden/disabled row or disabling the option clears that highlight. Empty lists retain focused cancellation. Tests cover callback order, modified/unmodified Enter, modified primary release, context highlighting, disabled behavior and empty cancellation. Tabs now default to the frozen Medium metrics rather than generic Button control height. `size` selects Medium/Small/Large/XSmall; `density` defaults to theme font_size/16 and scales logical pixels, and positive `height` is an explicit styled height override. Public `cui_tab_size_metrics` gives outer/inner heights, horizontal padding, font and icon glyph sizes for composing callbacks. At density one outer heights XS/S/M/L are 20/24/32/36 (Underline 26/30/36/44), and icon glyphs 10/14/16/16. The icon area uses the variant's inner height times 1.25, with its cap exemption preserved. Horizontal spacer layout avoids introducing vertical padding. Inter-tab gaps follow the variant/size table (Medium: Tab0, Outline12, Pill4, Segmented2, Underline16), while prefix/body/suffix gaps are four logical pixels. Panels retain supplied theme styles. Tests cover all twenty variant/size combinations, exact icon area and glyph bounds, scroll extent, explicit density and height override. This is a visible default change: a standard 42px Button theme now has 32px Medium Tabs. Automatic intrinsic slot reservation remains a separate parity gap. Segmented bars reserve horizontal XS/S/M/L padding of 2/3/4/4 logical pixels, outside the scroll viewport and inside the bar prefix/suffix. Underline bodies reserve top margins 1/2/3/5 and bottom margins 2/3/4/6, centered within the outer height; the selected underline is a bottom border and consumes no body layout. Headless bounds tests cover each size, both margins and the padded viewport. Tabs consume the independent tab foreground, active foreground, active surface and bar tokens. Outline and Pill use their source-specific secondary hover and foreground policies; disabled selected Pill colors halve opacity. Default tabs paint side borders, Underline paints only its bottom edge, and selected Segmented bodies paint an inset background with size-specific radius. A pointer-routed headless test customizes tokens and checks normal, hover, selected and disabled foregrounds for every variant. Segmented raised shadows still require a renderer primitive; the optional animated presentation is described below. Caller-owned `cui_tab_motion` and `cui_tab_motion_step` provide the retained left/width springs used by the frozen indicator. Pass `theme.spring_move` and frame delta; first layout snaps, later targets retain both velocities, and reduced motion, disabled travel or response zero snaps. Invalid geometry leaves state untouched. Exact analytic steps handle under-, critically- and overdamped settings without frame-subdivision dependence. Optional `cui_tabs_options.animation` wires this state to the shared indicator for horizontal Pill, Underline and Segmented strips. Supply frame `dt`; state and its retained bounds must live through `cui_end_frame`. First layout uses static selected visuals, then an underlay paints below labels with inherited clipping. Selection switches preserve velocity, scrolling adjusts box-relative position, and reduced motion snaps. Enabled selected static surfaces are suppressed while the indicator is ready; disabled selected tabs retain their static styling. Pill built-in text fades for 200ms with ease-in-out-cubic and linear HSL channels on later switches; custom body callbacks retain their own text presentation. Tests route clicks, check initial fallback and paint order, reverse retargets, scroll displacement, disabled fallback, reduced motion, grayscale and colored HSL fading. Full-bar background/radius includes prefix and suffix, and the bar centers its children vertically. Segmented shadows remain a separate gap. A configured bar suffix or overflow menu now reserves the frozen 12-logical-pixel `last_empty_space` tail inside the scroll content, including the inter-item gap. It remains present when an overflow menu is configured but currently hidden. `last_empty_space_width` overrides its logical width; the accompanying custom flag permits explicit zero. An optional callback and user pointer compose a custom body within this fixed reservation. Arbitrary intrinsic tail widths remain a measurement-contract gap; explicit widths keep first-frame scrolling exact. Headless tests check tail placement, range and density, wheel-to-end plus button routing in a custom tail, and event suppression for an explicit zero-width tail. This changes a 100px tab with suffix in a 110px viewport from no overflow to a 2px scroll range, as the 12px tail now participates in the range. Per-item parts also expose `omit_leading_border`, matching the frozen first Default tab's `tab_bar_prefix(false)` policy. It removes only that first tab's left edge; later tabs and other variants keep their own edge policy. Rendered edge tests cover default, opted-out, disabled selected and a later selected tab. Loading preserves the action label and custom body instead of replacing them with an ellipsis. It keeps the action inert while the menu remains independently usable. Headless tests verify the custom callback runs during loading, layout width remains stable, built-in labels remain visible and action clicks are blocked. Loading now applies inherited opacity of 0.8 to the entire action subtree, including caller-colored text/shapes, bitmap checkmarks and nested opacity. It preserves base palette alpha and applies the fade exactly once; a disabled loading action keeps disabled styling without that extra fade. Tests cover all twelve variants, custom text/shapes and nested bitmap opacity. Icon-to-loader substitution still needs a portable icon primitive. Dropdown now uses the frozen button metrics: XS/S/M/L heights 20/24/32/32, horizontal padding 4/8/10/12, fonts 12/14/14/16, content gaps 4/4/8/8, and caret areas 12/14/16/16. Public `cui_dropdown_button_size_metrics` exposes these logical metrics. `density` defaults to theme font_size/16; positive `height` overrides styled height while preserving caret/button widths and typography. Horizontal spacer padding avoids vertical padding, and labels reserve the source 1.25 line height. Link/Text fit label/custom content and caret areas without padding or fixed height; a styled height override still applies to them. Tests cover every theme/variant/size combination, exact spacing/font/caret bounds, density and height overrides, and Link action routing. This changes a standard 42px Button theme's Dropdown Medium height to 32px. Menu rows use their separately documented source metrics. The caret remains a text fallback pending a proper portable icon primitive; intrinsic custom-body sizing and built-in capped-label ellipsis remain separate presentation gaps. Choice selection marks now use the shared antialiased `cui_checkmark` bitmap, not ASCII checkbox/radio strings. Popup Menu checked and radio entries paint the source 12px check glyph. A left glyph/icon column aligns every row whenever any left glyph/icon exists; explicit icons win over left checks. Right checks appear only on checked rows and coexist with left icons. Flat multiselect Lists reserve a trailing 20px slot with a 14px muted check; Select and Combobox reserve a trailing 12px foreground check slot, including single-selection popups. Metrics scale with theme font_size/16. Unchecked slots stay blank. Existing roles, checked/selected states and radio exclusivity remain semantic properties. Headless tests route check/radio toggles and disabled clicks, inspect left/right placement, icon precedence and tints, and verify selection/check bounds and activation in all five List/Select/Combobox modes. Shared glyph pixel rendering is covered by the core/component/backend owner; Choice tests inspect IMAGE commands and routing. Popup menus use accent/accent_foreground for enabled active or hovered rows; disabled rows suppress that highlight. Select and Combobox rows use accent for the active cursor while retaining the normal text foreground, and unselected enabled hover uses accent at 70% alpha. Other rows leave their background transparent. Routed keyboard tests inspect row fills and check/text tints. Ordinary List rows use list_active (or accent when list_active_highlight is false) for the active cursor, list_hover for inactive unconfirmed hover, and selection for the secondary-selected outline. Their foreground remains text; disabled rows use muted and suppress active/secondary paint. Popup panels use popover, and ordinary hierarchical menu labels use popover_foreground. These colors are independently configurable and tested with distinct token values. Row metric policies are documented below; other remaining gaps stay explicit. Default and Underline bars paint their full-width one-pixel baseline as an anchored underlay, after the bar background and before tab children. Its width and bottom position resolve from the same frame's final bar bounds. Selected Underline edges and animated indicators therefore paint over the baseline. Headless tests change prefix width and height on consecutive frames and verify immediate baseline resizing, bottom anchoring and paint order. ToggleGroup's existing convenience API retains its exclusive/multiple, allow_empty and vertical keyboard policy, and paints each item through the shared Toggle renderer. It registers item semantics only once. Its default Medium item geometry is now the source Toggle 32px height and 14px text, with ghost accent styling, rather than the old ordinary Button theme geometry. The richer ToggleGroup_ex API provides independent size, variant, segmented styling and controlled requests. Routed tests cover rejected empty selection, exclusive changes, allowed clearing, same-batch navigation/activation and whole-group disablement through the convenience API. Hierarchical Menu options now expose size, density and max_height. Medium, Large and XSmall use the source 26 px row height; Small uses 20 px. Density defaults to theme.font_size/16 and scales these logical metrics. Rows use 14 px text, 12 px icon slots, 8 px horizontal padding, 4 px outer padding and 2 px vertical gaps. The radius caps at 8 px and Small halves it. A separator reserves 6 px (2 px line plus two 2 px margins); group labels reserve 14*1.618034 px. The natural line-height factor comes from the pinned upstream-pre 0.3.8 TextStyle default, rather than a Tailwind line-height assumption. The explicit core text line-height API preserves fractional font and line-height values through layout and painting. Default popup height caps at min(viewport.height/2,450 px); positive max_height sets an explicit cap. Popup fitting, semantic scroll offsets, submenu anchors, pointer hover routing and wheel tail limits account for nonuniform rows. Tests cover every size in four themes at densities 1/2, padding/font/bounds, submenus after separators/group labels, and one-event wheel movement to the true tail of a mixed-height menu. Source scroll still uses integer row windows; partial rows and continuous pixel offsets, natural intrinsic popup width, negative separator horizontal margins, custom arbitrary-height bodies and popover shadows remain gaps. Existing explicit popup.width remains supported. Dropdown variant ordinals now match the source default: Default 0, Primary 1, Secondary 2, Danger 3, Outline 4, Ghost 5, Warning 6, Success 7, Info 8, Link 9, Text 10, Custom 11. Zero-initialized options therefore use Default rather than Primary. This is an explicit enum-value migration: named constants continue to select the same variants, but persisted integers, foreign bindings and ordinal UI selectors must be remapped. Previous values were Primary 0, Secondary 1, Outline 2, Ghost 3, Danger 4, Warning 5, Success 6, Info 7, Default 8; Link/Text/Custom values remain unchanged. A custom Default token test verifies the zero-options presentation directly. Ordinary List rows now use the source 16 px font,12 px horizontal/4 px vertical padding, 4 px body/check gap and natural height 16*1.618034+8 px. List has no source size variant. Positive options.height overrides the fixed row height; density scales logical metrics and defaults to theme.font_size/16. Its multiselect check reserves 20 px and paints a 14 px muted glyph. Inactive rows are transparent; the secondary-selected selection outline is the only row border. Select and Combobox rows expose Medium/Small/Large/XSmall/Custom sizing. Their fonts are 14/14/16/12 px; horizontal padding is 7/5/9/1 px and vertical padding 4/2/8/4 px. Custom sizing uses font=custom_size*0.875 with 5 px horizontal and 4 px vertical padding. Natural height is font*1.618034+2*vertical_padding. All searchable rows reserve a 12 px check slot and 4 px body/check gap. Density scales these logical values, including fractional fonts and glyph sizes. Positive row_height overrides row height while preserving the font policy. Popup padding is 4 px and the default total height cap is 20 rem=320 px, scaled by density; positive max_height changes that cap. Popup fitting, cursor reveal and semantic scroll offsets use the resulting row heights. Headless tests cover all five sizes across Select/Combobox single/multiple modes, fractional custom fonts and density, padding/gap/check geometry, explicit row-height overrides, routed selection, default/custom popup caps and End reveal/activation. Existing wheel, disabled and custom-body routing tests remain in the full suite. The fixed-height convenience row APIs still do not measure arbitrary custom content height or variable multiline body heights. Scroll windows remain whole rows rather than continuous pixel offsets/partially visible rows. Custom body callbacks choose their own text presentation. Natural popup width, portal shadow and remaining icon/loader substitution remain separate gaps. Legacy flat Menu shares the flat popup infrastructure; hierarchical Menu has its dedicated source row metrics and nonuniform separator/label accounting. Searchable Select and Combobox option rows span the popup interior, including their pointer targets and highlight backgrounds. This applies to single and multiple selection at every supported row size. --- ## Window and pane chrome Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CHROME.md # Window and pane chrome `cui_status_bar` implements the frozen upstream kit 0.7.1 StatusBar composition: left and right regions pin to their respective ends; the center is centered in the remaining space when both ends are present, right-aligned with only a left region, and left-aligned otherwise. Regions accept borrowed text or arbitrary callbacks with stable unique IDs. Callbacks receive 12px muted text defaults at the standard density and retain ownership of their input and semantics. The default bar has an independent `status_bar` background and `status_bar_border`, an upper 1px border, 8px horizontal and 4px vertical padding, and 8px gaps. Spacing scales with the theme's base font density. `style` replaces the outer box; explicit content spacers remain. It is a passive group, not a live announcement region; custom interactive children keep their own Tab stops. Headless tests cover all four end-presence combinations, two same-frame widths, all four themes, callback sizing/semantics, and duplicate-ID rejection. Remaining source gaps: independent region overflow clips, inherited rich font styles, and the full Styled refinement API. The outer bar clips overflow; custom content can cross its own region boundary. Browser/native visual audit and TitleBar host integration remain pending. ## Title Bar `cui_title_bar` uses the source's fixed 34px height, 12px leading inset (80px for native traffic lights), full-height 34px window-control slots, small window SVGs, and vertical background gradient. The gradient starts at 55% title-bar / 45% application background and ends at the title-bar color; immutable bitmap underlays preserve its position beneath children on the first frame. Fullscreen native content receives the extra 12px leading inset. Multiple content items share free space between them. A portable `cui_window_host` in the core platform interface reports decoration, maximized/fullscreen state and supported actions. Browser, server-decorated and native-traffic-light hosts omit duplicate window controls. Client-decorated hosts render only supported controls. The optional close callback overrides host close. Buttons expose explicit accessible names and keyboard activation. Title-area pointer capture requests one move on the first motion, clears on release/cancel or an outside press, and leaves child controls independent. Double clicks use configurable time/distance thresholds because portable events do not yet carry native click-count/preferences. Client-decoration secondary clicks request the host window menu. The return value reports a performed action. The SDL adapter exposes `cui_sdl3_window_interface` and `cui_sdl3_set_decorated`. Window close requests stop the next poll without invalidating the current frame. Native drivers expose minimize/maximize/restore; window managers may complete these asynchronously. Dummy/offscreen hosts expose close only. Decoration changes return false when unsupported. Non-macOS native hosts map title-bar double-click to maximize/restore. These service contracts, unsupported actions and decoration flags run in the SDL tests, including X11; portable mock-host tests cover the complete pointer/keyboard routing and paint. Remaining TitleBar gaps: SDL does not expose drag initiation or a system-window menu through this bridge; a host can provide those callbacks. macOS traffic-light placement and system double-click preferences, Windows native hit-test control areas, and window-manager-specific capabilities are not fully integrated. The close override is portable rather than Linux-only. Custom box style replaces the outer source style rather than implementing arbitrary incremental refinements. Actual native window-manager behavior and browser story still need broader audit; this is tested partial support, not full platform parity. --- ## Validated inline color entry Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COLOR_ENTRY.md # Validated inline color entry Include `cui/cui_color_entry.h` for a bounded hex field with separate draft, preview and committed selection. Existing `cui_color_picker` remains an inline HSV/RGBA picker; its strict parser and aggregate events are unchanged. Initialize a zeroed, caller-owned `cui_color_entry_state` once, retain its address, and destroy it after the final frame's draw data has been consumed. The state owns a ten-byte draft and an allocated editor. It must not be copied or moved after initialization, and its editor/buffer fields must not be modified directly. The complete compiling owner example is [`tests/unit/test_color_entry_owner.c`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_color_entry_owner.c). It submits the actual styled field, types a shorthand color, commits with Enter, copies the selection into a separate owner model, and applies that model before the following submission. Its callback never mutates the live entry. The focused fixture compiles and executes the example with assertions enabled in Release. Use `cui_color_entry_init` with `{.present = false}` for an empty selection; transparent black is instead `{.present = true, .color = {0,0,0,0}}`. The pure `cui_color_entry_parse` accepts an optional hash and 3/4/6/8 ASCII hex digits. Shorthand duplicates each nibble; missing alpha is opaque. COMPLETE writes the output; INCOMPLETE and INVALID preserve it. It accepts no CSS names, functions, spaces or signed numbers. This does not expand legacy `cui_color_parse_hex`. The real field admits empty text or a hash followed by up to eight hex digits. It rejects other edits atomically using Input's existing acceptance mechanism. A complete draft updates preview only. An incomplete draft retains the previous valid preview and committed value. Empty text cannot commit and does not clear a selection. Enter commits only complete drafts, including a same-value commit. The field inherits Input's focused, nonrepeated Enter routing; consumed, unfocused, IME-owned, disabled, readonly or passive events do not create commits. It does not close a popup. Standard Input pointer hit testing, caret, selection and textbox semantics are used by the styled facade. Base supplies semantics and reduction; the caller supplies its layout, as with Base Input. `cui_color_entry_result` reports draft changes, status, previous/final selection, preview, completed commit count and rejected incomplete-submit count. Internal Input notifications preserve queue order, including text after a commit in the same frame. `input.rejected` concerns draft admission; `rejected_commit_count` concerns submitting an admitted but incomplete draft. Counts do not depend on installing an observer. Multiple completed commits produce one external observer call after final semantics (Base) or paint (styled), carrying the final committed value. This summary is UNKNOWN source with actual frame metadata, without a fabricated event index or input multiplicity. Copy the pointer-free payload to retain it. Do not mutate/destroy entry, context or borrowed submission resources, or recursively submit UI, inside its handler. `cui_color_entry_sync` silently replaces committed/preview and canonicalizes the draft (uppercase, alpha only when nonopaque). A dirty draft yields CONFLICT unless `replace_draft` is true. Success recreates the editor with empty undo history; allocation failure restores the old draft and leaves the old editor/model intact. Call only outside submissions, after prior draw consumption. Owner sync to absent clears selection and draft. `cui_color_entry_restore` discards draft/preview and restores the committed value by the same silent replacement path. The pure set-draft and commit operations do not notify UI observers. Theme changes affect field paint, not selection or draft. Incomplete text is not automatically presented as a source-defined validation error: the frozen source has no separate error/status taxonomy. Headless tests verify textbox names, readonly/disabled facts and actual theme backgrounds, not native AT announcements. This first slice stores byte RGBA. Frozen upstream keeps floating HSLA and uses truncating automatic hex formatting; half float alpha can format as `7F`, while byte alpha 128 formats as `80`. Exact float-HSLA precision, popup focus/actions, palette/HSLA tabs, featured theme palettes and optional trigger presentation remain next-review work. Screen sampling remains a host async capability; this API adds no native eye-dropper. Python, Node/TypeScript, Go and Rust builders do not yet expose this entry model. No full ColorPicker parity is claimed. For focused local verification, configure `tests/fixtures/color_entry` with `-DCUI_LIBRARY=/absolute/path/to/matching/libcui.a` and a private Release build directory, then use `python scripts/test_local.py --build-dir `. The fixture enables assertions and strict warnings and also runs existing picker, picker-event and Input regressions. Set TMPDIR to a private home-cache directory on hosts with limited `/tmp` quota. It does not install dependencies or use the maintainer's desktop. Integrator registration: add `src/base/cui_color_entry.c` and `src/components/cui_color_entry.c` to the CUI library, then the three new test executables from `tests/unit/test_color_entry*.{c,cpp}`, linked to `cui` (C++17 for the header check). No extra platform library is needed. Existing picker and Input regressions in the private fixture link the supplied matching static CUI library. For standalone amalgamation, embed the guarded private declaration block from `src/base/cui_color_entry_internal.h` before both new sources and remove their relative internal-header includes; the private block's public-header include is handled like other CUI includes. Keep private declarations out of the public header. All added private functions/types use the ColorEntry prefix. --- ## Float-HSLA inline color entry Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COLOR_HSLA_ENTRY.md # Float-HSLA inline color entry `cui_color_hsla.h` supplies reusable normalized float HSL/encoded-RGBA conversions and source-format hex operations. It depends only on Core declarations, and the primitive implementation can link independently with the math library. This is HSL lightness, not HSV brightness; encoded RGB is unpremultiplied and receives no sRGB transfer-function conversion. It is separate from Plot's linear shader seam. `cui_color_hsla_entry.h` adds a caller-owned float selection/preview/draft model and a real Input field. Existing byte `cui_color_entry`, HSV `cui_color_picker`, theme parsing, Plot and their event contracts remain unchanged. Handwritten Python, Node/TypeScript, Go and Rust builders do not expose this new model. Use normalized finite components in inclusive 0..1. Checked operations reject NaN, infinity or out-of-range values atomically; they do not wrap hue, clamp, snap to steps or discard latent hue on achromatic colors. Hue 1 is retained as owner state, although it renders like hue 0. Optional absence differs from a present transparent color. C float preserves source-scale precision, without promising bit-identical arithmetic on every C platform. Initialize a zeroed `cui_color_hsla_entry_state` once and retain its address. The editor borrows its ten-byte owned draft; the state cannot be copied/moved, and its members are read-only to callers. Destroy after the final draw list has been consumed. Repeated destroy is safe. Init/sync/preview/restore/direct-value commit format locally and allocate a fresh editor before publishing new float fields. Allocation failure restores the old buffer/editor/history/model; success resets Input state and undo history. Do not call these operations during field submission or while prior draw data remains borrowed. `cui_color_hsla_entry_sync` silently copies optional owner committed/preview values and derives display text. Dirty draft conflicts unless replacement is explicit, even for an equal owner. Preview replaces only preview/display; restore returns to committed display. Both respect dirty replacement and leave committed unchanged. Set-draft admits empty text or hash followed by up to eight ASCII hex digits; complete text previews, incomplete text retains the last valid preview. Empty text cannot commit or clear selection; silent owner sync to absent clears it. The crucial precision distinction is explicit commit versus derived display: - Sync, direct HSLA preview/commit, ordinary frames and theme changes retain the supplied float components. Formatting is never fed back through the hex parser. - Hex parsing accepts optional hash and 3/4/6/8 digits, expands nibbles, divides bytes by 255, then converts float RGB to HSL. No CSS names/functions/decimal channel grammar is included. The UI additionally requires hash (or empty draft). - Source-style formatting truncates channels and omits alpha only when opaque: float alpha `.5` displays `7F`. Explicit hex commit reparses even an unchanged formatted draft, so Enter on that display commits `127/255`, not `.5`. Direct `commit_value` retains `.5`. This deliberate distinction matches the frozen source's suppression of programmatic display feedback. Conversions write output only on success. Hex parse writes only on COMPLETE; NULL output validates. The formatter reports required payload bytes (7 or 9), capacity includes NUL, and insufficient capacity leaves destination untouched. NULL/0 probes length and returns CAPACITY; NULL/nonzero is invalid. Invalid arguments report required zero. Inputs/outputs must be disjoint. No universal byte-exact float hex round-trip or cross-platform GPU arithmetic claim is made. Commit results distinguish SELECT (close requested) and UPDATE (no close request). Both succeed for same-value commits. The inline field owns no popup, so a close request is not a completed dismissal. The actual Input field handles focused, accepted nonrepeated Enter as SELECT in queue order; consumed, IME-owned, disabled, readonly, inert or layout-only paths do not commit. Invalid admission is `input.rejected`; submitting admitted incomplete text increments the separate rejected-commit count. Counts do not depend on installing an observer. The outer observer receives one copied summary after Base semantics or styled paint if at least one commit completed. Previous is the entry selection at the start of submission; final committed may differ from preview if text follows Enter in the same frame. Metadata is UNKNOWN with actual eligible frame only, without invented source/index/activation facts. The payload is pointer-free and can be copied beyond callback/context lifetime. Handler/user/options are entry snapshots; borrowed label/user must survive return. Do not mutate/free live entry, context or borrowed resources, or recursively submit UI, inside the callback. Update a separate owner and sync before the next submission. The executable owner example is [`tests/unit/test_color_hsla_entry_owner.c`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_color_hsla_entry_owner.c). It submits the real styled field, enters shorthand text and commits with Enter, then applies a separately copied owner value on the next submission. The focused fixture compiles and runs it, with C++ header compatibility and existing byte ColorEntry/Picker/Picker Events/Input regressions. `test_color_hsla_model.c` uses linker-wrapped real editor allocation failures to verify rollback at every editor allocation budget; no public allocator test hook is introduced. The primitive test links without CUI implementations to prove independent reuse. Configure `tests/fixtures/color_hsla` with a matching `-DCUI_LIBRARY=/path/libcui.a` and a private Release build directory. The failure fixture uses GNU/ELF linker wrapping and is not a claim of Windows/macOS allocator-injection coverage. Build with strict warnings, then run `python scripts/test_local.py --build-dir ` with a private home-cache TMPDIR. Assertions remain enabled in Release. The semantic tests prove textbox naming/readonly/disabled facts and theme backgrounds, not native AT announcements or hardware rendering. This slice has no popup/open owner, palette/HSLA tabs, slider UI, native screen sampler or foreign builders. The next popup coordinator must apply SELECT close requests before its own outer notification, preserving source close-before-Change timing; it cannot simply forward an early inner callback. Future sliders must use direct float updates and avoid rewriting an active drag from formatted hex. These remain separately reviewed work; full ColorPicker parity is not claimed. Integrator guidance: register new Base sources `cui_color_hsla.c` and `cui_color_hsla_entry.c`, and styled `src/components/cui_color_hsla_entry.c`. Keep primitive tests linked only to the primitive implementation and `m`; field tests and owner example link CUI. The failure-injection test additionally needs `--wrap=malloc`, `--wrap=calloc`, `--wrap=realloc`. Embed guarded private `src/base/cui_color_hsla_entry_internal.h` before both entry sources when generating standalone headers; no private declarations belong in public headers. Canonical source metadata, SDK/dist/skill generation and standalone/CUI_ALL verification remain the integrator's next gate. --- ## Command Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMMAND.md # Command Command is an inline command palette, composed from the real persistent Input, virtual rows and Scroll control. The scroll area spans the panel width; rows reserve space for its scrollbar and horizontal insets. An application can host it in the existing Dialog/Overlay. This module follows the pinned upstream 0.7.1 `component/src/command/{command,item,state}.rs` contracts; it does not supply a native application Action registry or automatically create a modal dialog. ```c char query_buffer[256] = {0}; cui_edit *query = cui_edit_create((cui_edit_config){ .buffer = query_buffer, .capacity = sizeof(query_buffer)}); cui_command_row workspace[64]; cui_command_state state; cui_command_init(&state, workspace, 64, query); cui_command_item settings[] = { {.label = cui_string("Profile"), .icon = cui_string("user")}, {.label = cui_string("Billing"), .disabled = true}, }; cui_command_entry entries[] = { {.kind = CUI_COMMAND_ITEM, .item = {.label = cui_string("Calendar")}}, {.kind = CUI_COMMAND_SEPARATOR}, {.kind = CUI_COMMAND_GROUP, .heading = cui_string("Settings"), .items = settings, .item_count = 2}, }; cui_command_options options = cui_command_default(); options.label = cui_string("Commands"); cui_command(ui, id, &theme, &state, entries, 3, options); ``` Initialize once, submit each frame, and destroy the editor after the state is no longer rendered. Workspace and editor remain application-owned. Model-only use can initialize with a null editor. The base source links without Core, Theme or Edit implementations, and allocates nothing. Entries, strings, keyword arrays and callback users are borrowed until the next rebuild. Keep them alive through rendering and any direct model operation such as `cui_command_confirm`. Rebuilding validates the worst-case unfiltered row capacity before writing; include headings and every supplied separator in that capacity. The module limits workspace and supplied items to 4096. Bad model or capacity leaves the existing model unchanged. Measurement must produce finite, positive outer row heights no greater than one million logical pixels. Filtering trims whitespace, then matches a case-insensitive substring in the label or any keyword. Default folding handles ASCII; supply `options.matches` for Unicode case folding or another host search policy. Turning off filterable keeps all rows but still reports searchable query changes. Turning off searchable hides the Input, retains all rows and suppresses query callbacks, including for a programmatically modified hidden editor. Original indices survive filtering: all ungrouped items use section zero in input order. Groups use their group ordinal, offset by one when any ungrouped item exists. Empty groups hide their headings. Leading, trailing and repeated separators are omitted. Disabled items remain visible and count as matches, but cannot be selected or confirmed. Up/Down wrap through enabled items. Enter invokes the selected action first, then the confirmation callback, including for items with no action. Pointer entry changes the highlight without scrolling; a click confirms. Row pointer capture is exercised across separate press, movement and release frames. Keyboard changes request nearest scrolling; a model reinstall preserves an eligible original path and does not move the viewport. Explicitly cleared selection remains cleared until navigation or a query change. A changed query resets to the first enabled result and calls selection before query. Callbacks run synchronously after the model update; callers may inspect state, but must not destroy the UI/editor/state or invalidate borrowed model storage while a render call is in progress. Unlike upstream deferred callbacks, CUI has no window lease or liveness object: application dispatch owns that lifecycle boundary. `action` and `binding` share an `action_user`; the host resolves a live binding for the same executable action. The default row draws its resolved hint using Kbd. A binding takes precedence over a checked mark. Custom content owns its keybinding presentation, and checked custom items still receive the source's trailing check. Application scope/keymap registration and platform-specific Action dispatch remain host responsibilities. Default list maximum is 300 logical pixels. Frame uses popover colors, a one-pixel border and radius_lg; bordered=false removes that frame. List inset is 4, default rows use horizontal8/vertical6 padding and font14/line20; headings use font12/line16, and separators occupy9. Theme density scales those metrics. The 380-pixel default width is a portable convenience; negative width grows. Growing palettes use retained width for measurement with an initial380 estimate. Default labels use a clipped single-line box; automatic arbitrary intrinsic wrapping/measurement is not implemented. A row's `measure` callback receives available outer content width and font size, returns its complete outer height, and can implement wrapping/custom variable heights. It must agree with its content callback. Every flattened row is measured each submission; only visible rows invoke content and submit semantic/paint nodes. This has bounded O(n) measurement and avoids drawing all offscreen children, but does not reproduce upstream's typography/action-binding row measurement cache. Header/footer/empty callbacks receive current state and render arbitrary CUI content. Loading shows the actual Icon spinner beside Input and suppresses the empty slot. Placeholder, empty message and accessible label can be supplied by the application for localization. ListBox/Option semantics expose selection, disabled state and busy status. Quick-action mode focuses the Command frame; searchable mode focuses the actual Input. Row options have no Tab stop, while application-provided child controls retain their own semantics. For Dialog composition set `cui_surface_options.no_escape_dismiss=true`. Command consumes the first Escape when a searchable query is nonempty. Empty query Escape calls `on_cancel` and remains unconsumed; let that callback request `cui_surface_request_close(ui, surface, CUI_SURFACE_CANCELLED)`. The next surface submission applies the decision policy, removes the modal and restores trigger focus. Do not immediately destroy/close the host from an action callback. The headless suite exercises this actual Surface composition, including the two Escape presses and focus restoration. Link the base and component sources into normal CUI. Styled implementation uses Components/Input, Edit, Scroll, Icon and Content/Kbd. Tests additionally use Surface/Overlay for modal composition. A base-only test defines `CUI_COMMAND_BASE_ONLY` and links `src/base/cui_command.c` plus math only. --- ## Component reference and full parity backlog Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMPONENTS.md # Component reference and full parity backlog Baseline: upstream kit 0.7.1. This is an original functional breakdown informed by the upstream catalog and pinned source. It is not a claim of equivalent implementation. Read [machine-readable status](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/gpui-parity.json) for evidence and limitations. Upstream reference documentation: https://gpui-kit.com/component/ (upstream kit, CC BY 4.0). No upstream prose or illustrations reproduced here. ## Accordion Reference: https://gpui-kit.com/component/accordion/ - single/multiple expanded items - controlled state and disabled items - keyboard focus and disclosure semantics ## AlertDialog Reference: https://gpui-kit.com/component/alert-dialog/ - modal focus trap and restore - confirm/cancel actions - dismissal policies and semantics ## Alert Reference: https://gpui-kit.com/component/alert/ - severity variants - title/content/action slots - accessible announcement ## Attachment Reference: https://gpui-kit.com/component/attachment/ - file/media metadata - preview/remove actions - loading/error states ## Avatar Reference: https://gpui-kit.com/component/avatar/ - image source and fallback initials - size variants - image failures and accessible name ## Badge Reference: https://gpui-kit.com/component/badge/ - count and dot variants - overflow count - theme and accessible content ## Bubble Reference: https://gpui-kit.com/component/bubble/ - incoming/outgoing alignment - message/reaction slots - theme variants ## Button Reference: https://gpui-kit.com/component/button/ - pointer press/release/capture - keyboard activation and focus - disabled/loading/error states - variants/sizes/icons/slots ## Checkbox Reference: https://gpui-kit.com/component/checkbox/ - unchecked/checked/mixed state - controlled value and activation - disabled/keyboard/semantic state ## Clipboard Reference: https://gpui-kit.com/component/clipboard/ - OS read/write adapter - capability failure handling - headless adapter tests ## Collapsible Reference: https://gpui-kit.com/component/collapsible/ - controlled disclosure - keyboard trigger - semantic expanded relation ## DropdownButton Reference: https://gpui-kit.com/component/dropdown-button/ - split primary and menu actions - keyboard opening and focus restore - disabled/loading state ## Empty Reference: https://gpui-kit.com/component/empty/ - title/description/media/action slots - themed layout - accessible content ## Focus Trap Reference: https://gpui-kit.com/component/focus-trap/ - tab and reverse cycling - nested scope and restore - disabled/removed target cleanup ## GroupBox Reference: https://gpui-kit.com/component/group-box/ - title/content slots - themed border/layout - group semantics ## HoverCard Reference: https://gpui-kit.com/component/hover-card/ - hover/focus delay - popup placement/collision - dismissal and accessible relationship ## Icon Reference: https://gpui-kit.com/component/icon/ - original/licensed vector set - size/stroke/theme - accessible/decorative distinction ## Image Reference: https://gpui-kit.com/component/image/ - host resource lifecycle - scaling/clipping/fallback - loading/error/accessibility ## Kbd Reference: https://gpui-kit.com/component/kbd/ - platform key labels - grouped shortcut rendering (ordinary sibling composition; see [Kbd guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/KBD.md)) - accessible description ## Label Reference: https://gpui-kit.com/component/label/ - UTF-8 text and theme size - control association - disabled/error presentation ## Marker Reference: https://gpui-kit.com/component/marker/ - status/separator modes - semantic content - themed styling ## Message Reference: https://gpui-kit.com/component/message/ - sender/time/content slots - attachments and reactions - accessibility and alignment ## MessageScroller Reference: https://gpui-kit.com/component/message-scroller/ - variable-height virtualization - stable keys and incremental updates - tail following/scroll restore ## Notification Reference: https://gpui-kit.com/component/notification/ - toast queue/lifetimes - actions/dismissal - accessible live region ## Pagination Reference: https://gpui-kit.com/component/pagination/ - controlled page bounds - keyboard and disabled actions - page-count/ellipsis presentation ## Progress Reference: https://gpui-kit.com/component/progress/ - determinate and indeterminate - value semantics - theme variants and reduced motion ## Radio Reference: https://gpui-kit.com/component/radio/ - group exclusivity and roving focus - controlled selection - disabled/keyboard semantics ## Rating Reference: https://gpui-kit.com/component/rating/ - pointer and keyboard value - read-only/disabled states - fractional values and semantics ## Shimmer Reference: https://gpui-kit.com/component/shimmer/ - animation scheduling - reduced-motion fallback - loading region semantics ## Skeleton Reference: https://gpui-kit.com/component/skeleton/ - placeholder sizes/layout - loading semantics (decorative Skeleton plus application-owned busy region; see [example](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/loading_region/README.md)) - theme/motion states ## Spinner Reference: https://gpui-kit.com/component/spinner/ - animation scheduling - sizes and theme - reduced motion and status semantics ## Stepper Reference: https://gpui-kit.com/component/stepper/ - steps/current/completed state - navigation/validation (controlled requests and application-owned validation; see [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/STEPPER_NAVIGATION.md)) - keyboard and semantic progress ## Switch Reference: https://gpui-kit.com/component/switch/ - controlled binary activation - keyboard/pointer/disabled behavior - semantic checked state and theme ## Tag Reference: https://gpui-kit.com/component/tag/ - semantic/custom/named palettes, outlines, sizes and radius - passive accessible text and arbitrary rich children - hover opacity and inherited theme styling ## Toggle Reference: https://gpui-kit.com/component/toggle/ - controlled pressed state - keyboard/pointer/disabled behavior - pressed semantics/theme variants ## Tooltip Reference: https://gpui-kit.com/component/tooltip/ - hover/focus timing - popup collision - dismissal and accessible description ## Calendar Reference: https://gpui-kit.com/component/calendar/ - date/leap-year/month geometry - min/max bounds and range selection - keyboard/localized semantics ## ColorPicker Reference: https://gpui-kit.com/component/color-picker/ - color-space model and conversion - picker geometry and pointer drag - keyboard/validation/theme ## Combobox Reference: https://gpui-kit.com/component/combobox/ - filter/single/multiple selection - active descendant and keyboard - popup focus/dismissal/accessibility ## DatePicker Reference: https://gpui-kit.com/component/date-picker/ - calendar popup composition - parse/format and bounds - keyboard/localization/accessibility ## Editor Reference: https://gpui-kit.com/component/editor/ - UTF-8 grapheme editing and selection - undo/redo and multiline indentation - gutter/wrap/find/replace - highlight/diagnostic/completion callbacks - 200K-line benchmark ## Form Reference: https://gpui-kit.com/component/form/ - field registration and validation - error/required labels - submit/reset and keyboard ## Input Reference: https://gpui-kit.com/component/input/ - UTF-8 insertion/deletion/selection - clipboard and IME - undo/redo and grapheme boundaries - validation/disabled/error/semantic states ## Input Group Reference: https://gpui-kit.com/component/input-group/ - prefix/suffix/button slots - focus and disabled propagation - validation and layout ## NumberInput Reference: https://gpui-kit.com/component/number-input/ - numeric parsing and bounds - increment/decrement/step - keyboard/disabled/semantic value ## OtpInput Reference: https://gpui-kit.com/component/otp-input/ - segmented input focus - paste and validation - keyboard/accessible labels ## Questionnaire Reference: https://gpui-kit.com/component/questionnaire/ - step and answer models - validation/navigation - compound UI semantics ## Select Reference: https://gpui-kit.com/component/select/ - single/multiple controlled selection - keyboard active descendant - popup dismissal/focus restoration ## Slider Reference: https://gpui-kit.com/component/slider/ - pointer drag capture - keyboard range/step/clamp - controlled value and semantics - disabled/theme variants ## Speech Reference: https://gpui-kit.com/component/speech/ - capability/permission adapter - recognition callback lifecycle - fake adapter tests and explicit unavailability ## Textarea Reference: https://gpui-kit.com/component/textarea/ - multiline editing/selection - wrap and auto-grow - clipboard/IME/undo/semantics ## TimeField Reference: https://gpui-kit.com/component/time-field/ - segmented hour/minute/second model - parse/validation/localization - keyboard/semantic segments ## Carousel Reference: https://gpui-kit.com/component/carousel/ - controlled current item - keyboard/drag navigation - accessible position and theme ## DescriptionList Reference: https://gpui-kit.com/component/description-list/ - key/value composition - responsive layout - list semantics ## Dialog Reference: https://gpui-kit.com/component/dialog/ - modal overlay/dismissal - focus trap/restore - title/description/action slots ## Dock Reference: https://gpui-kit.com/component/dock/ - nested splits and tab groups - drag reorder/resize/edge docks - versioned serialization/restore - focus and keyboard behavior ## List Reference: https://gpui-kit.com/component/list/ - selection and item keys - keyboard navigation - item rendering and semantics ## Menu Reference: https://gpui-kit.com/component/menu/ - roving item focus/actions - nested popup collision - dismissal/restore/disabled semantics ## Popover Reference: https://gpui-kit.com/component/popover/ - anchor placement/collision - controlled open/dismissal - focus and accessible relationship ## Resizable Reference: https://gpui-kit.com/component/resizable/ - split geometry/min/max - pointer drag and keyboard resize - semantic separator and persistence ## Root View Reference: https://gpui-kit.com/component/root/ - theme/overlay/notification providers - window lifecycle and focus scopes - safe area/scaling ## Scrollable Reference: https://gpui-kit.com/component/scrollable/ - scroll bounds and nested clipping - wheel/drag scrollbar - keyboard and coordinate hit testing ## Settings Reference: https://gpui-kit.com/component/settings/ - grouped settings models - validation and persistence hooks - keyboard/accessibility composition ## Sheet Reference: https://gpui-kit.com/component/sheet/ - edge placement and transition - focus trap/restore/dismissal - theme/reduced motion ## Sidebar Reference: https://gpui-kit.com/component/sidebar/ - hierarchical navigation - collapsed/selected/disabled state - keyboard and accessible navigation ## StatusBar Reference: https://gpui-kit.com/component/status-bar/ - left/center/right slots - density/theme variants - accessible status ## Tabs Reference: https://gpui-kit.com/component/tabs/ - controlled selected tab - roving keyboard focus - tab/panel semantic relationship ## Theme Reference: https://gpui-kit.com/component/theme/ - runtime light/dark and tokens - per-component overrides/density - system preference/high contrast/reduced motion ## TitleBar Reference: https://gpui-kit.com/component/title-bar/ - window controls and host chrome - drag/maximize integration - platform semantics/theme ## Toolbar Reference: https://gpui-kit.com/component/toolbar/ - left/center/right slots - keyboard group navigation - size/theme variants ## Tree Reference: https://gpui-kit.com/component/tree/ - hierarchical model/expand/selection - keyboard parent/child navigation - virtualization and tree semantics ## VirtualList Reference: https://gpui-kit.com/component/virtual-list/ - variable-height efficient offsets - stable keyed incremental items - viewport overscan and scroll restore - 1K/10K/100K benchmark ## Chart Reference: https://gpui-kit.com/component/chart/ - line/bar/area/pie/candlestick series - axes/scales/ticks/legend - hover and accessible data - theme and headless models ## Command Reference: https://gpui-kit.com/component/command/ - fuzzy filtering and action model - keyboard navigation and focus restore - shortcut contexts and dismissal ## DataTable Reference: https://gpui-kit.com/component/data-table/ - column models/sort/resize/pinning - cell/row selection keyboard and mouse - row virtualization/remote callbacks - header/footer/table semantics ## Plot Reference: https://gpui-kit.com/component/plot/ - linear/log/category/time scales - axes/ticks/series/legend - zoom/hover/selection - headless geometry and themed output ## Table Reference: https://gpui-kit.com/component/table/ - semantic row/column/header/footer - selection/sorting/resizing - themed cells and keyboard behavior ## TextView Reference: https://gpui-kit.com/component/text-view/ - safe Markdown/HTML subset parser - Unicode text selection and links - inline code/lists/tables - no script execution and parser fuzzing --- ## Component status Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMPONENT_STATUS.md # Component status Generated from [component manifest](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/gpui-parity.json). Status describes the tested slice, not complete parity. Run `python scripts/cui_status.py Input Icon Sidebar` for features, evidence, and full limitations. Regenerate with `--write-summary`. | Component | Status | Reference | | --- | --- | --- | | Accordion | tested | [cui_disclosure.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_disclosure.h) | | AlertDialog | tested | [cui_surface.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_surface.h) | | Alert | tested | [cui_content.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) | | Attachment | tested | [cui_media.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_media.h) | | Avatar | tested | [cui_content.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) | | Badge | tested | [cui_components.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) | | Bubble | tested | [cui_content.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) | | Button | tested | [cui_components.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) | | Checkbox | tested | [cui_components.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) | | Clipboard | tested | [cui_sdl3.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_sdl3.h) | | Collapsible | tested | [cui_disclosure.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_disclosure.h) | | DropdownButton | tested | [cui_choice.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h) | | Empty | tested | [cui_content.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) | | Focus Trap | tested | [cui_overlay.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_overlay.h) | | GroupBox | tested | [cui_content.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) | | HoverCard | tested | [cui_content.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) | | Icon | tested | [cui_icon.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_icon.h) | | Image | tested | [cui_media.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_media.h) | | Kbd | tested | [cui_content.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) | | Label | tested | [cui_components.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) | | Marker | tested | [cui_status.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_status.h) | | Message | tested | [cui_message.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_message.h) | | MessageScroller | tested | [cui_message.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_message.h) | | Notification | tested | [cui_status.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_status.h) | | Pagination | tested | [cui_numeric.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_numeric.h) | | Progress | tested | [cui_components.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) | | Radio | tested | [cui_components.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) | | Rating | tested | [cui_numeric.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_numeric.h) | | Shimmer | tested | [cui_status.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_status.h) | | Skeleton | tested | [cui_skeleton_presentation.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_skeleton_presentation.h) | | Spinner | tested | [cui_content.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) | | Stepper | tested | [cui_numeric.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_numeric.h) | | Switch | tested | [cui_components.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) | | Tag | tested | [cui_status.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_status.h) | | Toggle | tested | [cui_components.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) | | Tooltip | tested | [cui_content.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) | | Calendar | tested | [cui_picker.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_picker.h) | | ColorPicker | tested | [cui_picker.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_picker.h) | | Combobox | tested | [cui_choice.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h) | | DatePicker | tested | [cui_picker.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_picker.h) | | Editor | tested | [cui_editor.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_editor.h) | | Form | tested | [cui_form.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_form.h) | | Input | tested | [cui_components.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) | | Input Group | tested | [cui_form.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_form.h) | | NumberInput | tested | [cui_numeric.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_numeric.h) | | OtpInput | tested | [cui_otp.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_otp.h) | | Questionnaire | implemented | [cui_questionnaire.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_questionnaire.h) | | Select | tested | [cui_choice.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h) | | Slider | tested | [cui_components.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) | | Speech | tested | [cui_speech.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_speech.h) | | Textarea | tested | [cui_textarea.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_textarea.h) | | TimeField | tested | [cui_picker.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_picker.h) | | Carousel | tested | [cui_carousel.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_carousel.h) | | DescriptionList | tested | [cui_description.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_description.h) | | Dialog | tested | [cui_surface.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_surface.h) | | Dock | tested | [cui_dock.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_dock.h) | | List | tested | [cui_choice.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h) | | Menu | tested | [cui_choice.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h) | | Popover | tested | [cui_surface.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_surface.h) | | Resizable | tested | [cui_resizable.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_resizable.h) | | Root View | tested | [cui_root.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_root.h) | | Scrollable | tested | [cui_scroll.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_scroll.h) | | Settings | tested | [cui_settings.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_settings.h) | | Sheet | tested | [cui_surface.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_surface.h) | | Sidebar | tested | [cui_sidebar.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_sidebar.h) | | StatusBar | tested | [cui_chrome.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_chrome.h) | | Tabs | tested | [cui_choice.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h) | | Theme | tested | [cui_theme.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_theme.h) | | TitleBar | tested | [cui_chrome.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_chrome.h) | | Toolbar | tested | [cui_toolbar.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_toolbar.h) | | Tree | tested | [cui_tree.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_tree.h) | | VirtualList | tested | [cui_virtual_scroll.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_virtual_scroll.h) | | Chart | tested | [cui_chart.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_chart.h) | | Command | tested | [cui_command.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_command.h) | | DataTable | tested | [cui_table.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_table.h) | | Plot | tested | [cui_plot_view.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_plot_view.h) | | Table | tested | [cui_table.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_table.h) | | TextView | tested | [cui_text_view.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_text_view.h) | --- ## Compound paint identities Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMPOUND_SHADOW_PARTS.md # Compound paint identities Development additions after alpha.3: use a matching current source checkout and headers/facades. These APIs are absent from the published alpha.3 packages. The additive C getters in `cui_content.h`, `cui_message.h`, `cui_status.h` and `cui_media.h` expose the existing identities of compound parts. They do not submit, open, allocate or query the presence of a box. Zero owners/scopes, invalid enums, invalid indices and null scroller state return zero without changing diagnostics. A valid identity may belong to an omitted, offscreen, layout-only or custom part. Submit the component first, then call `cui_element_set_box_shadows` before `cui_end_frame`, outside prepaint, measurement and diagnostic callbacks. Check the setter's result: previous `cui_bounds` are not proof of current-frame presence. The setter copies the layers; normal Core limits, clipping and failure behavior apply. Getters preserve legacy emitted IDs, including the legacy painters' separate zero-owner behavior. Existing action getters retain their original zero handling. | Component | Getters and actual owners | | --- | --- | | Composed Bubble | `cui_bubble_part_id`: SURFACE is the painted bubble, REACTIONS the conditional reaction container. The caller ID is the outer row. For direct `cui_begin_bubble`, the caller ID itself is the surface; the composed getter does not apply. | | Message | `cui_message_part_id`: AVATAR, HEADER, FOOTER. `cui_message_body_id(owner,index)` accepts indices below 256. A typed body owns its bubble surface; an untyped body owns its slot row. Optional/custom callbacks may omit boxes even when the namespace is valid. | | MessageScroller | `cui_message_scroller_part_id`: VIEWPORT and conditional JUMP. `cui_message_scroller_row_id(owner,state,index)` uses the current retained row key. Prepending preserves retained row identities; removal/reset invalidates assumptions about old indices. State must remain alive. Offscreen rows have identities but no current-frame paint owner. | | Notification | `cui_notification_part_id(scope,logical,part)`: CARD, CONTENT, ACTION, CLOSE. The logical `{type,key}` is not a paint ID, and the scope is not a submitted card. System-only, removed and fully hidden/layout-only cards cannot receive shadows. ACTION is a custom callback namespace or the default action button; CLOSE is conditional. The existing 128-bit logical-key to 64-bit paint mapping can collide: identity is not uniqueness or presence validation. | | Attachment | `cui_attachment_part_id`: CARD, MEDIA, MEDIA_OVERLAY, METADATA, ACTIONS, REMOVE, MEDIA_RETRY. `cui_attachment_child_part_id` accepts original child-array indices below 128 and ROW or RETRY. Child RETRY identifies the first eligible description's textual retry, distinct from MEDIA_RETRY. Media overlays/actions may be portals; custom callbacks may emit no box. No synthetic owner is added for absent parts. | ```c cui_bubble(ui, id, theme, options); cui_box_shadow shadow = { .kind = CUI_BOX_SHADOW_DROP, .layer = {.offset_y = 2, .sigma = 2, .color = {0, 0, 0, 80}} }; bool styled = cui_element_set_box_shadows( ui, cui_bubble_part_id(id, CUI_BUBBLE_PART_SURFACE), &shadow, 1, (cui_corner_radii){0}); ``` These are C identities, not new language-builder targets. Python, JavaScript, TypeScript, Go and Rust compound MAIN/ROOT/subpart authoring remains pending; [the design](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPOUND_SHADOW_PARTS.md) describes future mapping without claiming binding coverage. Use matching canonical headers and rebuilt libraries, standalone headers or SDKs. No public by-value layout changed. The 12 focused headless checks pass: the getter/legacy/element-shadow tests, existing Content/Message/Status/Media and three Base-only regressions, and selective/umbrella generated-header C11 declaration/link smoke tests. The legacy fixture was recorded and replayed before rebuilding, against the pre-change shared library with SHA-256 `7438a27c6e37855efe0d3e6009a29e0cad83faa56c1c830097695c700c1dd99b`. It records 20 scenes across five facades, including zero owners, normalized commands, layout IDs, semantics and callback order without reproducing ID salts. The frozen binary-value fixture is limited to 64-bit little-endian hosts; the getter tests are portable. These headless tests establish no native GPU/browser rendering or complete component/binding parity. --- ## Content components Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CONTENT.md # Content components `cui_content.h` adds controlled alert dismissal; named avatar initials; composable bubble and group surfaces; empty states; keyboard hints; loading indicators; dividers; and a shared delayed hover lifecycle. These portable C11 APIs use the existing theme and draw list. They do not imply complete upstream kit family parity. Alerts carry text naming their severity, an optional title, custom textual icon, banner style, width, and size multiplier. A dismiss button reports activation and updates optional application-owned visibility. Passing false visibility omits the entire subtree next frame. Success and warning currently use the theme primary color with distinct text because the theme has no separate success/warning tokens. Rich content can instead be composed with boxes; the convenience alert renders plain text. Avatar fallback takes the first scalar of the first and last ASCII-whitespace-separated words, uppercases ASCII letters, and preserves valid non-ASCII UTF-8. Empty/invalid input produces `?`. Its semantic name retains the person's name. The circular surface has an explicit pixel size. Image loading, generated hue palettes, exact typographic centering, custom icons, and overlapping groups remain pending. Bubble and GroupBox begin/end pairs accept arbitrary child controls or text. Bubble offers filled, secondary, muted, tinted, outline, ghost, and destructive surfaces. The caller supplies child text colors and owns horizontal placement, maximum width, wrapping, reactions, and footer content. Empty provides title and description; a custom actionable empty state can use a GroupBox instead. Empty custom-image/icon slots and upstream's exact typography remain pending. Keyboard formatting takes modifier bits, the display key label, and an explicit platform convention. It supports Ctrl/Alt/Shift/Win labels and macOS symbols in stable order, reports required bytes, and bounds/NUL-terminates the output. The caller supplies special-key labels; action/keybinding lookup is application-owned. `cui_kbd` styles any resulting string. The legacy `cui_spinner` is an eight-dot phase ring with Loading status semantics and moving-frame invalidation. Use `cui_spinner_ex` for the source-style decorative Loader SVG, custom color/icon/easing/size and caller-owned bounded wake scheduling; see [Spinner](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SPINNER.md). Skeleton supports arbitrary size, radius, a secondary opacity, and a legacy cosine pulse; `cui_skeleton_ex` adds source-style caller-clocked motion. Reduced motion freezes both APIs. Divider accepts horizontal/vertical orientation and length. `cui_hover_update` is the reusable Tooltip/HoverCard timing reducer. Trigger hover and keyboard focus open after a configured delay. Once open, hovering content keeps it open; leaving starts a cancellable close delay. Escape or disabled closes immediately. Invalid time steps do not advance timers. `cui_tooltip` and the composable HoverCard begin/end pair now render viewport portals above their clipping ancestors. They observe previous-frame clipped trigger/card regions, support keyboard-focus opening, and flip/clamp popup placement to the provided viewport. Escape suppresses reopening until hover and focus leave the trigger. Cards keep open while their contents are hovered or a child retains focus; tooltips never own a focus stop. Trigger descriptions preserve existing semantic details. Applications supply viewport and popup dimensions and frame time; text/layout is clipped to those bounds. Automatic text sizing/wrapping, tooltip animation, collision avoidance among unrelated overlays, native accessibility announcements, and all upstream appearance options remain pending. HoverCard is nonmodal and does not trap or take keyboard focus. Headless tests verify UTF-8 validation, formatting truncation, lifecycle transitions, reduced motion and animated redraw, measured geometry, named semantic snapshots, controlled pointer dismissal, actual portal clipping escape, edge flipping, keyboard opening, hover-card retention, Escape suppression, trigger-description preservation, and omission of dismissed content across all four themes. The worker compiles the new files with C11 strict warnings, runs `test_content` linked to the core library, and runs the existing CTest suite. Build/distribution registration belongs to the integrator. Avatar initials in `cui_avatar_ex` support independent `custom_background` and `custom_foreground` flags with `background` and `foreground` colors. Zero options retain the theme primary/on-primary defaults; explicit colors apply only when the image is missing or invalid, including transparent colors. Photo ring colors continue to use `custom_ring`/`ring`. ## Explicit HoverCard tap mode and relationships [HoverCard extended policy](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/HOVER_CARD_EXTENDED.md) adds caller-accepted trigger toggles, a bounded outside-tap workspace and optional current-trigger controls/expanded snapshots. The legacy hover helper is unchanged. The additive raw-primary-release policy uses prior content-only bounds without down/movement requirements; strict outside taps remain the default. Collapsed native accessibility state and foreign wrappers remain separate work. Typed single-stroke hints and ordinary grouped composition are documented in [Keyboard shortcut hints](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/KBD.md). For decorative Skeletons with an application-owned busy region and completion status, see the [loading-region example](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/loading_region/README.md). These examples distinguish Core/DOM/native event evidence from unverified screen-reader speech. --- ## Foundational controls Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CONTROLS.md # Foundational controls ## Switch `cui_switch` retains the bool-pointer convenience interface and renders a real track and thumb. `cui_switch_ex` adds sizes, disabled state, accessible-name override, optional custom label content and tooltip, label placement, Tab exclusion, focus-ring suppression, custom checked color, and persistent spring motion. Zero options select Medium and the source defaults. Track sizes are 28×16 (Extra Small/Small), 36×20 (Medium), and 44×24 (Large); thumbs have a two-pixel inset. Theme radius below four preserves square themes. Disabled tracks halve their alpha, while the thumb remains opaque. Without `on_change`, activation writes the caller's bool. With it, the callback receives the requested value and the bool stays controlled by the application. It may update the bool synchronously; painting and checked semantics use the resulting actual value. Callbacks and content userdata are borrowed for the call. Enter, Space release, pointer activation on either track or label, and normal Tab traversal use the base Switch. `skip_tab` removes sequential focus without removing programmatic/pointer focus. A caller-owned, zero-initialized `cui_switch_state` enables the theme's `spring_move` response/damping/epsilon policy. Supply monotonic `now_seconds`; the first paint is immediate, changes retain position and velocity, and settled controls request no frames. `next_wake_seconds` exposes the next suggested wake while core invalidation requests a follow-up frame. Reduced motion, zero response, and disabled travel settle immediately. The convenience function (and an extended call with null state) paints without animation. The state also owns the optional tooltip reducer; its options need the normal viewport and elapsed-time inputs described in the surface documentation. Switch labels use explicit 16/20/24-pixel line heights, including wrapping. Tooltip hit ownership covers the complete control, rather than only the source track. Font weight and native SVG details remain dependent on the host text renderer. These are tracked gaps, not a claim of complete source parity. `label_left` is a C convenience extension (the frozen source has the field but exposes no public setter). ## Toggle and ToggleGroup `cui_toggle` now paints its label without an invented indicator. `cui_toggle_ex` adds Ghost (default) and Outline variants, four source sizes, arbitrary child content, accessible-name override, tooltip, Tab exclusion, optional focus outline, independent corner radii/edge widths, and the same controlled boolean callback contract as Switch. Pressed and enabled-hovered toggles use accent/accent-foreground; disabled presentation keeps the source colors and suppresses interaction. Extra Small/Small/Medium/Large have 20/24/32/36-pixel minimum widths and fixed heights, with horizontal padding 2/4/8/12. A composed icon or long label can grow the width. No automatic focus outline is painted, matching the frozen source; `focus_ring` is an explicit C accessibility option. `cui_toggle_group_ex` is the richer source composition. The existing Choice module's `cui_toggle_group` remains available with its older selection options. Supply stable, unique item IDs, caller-owned values, and per-item label/content/tooltip configuration. The passive horizontal Toolbar group overrides child size and variant and combines group/child disabled state. Selections are independent; it does not introduce radio exclusivity or roving focus. Ordinary groups have an eight-pixel gap; segmented groups have zero gap, only outside corners, and no repeated left border. `custom_gap` permits an explicit spacing override. Without a group callback, activation writes `values`. With a callback, provide a separate `requested_values` scratch array of at least `count` elements. Each activation copies the current rendered vector, flips its corresponding entry, and synchronously reports that request. The callback may update the owner values immediately. Callback vectors are borrowed only during the callback. Do not replace item/value storage during rendering. Child callbacks are superseded by the group, matching the source grouping contract. Pointer, Enter and Space all report the group request; keyboard delivery fixes a frozen source limitation. The arrays and tooltip reducers stay application-owned, and rendering allocates no persistent group state. Invalid sizes, variants, numeric geometry, duplicate IDs, malformed strings, and insufficient/overlapping request scratch suppress the call. Toggle labels use the source 1.25 line-height multiplier, subject to core integer layout quantization. Hosts provide icon content and font weight; these remain rendering gaps. --- ## Control surface shadow gallery Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CONTROL_SURFACE_SHADOW_GALLERY.md # Control surface shadow gallery Development additions after alpha.3: use a matching current source checkout and headers/facades. These APIs are absent from the published alpha.3 packages. On Button, Checkbox, Radio, Switch and Slider routes, **Surface shadows** enables an additive example. It starts off on each route; turning it off uses the existing legacy call. Button collection mode retains its existing route and disables this standalone demonstration. Component size, design scale, disabled state, alignment and existing event handlers remain available. Button's Run action uses `cui_button_surface_ex`: normal DROP, a larger hovered DROP, pressed INSET and an explicit empty list while disabled. The pure callback checks `info.disabled` even in its instance phase: the captured instance patch replays after disabled, so clearing only in a disabled callback would be wrong. Activation still uses the existing `on_click` exactly once. No shadow is implicit when the feature is off. Checkbox and Radio use explicit `cui_selection_indicator_parts` with their `*_with_parts` facades. Their decoration follows the selected value; it targets the indicator, not the label row or glyph. Switch uses the public track/thumb IDs; thumb DROP remains clipped by the track. Slider uses its public legacy track ID and an INSET layer; it does not acquire a named thumb or fill. Indicator radii follow current size/design metrics and actual shape; shadow radii are clamped by Core to the current caster bounds. Identity is not a presence check: submit first, then check the current-frame setter before end_frame. The copyable snippet contains real public-header C functions and follows the selected size/design tokens. Application state remains caller-owned. The examples use built-in control artwork; they introduce no text glyph icons. These C callbacks and named-part seams do not imply corresponding language-builder callback support. All 78 component/portal/glyph/binding shadow coverage remains open beyond the explicitly implemented and tested slices. The integrator built the combined WASM source at `a07bd7ce` and passed all ten component/viewport cases, including actual pixel differences, state/input checks and strict C11 compilation of copied usage snippets. Hosted integration and public deployment of these additions remain pending. Reproduce the focused headless check: ```sh nice -n 19 taskset -c 0 python tests/web/test_control_surface_shadow_gallery.py \ --directory /home/matteo/.cache/cui-current-validation/web \ --report /home/matteo/.cache/cui-current-validation/control-surface-shadow-gallery.json ``` The fixture compares actual canvas pixels with the legacy route at unchanged bounds, checks Button hover/press/disabled policy, performs real component clicks/Slider key input, checks values and design sizes, and restores the off route. Wide/DPR1 and narrow/DPR2 cases are included. `--compile-usage` additionally syntax-checks copied snippets with strict C11; it requires the integrator to allocate a compiler slot. GPU/desktop tests are unnecessary and are not proof provided by this fixture. --- ## Unreleased Core V2 background transport Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CORE_DRAW_V2.md # Unreleased Core V2 background transport Explicit C-only opt-in in `include/cui/cui_draw_v2.h`. Core mode/storage/setters and emission are implemented. The unreleased [C software adapter](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SOFTWARE_V2.md) queries actual support before composition and consumes the V2 list. SDL_Renderer, SDL_GPU, Sokol GLCORE, Canvas wire and foreign bindings remain mandatory follow-up, not completed parity. The [CPU preparation helper](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BACKGROUND_PREPARATION.md) supplies allocation-free building blocks. Do not pass a V2 list to a V1 renderer, cast command arrays or fabricate adapter support. The software guide includes the initialized query/begin/end/render sequence; synthetic test consumers do not establish any other adapter support. The [reviewed record/adapter contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/BACKGROUND_V2_RECORDS.md) retains the full five-adapter objective. Pure [background values/sampling](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BACKGROUND_VALUES.md) remain independently usable. Existing V1 APIs/config/records/enums/layout/input and default commands/pixels are unchanged; no V2 buffers are allocated by V1-only contexts. No component-wide or all78-parts coverage claim follows from setters. An actual consumer query must precede composition. Copy its exact-sized `cui_draw_v2_support` into exact-sized `cui_frame_v2_options`; select required features explicitly, then call `cui_begin_frame_v2` and matching `cui_end_frame_v2`. Unknown features/record version/output policy fail INVALID_ACTION; insufficient budgets/allocation fail CAPACITY. Admission reserves all optional storage before opening/consuming input. Replaced frame-only blocks are freed before growth allocation to bound peak memory; allocation failure leaves input queued and context usable, with no new active mode/frame. Previous V2 lists expire at begin attempt, including failed growth. Invalid option/budget validation never opens or consumes a frame. Wrong end reports LIFECYCLE without closing, finalizing layout or dispatching paint callbacks. Clear the diagnostic, then match the end once. Null V2 output rejects before closing. Matching end closes even on failure and returns an empty ABI2 non-OK list; never render/clear a non-OK list. Numeric snapshot invalidity from an in-frame diagnostic persists after clear; only a fresh successful frame restores readiness. No conversion occurs after semantic/readiness publication. `cui_set_background` addresses the actual open anonymous/named box; `cui_element_set_background` addresses a named box already submitted this frame, including a closed box or portal. No previous-frame geometry, new nodes, ID replacement, input routing or callback dispatch architecture. Reject suppressed, layout-only, missing/colliding targets and mutation from measurement/prepaint or diagnostics. Values validate/copy only active fields; inactive fields become zero. Invalid/capacity failure preserves the previous override and all other paint. NULL clears; transparent SOLID replaces the ordinary fill. Repeated calls reuse an owner slot; clear preserves other custom paint and the owner's slot until the next admitted begin. Distinct touched owners consume capacity even if cleared. Final-layout bounds and clamped box corner radii accompany the brush by value; ancestor opacity is separate and applied once by shared preparation. Replace ONLY box fill: DROP, outside outline, fill, INSET, mesh, locally clipped underlay, prepaint, children retain their order; deferred layers/portals retain their route. A no-setter V2 frame wraps ordinary V1 commands exactly. Legacy strings, bitmap pixels, mesh vertices and font/provider backing retain V1 borrowing; copying the array copies brushes, **not a complete resource snapshot**. Array lifetime ends at next begin attempt (either mode) or context destruction. Command capacity is min(config.max_commands,16384,support.max_commands, command_bytes/sizeof(cui_draw_command_v2)). Default16MiB, hard16MiB. Background capacity is min(config.max_elements,4096,support.max_backgrounds); its default512KiB budget must fit align_up(max_elements*sizeof(uint32_t),alignof(private owner)) plus capacity*sizeof(private owner record), in one aligned block. Hard16MiB, checked actual sizes. Feature-free V2 needs no owner map. Retain bounded high-water capacities until destruction; smaller later logical budgets do not shrink them or allocate duplicate frame copies. At most32MiB additional retained payload plus one fixed private control record; ordinary Core arrays/frame/resource budgets remain separate. No raster cache/upload allocation. All five support descriptor pixel/upload budgets are for future consumer admission; Core validates nonzero bounds when requesting backgrounds but cannot preflight physical pixels or target availability before layout/render. Validation combines the independent pre-V2 frozen V1 commands/software pixels, all24 scenes wrapped without setters, strict V1 ABI checks, faulted allocation, transactional owner/identity/clear tests, current portal move/resize, exact paint order/opacity/radii, wrong-mode/non-replay, typed numeric queue/claim and reentrancy. No GPU/browser/glyph rendering result is claimed for this Core-only slice. --- ## Core numeric accessibility input (unreleased) Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CORE_NUMERIC_ACCESSIBILITY.md # Core numeric accessibility input (unreleased) The additive declarations in `include/cui/cui.h` provide explicit numeric consumer capabilities, typed SET_VALUE queueing and current-semantic input claims. They do not implement a Slider model, bridge/binding authoring, native AccessKit numeric mapping, browser semantic bridge or physical assistive-technology acceptance. Existing Focus/Activate behavior and legacy Slider routes remain unchanged. ## Registration and completed authority A painted custom Slider semantic explicitly calls `cui_set_accessibility_numeric_actions(ui,id,mask)` after setting semantic details. Only INCREMENT/DECREMENT/SET_VALUE capability bits are supported. Registration is per current frame/semantic, not inferred from role. Disabled, readonly and modal scope still gate eligibility. Missing ID/wrong role/unknown mask/lifecycle rejects; inert/layout-only registration is ignored with false/no mutation. A zero mask before opt-in allocates nothing; first valid nonzero mask allocates bounded owned storage retained until context destruction. Capacity failure leaves registration and queues unchanged and reports CUI_ERROR_CAPACITY. `cui_accessibility_action_supported` remains an outside-frame completed-snapshot query. A legacy Slider that never registers has no numeric actions. Re-register every successful frame; omission/revocation does not inherit an old capability. Capability does not imply a value will change at a bound or that owner accepts it. `cui_accessibility_numeric_snapshot_ready` reports only valid completed Core semantics: false initially/in-frame/after invalidating failed begin/end, true after ordinary successful end even without numeric registration/storage. Clearing error alone cannot restore an invalidated snapshot. Known in-frame errors prevent new claims/publication even if cleared before end; only a fresh good frame restores readiness. A private invalid-frame marker persists until a new admitted begin. New scroll-layout opt-in failure always ends non-OK/empty and invalidates numeric authority until a successful fresh frame. Already claimed input is not rolled back by a later error. Renderer/native/platform success is not certified by readiness. Old Focus/Activate paths do not use the new predicate. `cui_frame_input_snapshot_ready` is the distinct in-frame observer: true only in ordinary admitted composition with valid prior completed Core geometry/semantics and no known invalidating current-frame error. It is false outside that phase; it does not certify final current geometry or current target/modal eligibility. An empty prior semantic list and zero numeric allocations/capabilities can still be ready. Inert/layout-only composition requires the separate frame_sequence eligibility check; readiness alone does not permit reduction. Known current errors remain invalid after clear, and only successful end establishes next-frame readiness. Legacy input routes do not consult either new gate. Every rejected V2 begin conservatively expires new numeric/input authority, including options, budget or allocation failures before common begin; existing error codes, queued input and old Focus/Activate routing are preserved. Failed buffer growth still expires the old V2 list under its existing lifetime contract. This observer does not implement the planned typed Slider UI reducer or any host delivery. ## Typed queue, ownership and claims Use existing `cui_queue_accessibility_action` for opted-in INCREMENT/DECREMENT. For SET_VALUE use `cui_queue_accessibility_set_value_v1` with exact payload size, version 1/reserved 0 and finite double in **published semantic numeric units**. The consumer defines domain/step conversion; Core does not infer it. Generic no-payload SET_VALUE is invalid; zero is a valid typed value, not missing data. The queue copies the scalar, so stack payload lifetime ends at return. Invalid, unsupported, lifecycle or queue-full failure preserves queued input. Existing sticky errors must be handled; only actual capacity failures justify retry. During painted submission, after current semantics/details/registration, inspect actual frame inputs and call `cui_claim_accessibility_numeric_input_v1` with exact output size. It rechecks target, previous/current Slider role/capability, enabled/ readonly/modal eligibility and unconsumed input. Success returns owned v1 action/ target/flags/value and consumes once. Failure preserves output and consumption. Input consumption is independent of owner acceptance. No focus change, pointer capture, activation identity, keyboard event or fabricated source is produced. Freeze frame/index and ACCESSIBILITY metadata before invoking a mutable external application callback; never use an activation-snapshot helper for numeric input. Callbacks may update external owner/userdata safely under their family's borrowed state/lifetime rules. Core retains no callback or owner pointer here. Typed payloads are stored by original queued-event origin; actual touch-cancel insertions/reordering do not attach a value to the wrong dispatch index. Synthetic inputs have no typed value. Copies returned by claim survive frame/context lifetime. New frames clear payload presence; stale/omitted/disabled inputs never replay. ## Memory, ABI and verification scope No existing public struct grows; old enum values 0/1 remain. Private idle cost is one pointer plus snapshot-valid/current-frame-invalid bools and alignment (measure actual context delta, not a universal 8-byte claim). No numeric allocation is added to cui_create. With N=max_elements, exact opt-in allocation is `sizeof(private_numeric_state)+2*N*sizeof(uint32_t)`: current/previous masks plus two EVENT_MAX=256 bounded scalar/presence arrays and origin count. No per-event allocation or hidden registry. All storage frees with context. New clients require matching new symbols; old source/binaries retain their existing routes. Focused source/public/distribution tests cover owned payloads, original input order, actual touch-origin shifts, repeat/invalid claim, masks/role/readonly/modal/ omission/compaction, queue capacity/recovery, legacy Focus/Activate and actual scroll-layout failure/error-clear recovery. TU-local allocator instrumentation checks zero legacy/zero-mask allocations and atomic first-allocation failure, retention/free and exact sizeof evidence without production hooks. The observer source/distribution fixtures and numeric allocator fixture passed all three focused private-Xvfb tests with strict C11 warnings on the combined CoreV2 base. They include actual failed V2 buffer growth with queued Focus, Activate and key replay, first/fresh-frame authority, known current errors, clear-only rejection, modal/omission distinctions, V1 early and V2 late real scroll-layout failure, and matching/wrong-end lifecycle recovery. The observer adds no context fields or allocation. On the tested 64-bit Linux ABI the combined context is 255520 bytes versus 255504 without its existing numeric block (delta 16); private numeric fixed storage is 8200 bytes, each scalar slot 16, and opt-in N=32 allocation 8456 bytes. The allocator fixture measures that block relative to the surrounding V2 layout, not the whole prefix. Measurements are ABI-specific. See [numeric action design](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SLIDER_ACCESSIBILITY_ACTIONS.md) for independent native-mode/host SET_VALUE and future model/binding gates. Core helper tests do not establish Linux native numeric delivery or full Slider family completion. --- ## Date-only DatePicker actions Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DATE_PICKER_ACTIONS.md # Date-only DatePicker actions Include `cui/cui_date_picker_actions.h` and rebuild with matching sources and headers. This opt-in facade adds bounded presets and clear actions. Existing DatePicker APIs and layouts are unchanged. It is not date-time editing, an event observer, arbitrary styling or a complete DatePicker parity claim. The canonical library and generated distributions include both implementation files. The focused tests compile and execute the example below. This Base composition is compiled by the private fixture. Call it once inside a frame; state and value persist across frames. Use a real host viewport rather than a clock or platform date service in the widget. ```c #include "cui/cui_date_picker_actions.h" #include /* Small custom numeric Calendar control grid. It deliberately has no weekday * columns: each date/month/year is an explicitly labeled button. */ static void example_calendar_paint(cui_context *ui, cui_id root, size_t first) { size_t count; const cui_semantic *sem = cui_semantics(ui, &count); unsigned column = 0; cui_begin_box(ui, 0, (cui_box){.row = true}); for (size_t i = first; i < count; i++) { if (sem[i].role != CUI_ROLE_BUTTON) continue; if (column == 7) { cui_end_box(ui); cui_begin_box(ui, 0, (cui_box){.row = true}); column = 0; } char number[16]; cui_str label = sem[i].name; if (sem[i].value > 0) { snprintf(number, sizeof number, "%.0f", (double)sem[i].value); label = cui_string(number); } const char *navigation[] = {"<<", "<", ">", ">>", "Year"}; for (unsigned part = 1; part <= 5; part++) if (sem[i].id == cui_calendar_navigation_id(root, part)) label = cui_string(navigation[part - 1]); if (sem[i].id == cui_calendar_month_toggle_id(root)) label = cui_string("Month"); cui_begin_box(ui, sem[i].id, (cui_box){.width = 40, .height = 32, .clip = true, .border_width = cui_focused(ui) == sem[i].id ? 2 : 0, .border = {255, 255, 255, 255}, .background = sem[i].checked ? (cui_color){30, 100, 180, 255} : (cui_color){30, 30, 30, 255}}); cui_text(ui, label, 12, sem[i].disabled ? (cui_color){100, 100, 100, 255} : (cui_color){255, 255, 255, 255}); cui_end_box(ui); column++; } cui_end_box(ui); } void example_date_actions(cui_context *ui, cui_date_picker_actions_state *state, cui_date_picker_value *value, cui_rect viewport) { /* Initialize once before the first frame: * cui_date_picker_actions_init(state, 702, (cui_date){2024, 2, 1}); * *value = (cui_date_picker_value){.dates = {.start = {2024, 2, 15}}}; */ const cui_date_picker_preset preset = { .id = 704, .label = {"March", 5}, .value = {.dates = {.start = {2024, 3, 1}}}}; cui_date_picker_actions_options options = { .picker = {.viewport = viewport}, .calendar = {.presentation = {.month_toggle = true}}, .presets = &preset, .preset_count = 1, .clear_id = 703, .clear_label = {"Clear", 5}, .cleanable = true, .delete_policy = CUI_DATE_PICKER_DELETE_TRIGGER}; cui_date_picker_actions_result result = cui_base_date_picker_actions( ui, 701, 700, cui_string("Date"), state, value, options); if (!result.valid) return; cui_begin_box(ui, 701, (cui_box){.width = 180, .height = 32}); cui_text(ui, cui_string("Choose date"), 14, (cui_color){255, 255, 255, 255}); cui_end_box(ui); if (options.cleanable && cui_date_valid(value->dates.start)) { cui_begin_box(ui, 703, (cui_box){.width = 80, .height = 32}); cui_text(ui, options.clear_label, 14, (cui_color){255, 255, 255, 255}); cui_end_box(ui); } if (state->picker.overlay.open) { cui_rect panel = {viewport.x, viewport.y + 40, 300, 360}; cui_overlay_set_bounds(&state->picker.overlay, panel); if (cui_overlay_begin(ui, &state->picker.overlay)) { cui_begin_portal(ui, 702, (cui_box){.clip = true}, panel, 100); cui_calendar_options calendar = options.picker.calendar; calendar.range = state->calendar_value.shape == CUI_DATE_PICKER_RANGE; calendar.disabled = calendar.disabled || options.picker.disabled; /* Capture the semantic range, submit once, then custom-paint its * numeric buttons without reducing input again. */ size_t calendar_first; cui_semantics(ui, &calendar_first); cui_calendar_submit_ex(ui, 700, &state->picker.calendar, state->calendar_value.dates, calendar, options.calendar.presentation); example_calendar_paint(ui, 700, calendar_first); cui_date_picker_actions_submit_presets(ui, state, options); cui_begin_box(ui, 704, (cui_box){.width = 180, .height = 32}); cui_text(ui, preset.label, 14, (cui_color){255, 255, 255, 255}); cui_end_box(ui); cui_end_box(ui); cui_overlay_end(ui); } } } ``` `cui_calendar_submit_ex` submits semantics, not layout/paint. The example paints a simple numeric button grid including navigation and selectors; it is not a weekday-aligned Calendar design. Use the Styled facade for the standard Calendar layout or implement a custom Base layout for all submitted IDs. The preset helper submits semantics only, inside the caller's one popup scope; it does not begin/end a scope, paint, reduce input or invoke predicates/callbacks. Use the same valid options as the successful Base call and paint each submitted preset ID within the visible panel. Do not call it twice. It publishes copied submission identities only after every interaction submission succeeds. Its state argument is mutable solely for that bounded metadata. No borrowed pointer is retained. A helper failure cannot turn a partial list into next-frame eligibility. The new state deliberately keeps the outer picker value and child Calendar value separate. Initialize once with `cui_date_picker_actions_init`; NULL is a no-op. The first successful call synchronizes the supplied outer value once. Later external value changes are detected by comparing dates/shape with `observed_value`. A rejected child update is not retried on ordinary render, reopening or a matcher change alone. Do not edit internal observed/submission fields or manually toggle the overlay; use ordinary trigger/dismiss input. Calendar view/cursor remain caller-owned, like the existing picker. Reinitialization invalidates all identities. SOURCE presets accept the outer value first, including shape changes, then attempt child synchronization. Child eligibility uses CUI bounds and the pure disabled predicate; Calendar-only `disabled` does not reject assigned values. Rejection leaves child selection/month/view/range phase unchanged. Acceptance sets the child selection and range phase, and recenters month/year to the start without resetting view/year page/cursors. These are the frozen source's independent ownership and accepted-start recenter semantics, with explicit CUI min/max extension. Presets close and unconditionally request trigger focus. An accepted complete child day activation publishes the child's value/shape back to the outer value even if the child date did not change: upstream Calendar emits Selected for this case. Actual child edits also publish incomplete ranges under CUI's existing partial-range semantics; this is not a claim of upstream's completion-only subscription delivery. Navigation and rejected activation do not overwrite a diverged outer value. MATCH_SHAPE rejects mismatched preset shapes but otherwise keeps SOURCE child semantics. MATCH_SHAPE_ENABLED additionally atomically rejects a preset if either endpoint is disabled/out of bounds. No interior range scan occurs. Relative dates are resolved by the host. `picker.calendar.range` is ignored by this facade; the outer value and independent child each carry explicit shape. Clear empties both values, keeps outer shape, resets the child's range phase, closes without an explicit focus request, and preserves month/year/view/cursors. Empty candidates never call the date predicate. `cleanable` controls visibility; Delete is separately OFF (default), TRIGGER or SCOPE. Only unmodified nonrepeating Delete is handled; Backspace is not. SCOPE covers prior submitted enabled Calendar navigation/month/year headers, grids/day cells and preset buttons. Outer disabled gates every action; Calendar-only disabled gates day input. Preset buttons match the source's disabled Tab-stop policy; pointer, accessibility and explicit focus plus Enter activation remain available. The existing modal outside-dismiss policy still applies to trigger-row controls outside an open popup: dismiss first, then activate clear, or use scope Delete. This slice does not change Core hit routing to promise one-click outside-popup clear. There is no future text-entry child in this date-only slice. Preflight rejects all invalid options before mutation, event consumption or predicates. Limit8 presets and96 UTF-8 bytes per nonempty label; no embedded NUL, invalid scalar, zero/duplicate/conflicting IDs or invalid dates. Single end must be absent; range can be empty/start-only/ordered complete, never end-only. Presets are complete. Active clear support needs a distinct nonzero ID and label. Viewport must be finite/positive; width and cell size finite/nonnegative, with zero retaining the existing defaults and small positive cells using normalization. Bounds must be absent or valid and ordered. Unknown action enums fail; inherited Calendar extension normalization remains its existing contract. Styled also requires finite positive font size/nonnegative padding/gap/radius and enough viewport width/height for all preset rows; it does not submit clipped-off rows. Ordinary global caller ID collision discipline remains required, including custom Base layouts. Known Calendar ID conflicts are rejected before predicate calls. The array and preset values are borrowed for the call; label/locale strings and predicate/user resources remain valid through normal frame/render consumption. Do not mutate UI from predicates. State/value belong to the owner UI thread. Reinitialize before using the state with a different context; frame sequences are local to one context. No resources are allocated or retained by this API. It is not a stable binary layout extension to old records; rebuild new state users with matching headers. Queue order is the existing selector Escape prepass, overlay dismissal/trigger pass, one entire Calendar reduction, then one action pass in frame event order. Only the first eligible accepted action wins. Rejected presets do not consume. Calendar and action phases are not global chronological interleaving: a queued preset can run after a later queued day edit. Calendar auto-close in that one reduction does not erase original submitted action eligibility; prior overlay dismissal does erase it; trigger toggles and Escape invalidate popup action eligibility for the call. Prior records expire after an omitted frame, omitted/failed popup submission, or a close/reopen transition. They contain only copied IDs/grid/week-start/month-count/frame sequence and at most 144 target IDs for submitted enabled Calendar/preset targets, not a host/context pointer. Scope Delete additionally checks current view/grid and list membership; a reserved but absent/off-view year/day ID cannot qualify. The 144 bound includes at most 126 day occurrences, navigation and the 8 presets; the helper publishes no partial target set. A real previous semantic/input target is still required; retained IDs alone cannot fabricate an activation. Current preset ID and policy must also match. Same-frame root reuse and global ID collisions remain invalid. `valid` denotes preflight success; later Core capacity/layout errors are not transaction rollback. `calendar` is the single Calendar reduction result; `action_activated` is acceptance independently of a value edit; `changed` compares final outer dates/shape with the entry value. Clear on empty and identical presets can be accepted without `changed`. No typed observer wrapper or binding builder is added here. No live AT, browser or platform date-time behavior is implied. Scope Delete additionally requires current view/list eligibility. A submitted year then hidden by a day-view switch, or a day hidden by a month change, is rejected. Unsubmitted year/day IDs are not retained. Core may redirect programmatic focus on an unknown ID to a valid modal target before dispatch; Delete then applies to that actual target, not to the unknown requested ID. The popup root itself is not a Scope Delete target. ## Verified worker fixture The isolated fixture registers the new sources without changing canonical build metadata. Strict C11 (`-Wall -Wextra -Wpedantic -Werror`) and the C++ header compile pass. The guide code block is extracted, compiled and exercised by the test. ```sh cmake -S tests/fixtures/date_picker_actions -B build-actions -G Ninja cmake --build build-actions --target test_date_picker_actions date_picker_actions_header date_picker_actions_guide test_picker test_picker_base test_picker_events test_date_picker_calendar test_calendar_behavior test_calendar_presentation python scripts/test_local.py --build-dir build-actions -- -V -R '^(date_picker_actions|picker|picker_base_only|picker_events|date_picker_calendar|calendar_behavior|calendar_presentation)$' ``` Results: native 7/7; separate `-DCUI_SANITIZE=ON` build, ASan/UBSan 7/7. The action suite reports 1,738 assertions for Base and Styled, including source child-rejection/retention, complete no-op adoption, clear/preset focus, queue order, preflight failures, previous-submission expiry, off-view target rejection, reduce-once and legacy zero-option semantic/software-pixel equivalence. The private `tests/fixtures/date_picker_actions/test_wasi.py --build-dir BUILD` uses the existing repository pinned WASI driver: Zig 0.16.0, wasmtime 49.0.0, WASI Preview 1. It passed 1/1 suite and the same 1,738 assertions, with source fingerprint validation. No dependencies were installed. Native checks used the private-display wrapper; no browser, desktop, live AT or bindings were exercised. Canonical source/umbrella/amalgamation/binding/metadata registration, generated skill resources and full integration checks remain the integrator's work. --- ## DatePicker with Calendar options Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DATE_PICKER_CALENDAR.md # DatePicker with Calendar options Include `cui/cui_date_picker_calendar.h` and rebuild with matching headers/library. This additive value record forwards Calendar presentation and behavior through DatePicker; zero preserves the legacy DatePicker path without resizing existing public records. ```c #include "cui/cui_date_picker_calendar.h" bool reservation_date(cui_context *ui, const cui_theme *theme, cui_date_picker_state *state, cui_date_selection *selection, cui_rect viewport, cui_date host_today) { return cui_date_picker_ex(ui, 100, theme, cui_string("Reservation date"), state, selection, (cui_date_picker_options){.viewport = viewport, .calendar = {.range = true, .locale = cui_date_locale_builtin(CUI_DATE_LOCALE_IT)}}, (cui_date_picker_calendar_options){ .presentation = {.month_toggle = true, .today = host_today, .neighboring_days = true}, .behavior = {.range_transition = CUI_CALENDAR_RANGE_RESTART_EARLIER, .year_destination = CUI_CALENDAR_YEAR_OPEN_DAYS, .recenter = CUI_CALENDAR_RECENTER_SELECTION_START, .range_validation = CUI_CALENDAR_VALIDATE_RANGE_ENDPOINTS}}); } ``` Call `cui_date_picker_init(state, popup_id, initial_date)` once, then submit each active frame. The caller retains state and selection. Supply a finite positive viewport and a distinct popup ID. Locale/custom labels, first weekday, 1–3 months, cell size, range, bounds and disabled-date predicate already belong to `options.calendar`; they are not duplicated in the new record. Today is a host-supplied civil date, with no clock lookup; invalid/zero omits its paint. Month toggle is effective only for one month. See [Calendar presentation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CALENDAR_PRESENTATION.md) and [behavior policies](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CALENDAR_BEHAVIOR.md) for exact normalization, occurrence IDs, eligibility and paint precedence. DatePicker reduces Calendar exactly once, then closes after the entire queued Calendar input when an accepted single selection or completed range remains. An earlier endpoint restart remains open; a rejected completion remains open. A same-date single activation closes even when the bool is false because the final selection did not change. Queued targets use the original grid and panel identity even when an earlier activation recenters. Completion followed by another start in the same queue remains open. Opening, rendering or supplying policies does not reset Calendar state or synchronize range phase. The existing pass order remains Escape-from-month/year handling, overlay dismissal/trigger toggles, Calendar reduction, close, trigger and popup submission/paint. These are separate passes, not a globally chronological dispatcher. Two Escapes queued in a selector frame are handled by the existing selector prepass; they are not equivalent to Escape in two successive frames. Closing restores trigger focus; a newly opened Styled popup focuses the existing Calendar cursor or selector. Outer disabled closes the popup; Calendar-only disabled leaves the trigger operable while suppressing Calendar actions. Omitted components do not reduce input or manufacture close events. The Styled bool is the exact legacy result. In particular, an invalid viewport or late overlay-begin failure can return false after a selection edit; inspect caller state/selection when handling such errors. `cui_base_date_picker_ex` returns the full aggregate Calendar result but owns neither layout nor popup submission. A Base host calls it once, then positions/begins its overlay and calls `cui_calendar_submit_ex` with the same presentation record; do not reduce a second time. `cui_date_picker_calendar_id(trigger)` exposes Styled's unchanged Calendar ID for `cui_calendar_cell_resolve`; zero trigger or zero derived ID returns zero, and ordinary ID collision discipline still applies. Extension values are copied and not retained. Keep state/selection, locale strings, predicate and user resources alive under existing submission/frame/render-consumption lifetimes. Disabled predicates must be pure and must not mutate active UI or recursively submit. The existing typed CHANGE wrappers retain their legacy path, final-value comparison and callback timing; they do not accept these options. There is no new selection observer, open/close notification, cancellation cause, event-source attribution or binding-builder support in this slice. Full DatePicker time editing, presets, cleanable controls, arbitrary styling and browser extension parity remain separate work. The browser gallery uses this API with the separate month menu, selectable adjacent-month days and host-local today marker enabled. Its copyable example calls the same additive entry point. Headless desktop and touch checks in `tests/web/test_date_picker_presentation_gallery.py` cover month navigation without changing the selected value, adjacent-day selection and popup close, two-stage Escape and disabled triggers. The locale/year-grid suite separately covers localized 1980 leap-day selection. These checks do not establish the remaining editing, preset or styling capabilities. --- ## Single-date time picker Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DATE_TIME_PICKER.md # Single-date time picker This opt-in portable C11 API composes one civil date and time. It implements the Base/value/synchronization and Styled slices of `design/DATE_PICKER_DATETIME.md`. No timezone/range editor, arbitrary date parser/formatter, typed event wrapper or binding builder is included. Existing DatePicker/actions and TimeField calls keep their behavior. Include `cui/cui_date_time_picker.h`; link `src/base/cui_date_time_picker.c` along with the normal picker/actions/Calendar sources. Canonical builds register the Base and Styled sources, standalone optional `CUI_DATE_TIME_PICKER_IMPLEMENTATION` and `CUI_IMPLEMENTATION_ALL` distribution paths. Native source SDKs carry the API; language builders do not expose it. ## Ownership and frame order Retain `cui_date_time_picker_state` and `cui_date_time_value` for one UI context, on its owner thread. Initialize with a stable popup ID and initial valid month. NULL init is a no-op; all-zero/uninitialized state cannot reduce or assign. `cui_date_time_value.date` is a valid Gregorian date or all-zero absence; partial invalid dates reject preflight. `time` must always be valid 00–23:00–59:00–59, even with no date. It exposes retained time that upstream's empty DateTime hides; check date presence before using it as a committed date-time. Call `cui_base_date_time_picker` once per frame, passing stable distinct trigger, Calendar and TimeField IDs plus state/value/options. It reduces once, submits trigger/optional clear semantics, and returns result flags. Caller owns all paint and the popup. Do not call public `cui_time_field` or `cui_base_time_field` again: those functions both reduce and submit. For an open popup, the exact order is: 1. Set bounds and begin the existing `state.actions.picker.overlay` once; begin the caller's portal/layout inside that scope. 2. `cui_calendar_submit_ex` using `state.actions.picker.calendar` and retained `state.actions.calendar_value.dates`, with the same Calendar options/extensions. Combine outer disabled into Calendar disabled. This submits without reducing. 3. `cui_date_time_picker_submit_time(ui,time_id,&state,&value,options)`. 4. `cui_date_time_picker_submit_presets(ui,&state,options)` even if preset_count=0. 5. Paint/layout these submitted IDs; end the portal and overlay scope once. Both helpers are semantics-only and require this frame's successful Base call, the same valid options/value and the caller's real open popup scope. Time submission must precede preset submission: the latter publishes bounded actual Calendar, preset and TimeField target identities for the next frame. Time segments require both successful helper stamps from the immediately preceding frame; omission, failed/duplicate helper, omitted frame or close/reopen expires admission. Helpers never replay input/state edits/callbacks. Core capacity errors after submissions are not rolled back; failed helper stamps publish no partial identity set. `cui_date_time_picker_time_id(trigger)` supplies a stable optional derived time root; Base also accepts a caller-supplied time ID. Segment IDs are the existing `cui_time_segment_id(time_id,0..3)`. All four are reserved during preflight, including currently hidden second/AM-PM segments. Caller global ID discipline is still required. Existing modal outside-clear restrictions apply: dismiss the popup before using the separate clear button outside it. ## Values, synchronization and drafts MINUTE truncates seconds to zero; SECOND retains them. Twelve-hour appearance never changes civil storage. No timezone, UTC offset, DST, leap-second or implicit clock service exists. First valid reduction uses supplied time for a present date, and configured default time for an absent date. Options are validated atomically before predicates, normalization, input or state changes. Repeated unchanged controlled values preserve draft digit count/segment, Calendar view and rejected-child divergence. A changed external value is setter intent: reset draft, truncate supplied time (empty assignment uses default), sync child if eligible, close directly and emit no source Change. Between frames, `cui_date_time_picker_assign(&state,&value,next)` queues identical setter intent as well: it validates next atomically and sets a pending flag, consumed only by a valid Base call. Invalid options leave pending assignment intact. It does not require a UI context or touch focus/semantics between frames. Default-time changes reset current time; precision changes truncate it; hour-cycle changes reset draft while preserving civil time. Changes apply once before input; external setter intent wins over simultaneous default changes. Ordinary close, reopen and idle frames do not push a time value into a pending draft. Disabled popup omission retains draft but rejects user input; Calendar-only disabled gates day edits and does not disable the time field, presets or clear. ## Source behavior and results Frozen authority is `87d10ae5e1299d1be18670a37570c5402f952e34`, `crates/component/src/time/date_picker.rs:215–227,261–291,327–447,484–538`. - Different accepted day adopts child into outer date, preserves time and stays open. Same accepted day closes and confirms without a source Change. Comparison uses outer date: an unchanged retained child can still replace a divergent outer. - Actual TimeField change stays open, preserving date. A present date reports source Change; an absent date only changes retained time storage. - Date-only preset preserves current time. Timed preset replaces/truncates it and resets draft. Both close, emit source Change even if identical and explicitly focus trigger. SOURCE may accept outer date despite child matcher/bounds rejection; MATCH_SHAPE_ENABLED pre-rejects ineligible assignments. Shape matching alone is vacuous for this single-only facade. Changing matcher or reopening does not silently resynchronize rejected child; an actual later day edit does. - Clear/Delete restores default time, clears outer/child date and draft, preserves Calendar view/month, closes without an explicit focus request, and reports source Change even if already empty. `cleanable` controls visibility independently of Delete OFF/TRIGGER/SCOPE. Outer disabled gates every user action. `valid` is preflight success, not rollback of later Core/layout failures. `value_changed` compares final date AND time against entry storage, including normalization/external-empty/default changes. `source_change` coalesces accepted source Change causes; it is not a callback stream or Change count. Repeated preset or clear can report source_change=true with value_changed=false. A time edit then preset can restore the entry value with source_change=true. An empty-date time edit has value_changed=true but source_change=false. `time_edited` means the TimeField actually changed storage; `action_activated` means accepted clear/preset; `confirmed` means same-day confirmation. `calendar` is the one reduction result. Phase order: configuration/external sync; Escape/overlay/trigger pass; Calendar; TimeField if still open and admitted; first eligible action in queued order. There is no global chronological interleaving of Calendar/time/action events. Escape/trigger transitions invalidate old popup action/time admission. Scope Delete accepts only actual previous submitted enabled targets still eligible in the current view/list/precision. Popup root or generated namespace IDs alone do not qualify. Core may redirect invalid programmatic focus before key dispatch; the resolved real target is authoritative. ## Validation and lifetimes Preflight bounds: at most 8 presets, 96-byte nonempty scalar UTF-8 action labels; empty time_label falls back to Time. Reject malformed active time, date, precision, policy, dimensions/viewport, min/max, range=true, duplicate/reserved IDs, invalid active UTF-8 or NULL preset storage before mutation/predicates/input. Ignored has_time=false preset time is not inspected. Bounds/predicate checks on assignment are inherited CUI extensions; predicates are pure, owner-thread only. Arrays/options are borrowed for calls. Strings, locale tables and predicate/user resources remain valid through frame/render consumption. State stores copied values/IDs only and allocates nothing. Reinitialize before moving to a different context; do not edit bookkeeping, manually force reopen or reuse state roots in the same frame. Legacy public record layouts stay unchanged; new record users must rebuild with matching headers. Private fixture: `cmake -S tests/fixtures/date_time_picker -B BUILD -G Ninja`, then build `test_date_time_picker test_date_time_picker_styled test_picker test_date_picker_actions date_time_picker_header date_time_picker_guide date_time_picker_guide_cpp`. Run through `python scripts/test_local.py --build-dir BUILD -- -V -R '^(date_time_picker|date_time_picker_styled|picker|date_picker_actions)$'`. Repeat in a separate `-DCUI_SANITIZE=ON` build. `tests/fixtures/date_time_picker/test_wasi.py --build-dir BUILD` uses the repository's existing pinned offline WASI driver. The Base/Styled checks alone add no live-AT or full source-parity evidence. Final worker results will be reported with the signed checkpoint. Configure a separate fixture with `-DCUI_DATETIME_BUILD_STYLED=OFF` to build/run the Base test without the optional Styled source. Accepted Calendar selections are evaluated in queue order against the immediately preceding outer date. A→B→A remains open with source_change true and value_changed false. A→B→B confirms B; A→A→B confirms A and skips later Calendar events. The private synchronous visitor uses constant stack storage; close occurs once after Calendar reduction. Legacy Calendar entry points have no visitor and preserve their existing queue behavior. This stop-first-confirmation rule describes CUI routing, not upstream scheduler equivalence. TimeField source_change uses the existing reducer's net phase result: Up then Down restoring the entry time does not report a time source change. There is no ordered callback stream or per-intermediate-time-edit notification claim. ## Styled composition `cui_date_time_picker` calls Base once and owns the single popup scope, Calendar, paint-only TimeField, and preset/clear paint. Use this instead of manually calling Base/helpers in that frame. Calendar root is `cui_date_picker_calendar_id(trigger)`; time root is `cui_date_time_picker_time_id(trigger)`. No extra resources are retained. The trigger displays a bounded locale date plus 12/24-hour minute/second time; there is no chrono pattern API. This display is separate from its accessible name supplied by the caller. `time_label` labels both the visible row and group. Styled validates theme metrics and rejects a popup larger than the supplied viewport before reducing input or mutating value/state. It does not silently clip away time/actions or add scrolling. Supply enough room, fewer months/presets, or smaller Calendar cells. DatePicker has no `design_size` field: actual supported metrics are Calendar cell_size (20–128, default32), 1–3 months, and finite theme font/padding/gap/radius; XS–9XL enums from other components are not accepted here. A bounded formatter can truncate very long localized date labels; custom source format patterns remain unsupported. Native/browser text shaping follows the existing host; software geometry tests omit glyph rasterization without a font. The following complete C11/C++11-compatible example is compiled by the standalone fixture. The application calls init once, retains both objects, and calls frame inside its own begun CUI frame. It links the Base source plus optional `src/components/cui_date_time_picker.c` and ordinary components/Calendar sources. ```c #include "cui/cui_date_time_picker.h" #include void example_datetime_init(cui_date_time_picker_state *state, cui_date_time_value *value) { cui_date initial; initial.year = 2024; initial.month = 2; initial.day = 15; memset(value, 0, sizeof *value); value->date = initial; value->time.hour = 9; value->time.minute = 30; cui_date_time_picker_init(state, 702, initial); } cui_date_time_picker_result example_datetime_frame(cui_context *ui, const cui_theme *theme, cui_date_time_picker_state *state, cui_date_time_value *value, cui_rect viewport) { cui_date_time_picker_options options; cui_date_time_preset preset; memset(&options, 0, sizeof options); memset(&preset, 0, sizeof preset); preset.id = 704; preset.label = cui_string("Tomorrow"); preset.date.year = 2024; preset.date.month = 2; preset.date.day = 16; options.picker.viewport = viewport; options.precision = CUI_DATE_TIME_SECOND; options.default_time.hour = 8; options.presets = &preset; options.preset_count = 1; options.cleanable = true; options.clear_id = 703; options.clear_label = cui_string("Clear"); options.delete_policy = CUI_DATE_PICKER_DELETE_SCOPE; return cui_date_time_picker(ui, 701, theme, cui_string("Appointment"), state, value, options); } ``` The local preset array is borrowed only during submission; its literal label remains readable for rendering. Application-owned dynamic strings must follow the frame lifetime rules above. Bindings remain separate; the gallery mode below uses the C API directly. Styled slice validation: focused native and ASan/UBSan wrapper checks each pass 4/4 suites; pinned WASI passes Base579 and Styled695 assertions. Base-only configuration passes its 579 assertions without the optional Styled source. Software tests cover 1–3 months, minute/second and 12/24-hour segments, actual popup containment, supported cell metrics/theme variants, eight presets, narrow rejection, draft/Tab/preset/clear behavior, and legacy TimeField memberwise semantics/nontext pixel equivalence. Existing date-only actions tests retain legacy zero-option picker equivalence. Guide/header compile as C11/C++11. These are headless software/semantic checks, not browser, live-AT or GPU proof. Canonical integration additionally compiles and executes the exact guide example in the native and WASI Styled suite (701 assertions including that example). Standalone optional-module and CUI_ALL fixtures create a real popup, edit its TimeField, and confirm the selected date. The packaged Python source tree omits docs, configures and builds both native DateTime tests, and runs them through the private-display wrapper. Consumer SDK/distribution headers are generated; language builder/bridge omissions remain explicit above. This stays within the existing DatePicker family; it does not add a 79th manifest entry or claim complete parity. For standalone header implementation, emit the ordinary Core, Base, Theme and Components implementation macros once, then `CUI_DATE_TIME_PICKER_IMPLEMENTATION` and include `cui_date_time_picker.h`. The exact independent recipe is compiled and executed in `tests/distribution/date_time_picker.c`; its CUI_ALL mode uses `CUI_IMPLEMENTATION_ALL` instead. Declarations alone do not enable implementation. ## Browser gallery mode The DatePicker story defaults to its existing date-only presentation. Enable **Date + time** for the single civil date/time facade; only then do Include seconds, 12-hour clock and optional clear/Delete controls appear. Configure those controls while the popup is closed. Date-only actions are hidden during time mode and restored when it is turned off. The current date transfers between modes; entering time mode retains its last time, while clear restores 09:30 and precision reduction permanently drops seconds. Time mode is single-date and discards a range end; the gallery does not offer a date-time range control. Launch day preserves time; Timed review replaces date/time (and truncates seconds at minute precision). A changed day leaves the popup open for time editing; selecting that same day confirms. Clear/Delete empties the date and resets time. The visible date/time label follows the selected date locale and time appearance; Time/segment names and preset labels are explicit English sample strings. The copied complete C11 snippet reflects precision, period, clear/Delete and locale. No timezone conversion or localization service is involved. `tests/web/test_date_time_picker_gallery.py` uses actual headless Chromium mouse/ keyboard and CDP touch input to exercise numeric drafts across idle frames, seconds/AM-PM, changed/same-day confirmation, timed/date-only presets, clear and scope Delete from a time segment, disabled state, EN_US/FR and mode transfers. It copies and strictly compiles the displayed snippets. Existing date-only presentation/actions desktop/touch tests remain passing. This is sample/browser host evidence, not Safari/mobile-OS keyboard/live-AT or full event-stream parity. --- ## Native density integration Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DENSITY_INTEGRATION.md # Native density integration The integration merges origin/main `30ec050b` into package integration `81a7fe89`. SDL keeps logical layout/input coordinates while painting at renderer density. The additive scaled text APIs leave shaped geometry and caret coordinates logical. The merge preserves the existing per-face glyph raster cache, elapsed frame timing, idle event waits, and bounded rounded-shape rectangle submissions. Cache keys use physical character size (`logical size * paint scale`); using logical size alone would incorrectly reuse rasters after density changes. Rounded strips use device row height while retaining batches of at most 128 strips. Core, browser/WASI sources and SDK copies are unchanged from `81a7fe89`. SDK copies must be refreshed by the integrator. Native tests use `scripts/test_local.py` and its private Xvfb display. Hardware display migration and GPU density checks are not established by virtual-display coverage. Validation on Linux: strict default native build passed. Eight targeted native CTest entries passed through the invisible-display wrapper: raster cache, density, shaping, native text geometry, SDL appearance, password bridge, SDL services and rounded batching. A separate `CUI_BUILD_BIDI=OFF` strict build passed both density and raster-cache CTest entries. The density runs explicitly selected `/usr/share/fonts/noto/NotoSans-Regular.ttf` through `CUI_TEST_FONT`; no selected test was skipped. Density coverage exercises 1x, 1.5x, 2x, then revisits cached sizes while checking stable logical metrics/carets and device-pixel coverage. --- ## Description List Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DESCRIPTION_LIST.md # Description List `cui_description_list` composes borrowed label/value strings or custom callbacks into horizontal or vertical rows. Items have stable nonzero IDs; duplicate IDs and invalid dimensions reject the call before it submits layout or semantics. There is no persistent allocation or interaction state. The frozen upstream kit 0.7.1 `description_list.rs` supplies the defaults: three columns, horizontal bordered cells, a 120px label, medium 8px/4px padding, 14px labels at the default 16px text size, and full-width 8px separators. Small and extra-small use 4px/2px padding; large uses 12px/6px. Unbordered lists remove cell padding and use size-dependent spacing between rows. Label backgrounds and foregrounds are independent theme tokens. The headless row iterator groups spans into 1–10 columns. Zero columns select three; zero spans normalize to one. Separators occupy isolated rows. Oversized spans retain proportional shrink, without the upstream empty leading row edge case. In an incomplete row, CSS flex free space is shared equally: spans 1 and 2 in four columns receive 37.5% and 62.5%, respectively. Percentage box sizing resolves these widths in the same frame, including after a parent resize. Set `custom_label_width` to use `label_width` (including zero), and additionally `label_width_percent` to interpret it as a fraction of the cell. Vertical mode ignores label width. Callbacks receive a theme copy with the appropriate text size and color; they own their semantics. Plain content exposes passive labels inside a group and adds no Tab stops. `tests/unit/test_description.c` covers grouping, oversized spans, separators, first-frame and resized fractions, all four themes/sizes/layouts/border modes, custom content, wrapped row height, percentage labels, and invalid IDs. Remaining parity limits: CUI currently clips the outer list to a rectangle; rounded clip masks and independent per-cell paint clipping are not implemented. Custom overflowing children can cross a cell boundary before reaching the outer clip. Rich Text values use host callbacks until the complete Text component is available. The source's inherited font weight and application-level typography are not yet represented by this API. No browser/native visual parity claim is made from these headless tests. --- ## Dialog composition V1 — focused C implementation Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DIALOG_COMPOSITION.md # Dialog composition V1 — focused C implementation This guide describes the additive C implementation originating in source checkpoint `138c3a39`, with the focused native proof and cache correction in `db888055`. Strict C11 builds, native and WASM32 record checks, first-frame geometry/current-font software tests, owner actions and the complete example have been exercised locally. Configured distribution, canonical generated freshness, gallery/browser and wider compatibility checks are tracked separately; see the validation receipts before claiming a backend or full parity. This work is unreleased; Root/host and all five foreign composition facades remain unfinished. Use headers, sources, SDK and generated resources from one matching revision. ## API and ownership The authoritative declarations are [`cui_dialog_composition.h`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_dialog_composition.h) and [`cui_dialog_composition_styled.h`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_dialog_composition_styled.h). The latter adds the Styled action helper and includes standard component types. | Operation | Base | Styled | | --- | --- | --- | | Initialize caller storage | `cui_dialog_layout_init_v1` | Same | | Open/reset a closed owner | `cui_dialog_open_v1` | Same | | Resolve default sizing | `cui_dialog_sizing_default_v1` | Same | | Submit complete tree | `cui_base_dialog_compose_v1` | `cui_dialog_compose_v1` | | Submit owner action | `cui_base_dialog_action_v1` | `cui_dialog_action_v1` | | Inspect resolved slot style | `cui_dialog_slot_style_v1_get` | Same | | Balanced child wrapper | `cui_dialog_slot_begin_v1` / `cui_dialog_slot_end_v1` | Same | Retain one `cui_surface_state` and one `cui_dialog_layout_v1` for each Dialog or AlertDialog. Initialize the surface with `CUI_SURFACE_DIALOG` or `CUI_SURFACE_ALERT`, then initialize its layout. Use `cui_dialog_open_v1` for every closed-to-open transition, including close/reopen between frames. Already-open calls do not reset scroll. Existing `cui_surface_open` behavior is unchanged; it does not perform the new layout reset protocol. Call compose between `cui_begin_frame` and `cui_end_frame`. Compose owns all structural begin/end calls, focus scope and callbacks. There is no new manual top-level begin/end route. Submit a layout at most once per ordinary frame; do not recursively compose the same layout. Distinct nested owners are allowed. The surface, layout and their borrowed offset/bounds storage must remain alive through `cui_end_frame`. Do not edit private bookkeeping fields. The layout binds to its context; reinitialize only while unmounted before rebinding. Descriptor, slot-user and refinement pointers are read during compose. Emitted strings, images and other resources retain their ordinary Core frame/draw lifetimes. A callback token is valid only inside its active callback; never store it. ## Six independent slots Callbacks run once in enum order, while the owner remains open. Core may measure text repeatedly; it does not replay application composition. | Slot | Default when no `present` or `omit` bit | Layout role | | --- | --- | --- | | `CUI_DIALOG_HEADER` | Absent | Intrinsic region, independent of Title | | `CUI_DIALOG_TITLE` | Wrapped `name` when nonempty | Intrinsic label region | | `CUI_DIALOG_DESCRIPTION` | Wrapped `description` when nonempty | Intrinsic region | | `CUI_DIALOG_CONTENT` | Absent | FLEX1 with intrinsic minimum | | `CUI_DIALOG_BODY` | Absent | FLEX1 with zero minimum; scrolling children | | `CUI_DIALOG_FOOTER` | Absent | Separate intrinsic row outside Inner clip | Set a slot's `present` bit to invoke its callback. `present` plus a NULL callback means authored empty, including an empty Content/Body allocation. `omit` suppresses the slot and string fallback; masks cannot overlap or contain unknown bits. An omitted Body has no Body callback, scroll semantics or scrollbar. Header never suppresses Title or Description. To compose Description inside a custom Header, set the independent Description's `omit` bit and use a balanced manual child wrapper inside Header. Manual wrappers cannot span callbacks. `name` and `description` supply explicit accessibility text. Arbitrary visual callback children do not replace those strings. The draft links the owner to its Title label only when the Title wrapper is admitted. Caller-created child IDs must be distinct from structural IDs; use stable IDs from the owning context. ## Sizing, styling and placement Recompute `cui_dialog_sizing_default_v1` from the current viewport each frame, then apply explicit overrides. In this route `sizing` alone owns Panel width and height; `cui_surface_options.width/height` are inactive. Defaults are width420, AUTO intrinsic height, minimum96, viewport-bounded finite maximum, and `CUI_DIALOG_SOURCE_TOP`. The source96 minimum wins over a smaller usable maximum; the default resolver normalizes the effective maximum accordingly. Nonpositive usable width or height is rejected; do not silently skip failed submission. `CUI_DIALOG_CENTERED` selects current-size centering. Source-top defaults to viewport-height/10 and can take explicit preferred-top/layer-offset fields. The submitted current tree determines placement; previous completed bounds are not used to paint or allocate current geometry. Content and Body have separate `cui_scroll_region_sizing_v1` policies: FLEX1, FIT or FIXED, explicit minimum policy and finite bounds. Preserve their distinct default minima. Content can exceed its Inner allocation and be clipped while Footer retains its independent position. An oversized Footer can overflow the bounded Panel; this source policy does not convert Outer into a scroll owner. Body alone scrolls. The two FLEX1 peers use equal zero-basis allocation after minimum freezing. AUTO sizes the Panel from their combined intrinsic demand; it does not promise each peer receives its own natural height. For example, a short status Content can grow while a taller Body scrolls. This is the reviewed source policy, not stale first-frame geometry. For a status region that should stay intrinsic, explicitly set `sizing.content_sizing.mode = CUI_SCROLL_REGION_FIT` after resolving defaults, leaving Body FLEX1. The gallery Dialog uses this application policy: status may wrap at narrow widths, short Body fits, and long Body still scrolls. Do not change the global FLEX1 default to obtain that choice. This is a bounded Y constraint route, not a general layout solver: widths must remain independent of allocated Y. See [`SCROLL_LAYOUT.md`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SCROLL_LAYOUT.md) for admission and failed-frame behavior. Use `cui_dialog_refinement_v1` to override masked Panel background, border, radius, padding, gap and border width, or each slot's foreground, font size, padding, gap and alignment. Zero reserved fields; initialize `struct_size` and `version` with `sizeof` and `CUI_DIALOG_COMPOSITION_VERSION_1`. Unknown fields and invalid active floats fail validation. Base starts with neutral styles; Styled resolves theme values before explicit refinements. Supply the same theme to Styled compose and Styled actions. Core layout record V2 is unrelated to draw ABI2/background negotiation. This route uses ordinary V1 drawing and real track/thumb nodes; it does not require another renderer ABI. Its draft scrollbar/input behavior still needs runtime validation. Hidden bars do not imply disabling wheel scrolling. ## Actions, timing and failure Base action requires a caller-submitted box with the same ID. Styled action submits the standard button. Return values report the underlying interaction or button activation; **an activation can be vetoed** and need not mean the owner closed. Standard Styled button callbacks run before the owner action reducer. CONFIRM/CANCEL/CLOSE map to ACCEPTED/CANCELLED/CLOSED. The existing synchronous `decide` callback may veto; accepted close restores focus and calls `on_close` through existing surface behavior. No queued veto or global Enter mapping is introduced. `cui_surface_request_close` remains deferred to the next ordinary update; it is not an immediate between-frame close callback. Slot/action/decide/on_close callbacks may close the owner through supported helpers. Stop emitting application children after that close. They must not free or reinitialize the active layout/surface/context, or invalidate borrowed strings or offset storage. Remove owned storage only after `cui_end_frame`. Earlier callback effects are not rolled back when a later callback closes or fails. The new route uses `surface.body_viewport`, `body_content` and `body_maximum` only as admitted previous-input caches, refreshed before ordinary input reduction and cleared when not admitted. Current completed ranges come from the Body semantic after successful end_frame; current rectangles come from `layout.completed`. These state cache fields are not a current-paint oracle. Input uses the previous valid completed snapshot. The draft admits previous Body geometry only for an adjacent successful submission in the same open lifetime. It does not add an input-lifetime reset operation: **held pointer, touch or Space capture can retain existing Core behavior across close/reopen**. No cancellation marker, dispatcher rewrite or guarantee of suppressing every old held child press is included. Root/native-host ownership, all five foreign facade builders and stronger lifecycle closure remain separate unfinished work. Inspect both `cui_dialog_submit_result` and the error after `cui_end_frame`. `valid=false` rejects a descriptor or reports a later submission failure; `submitted=false` can also mean the owner is closed. An early valid result does not guarantee the later Core constraint calculation succeeds. An errored opt-in frame has no valid current geometry/draw promise; do not present its draw list. Clear/correct errors according to Core recovery, then submit a new frame. Never retry compose in the same ordinary frame or assume callbacks were rolled back. `layout.completed[10]` is meaningful only after successful end_frame while the owner remains open: Panel, Header, Title, Description, Content, BodyViewport, BodyContent, Footer, Outer, Column. These are borrowed tracking destinations, not an input cache to be copied back into current paint geometry. Present-part rectangles remain retained across ordinary submissions so unchanged tracked bounds do not request another frame. Omitted parts clear their rectangles; a new open lifetime resets all retained rectangles. A successful stable Dialog can quiesce after input and bounded animations settle. Auto-hide fading may request frames while active; focused scrollbar visibility does not itself require an endless redraw loop. Failed opt-in frames still provide no valid current geometry. ## Complete source example This small native headless program composes its first open frame, renders to a software buffer, then tears down after end_frame. The extracted example passed a strict C11 build and a private-Xvfb headless Inter Regular/Bold run. A host application calls the frame code repeatedly and queues its real input before begin_frame. Pass actual regular and semibold font paths; the program does not download fonts or open a window. The example uses Header, Title and Description independently, Content, Body and Footer. Static text outlives the frame. ```c #include "cui/cui_dialog_composition_styled.h" #include "cui/cui_software.h" #include "cui/cui_text.h" #include typedef struct { cui_surface_state surface; cui_dialog_layout_v1 layout; cui_theme theme; unsigned confirmations; bool closed; } demo; static bool decide(void *user, cui_surface_result result) { demo *d = user; if (result == CUI_SURFACE_ACCEPTED) ++d->confirmations; return true; /* Return false here to veto synchronously. */ } static void on_close(void *user, cui_surface_result result) { (void)result; ((demo *)user)->closed = true; /* No storage removal here. */ } static void header(cui_context *ui, const cui_dialog_frame *frame, void *user) { (void)frame; demo *d = user; cui_label(ui, &d->theme, cui_string("Workspace settings")); } static void content(cui_context *ui, const cui_dialog_frame *frame, void *user) { (void)frame; demo *d = user; cui_label(ui, &d->theme, cui_string("Changes apply to this workspace.")); } static void body(cui_context *ui, const cui_dialog_frame *frame, void *user) { (void)user; cui_dialog_slot_style_v1 style; if (!cui_dialog_slot_style_v1_get(frame, CUI_DIALOG_BODY, &style)) return; (void)cui_text_paragraph_colored( ui, cui_string("This body wraps at the current width. Longer content " "scrolls without placing the independent Footer inside it."), style.font_size, style.foreground, style.font_size * 1.25f, (cui_text_style){0}, true, NULL, 0); } static void footer(cui_context *ui, const cui_dialog_frame *frame, void *user) { demo *d = user; (void)cui_dialog_action_v1( ui, frame, &d->theme, cui_id_from(ui, "demo-cancel"), cui_string("Cancel"), CUI_DIALOG_CANCEL, (cui_button_options){0}); if (!d->surface.overlay.open) return; (void)cui_dialog_action_v1( ui, frame, &d->theme, cui_id_from(ui, "demo-confirm"), cui_string("Save"), CUI_DIALOG_CONFIRM, (cui_button_options){0}); } int main(int argc, char **argv) { if (argc != 3) { fprintf(stderr, "usage: %s regular-font semibold-font\n", argv[0]); return 2; } int status = 1; cui_font *font = cui_font_open(argv[1]); if (!font) return 1; if (!cui_font_register_style( font, (cui_text_style){.weight = CUI_TEXT_WEIGHT_SEMIBOLD}, argv[2])) { cui_font_close(font); return 1; } cui_context *ui = cui_create((cui_config){ .width = 640, .height = 480, .measure = cui_font_measure, .measure_styled = cui_font_measure_styled, .measure_user = font, .font_metrics = cui_font_get_metrics, .text_geometry = cui_font_text_geometry, .text_geometry_line = cui_font_text_geometry_line, .text_capabilities = cui_font_text_capabilities()}); cui_software *renderer = ui ? cui_software_create(640, 480, font) : NULL; if (!ui || !renderer) goto cleanup; demo d = {.theme = cui_theme_light()}; cui_surface_init(&d.surface, cui_id_from(ui, "demo-dialog"), CUI_SURFACE_DIALOG); if (!cui_dialog_layout_init_v1(&d.layout, &d.surface) || !cui_dialog_open_v1(ui, &d.layout, 0)) goto cleanup; cui_surface_options options = { .viewport = {0, 0, 640, 480}, .margin = 16, .decide = decide, .decision_user = &d, .on_close = on_close, .close_user = &d}; cui_dialog_sizing_v1 sizing; if (!cui_dialog_sizing_default_v1(options, &sizing)) goto cleanup; cui_dialog_composition_v1 composition = { .struct_size = sizeof composition, .version = CUI_DIALOG_COMPOSITION_VERSION_1, .present = (1u << CUI_DIALOG_HEADER) | (1u << CUI_DIALOG_CONTENT) | (1u << CUI_DIALOG_BODY) | (1u << CUI_DIALOG_FOOTER), .name = {"Notification preferences", 24}, .description = {"Choose how to stay informed.", 28}, .slots = { [CUI_DIALOG_HEADER] = {header, &d}, [CUI_DIALOG_CONTENT] = {content, &d}, [CUI_DIALOG_BODY] = {body, &d}, [CUI_DIALOG_FOOTER] = {footer, &d}}}; if (!cui_begin_frame(ui, 640, 480, 0.016f)) goto cleanup; cui_dialog_submit_result result = cui_dialog_compose_v1(ui, &d.theme, &d.layout, options, &sizing, &composition); cui_draw_list draw = cui_end_frame(ui); /* d and all borrowed data still live */ if (result.valid && result.submitted && cui_last_error(ui) == CUI_OK && cui_software_render(renderer, &draw, (cui_color){240, 240, 240, 255})) status = 0; cleanup: cui_software_destroy(renderer); cui_destroy(ui); cui_font_close(font); return status; } ``` For AlertDialog, initialize with `CUI_SURFACE_ALERT`, provide the desired Header and Footer callbacks, and omit Body when there are no children. This route does not introduce an automatic AlertDialog composition adapter. Existing `cui_alert_dialog`, `cui_surface_begin`/footer/end and their measured-height or fixed-height behavior stay unchanged. The intended source CMake consumer links `cui`, `cui_text` and `cui_software` from the same checkout (native text requires the repository's pinned/configured FreeType/HarfBuzz prerequisites). For example, after saving the program as `dialog_demo.c`, use a separate consumer CMake project with: ```cmake cmake_minimum_required(VERSION 3.20) project(dialog_demo C) set(CMAKE_C_STANDARD 11) set(CMAKE_C_STANDARD_REQUIRED ON) set(CMAKE_C_EXTENSIONS OFF) set(CUI_BUILD_NATIVE ON CACHE BOOL "" FORCE) add_subdirectory("/absolute/path/to/matching/cui" cui) if(NOT TARGET cui_text) message(FATAL_ERROR "Configure CUI native shaped-text prerequisites first") endif() add_executable(dialog_demo dialog_demo.c) target_link_libraries(dialog_demo PRIVATE cui cui_text cui_software) ``` The extracted C example has run with real Inter fonts. The standalone consumer CMake recipe and generated-header/SDK alternatives require their own validation. Do not combine this draft's header with an older installed library. The source metadata/guide registration to keep synchronized before release is: Dialog and AlertDialog entries in `docs/component-usage.json` and their matching human Usage paragraphs; supplemental header authority and Base/Styled limitations; consumer skill guidance; canonical SDK, amalgamation and skill generation; and meaningful configured source/distribution/offline-resource checks. Keep all78 manifest entries. See the exact pending-gate receipt in [`dialog-six-slot-source-checkpoint.json`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/validation/dialog-six-slot-source-checkpoint.json). --- ## Disclosure controls Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DISCLOSURE.md # Disclosure controls `cui_disclosure.h` provides unstyled trigger behavior and styled Accordion and Collapsible containers. The caller owns expanded booleans. No control allocates persistent state. Trigger IDs must remain unique and stable across frames. ```c cui_disclosure_item sections[] = { {11, cui_string("Account"), false}, {12, cui_string("Advanced"), false}, }; bool open[] = {true, false}; /* keep in application state */ cui_accordion(ui, 10, &theme, sections, 2, open, (cui_accordion_options){.collapsible = true, .bordered = true}, draw_section, application); ``` `draw_section(cui_context *, size_t index, void *)` runs synchronously only for expanded panels. It can submit any CUI children, including nested accordions. Children of collapsed panels are omitted from rendering and focus order. Collapsible uses the same callback shape with index zero. Accordion supports single or multiple expanded sections, optional collapse of the last expanded section, group and individual disabled states, and optional borders. Click, Enter and released Space activate a trigger. Up/Down wrap among enabled triggers; Home/End jump to the first/last enabled trigger. Arrow traversal moves focus without opening panels. The return value reports controlled state changes. Applications can also change the booleans themselves between frames. The base functions submit trigger semantics without painting. Custom designs can call them and then submit boxes with matching trigger IDs. The styled functions use theme colors, padding, gap, radius and control height; themes provide density and high contrast without duplicating behavior. Trigger semantics expose expanded state and the controlled panel ID. Mounted panels expose their trigger relationship; an Accordion group supplies a semantic parent. Native accessibility bridges are separate unfinished infrastructure. The implementation derives panel IDs by XORing the trigger ID with `0x1d8f322539deca61`; Collapsible derives its outer container using `0xb7c1c9d453922783`. Reserve those IDs when composing children. Duplicate IDs are diagnosed by the core rather than silently reused. `tests/unit/test_disclosure.c` exercises all four supplied themes, actual pointer clicks, Enter and Space, disabled triggers, single/multiple expansion, required expansion, keyboard traversal, and removal of focused hidden content. Portable C11 and renderer-independent draw lists are supported; OS accessibility is not claimed. Compared with upstream kit 0.7.1, a demonstrated native/browser gallery remain unfinished. Immediate mount/unmount behavior is implemented. Full family parity is not yet verified. Set Accordion `render_header` and `header_user` to compose a custom title, icon, badge or other header body. `cui_collapsible_ex` exposes the same callback and optional `borderless` appearance; `cui_collapsible` retains its existing defaults. The callback replaces the default title/indicator body, receives the current expanded state and effective disabled item, and executes inside the themed trigger box. The original item's label remains the accessible name. Trigger activation, keyboard navigation and panel mounting continue to use base behavior. Callback item pointers are borrowed only for that invocation. Headless tests verify custom headers, semantic names, individual/group disabled propagation and actual pointer and keyboard activation of both components. Accordion `trigger_boxes` and `panel_boxes` are optional borrowed per-item arrays of full `cui_box` styles; `style_count` bounds both nonnull arrays, and later items keep the theme defaults. `cui_collapsible_ex` accepts individual `trigger_box` and `panel_box` pointers. These override layout/paint properties without replacing base activation or accessible names. Header focus still uses the theme focus color and border width; explicitly masked border edges remain a caller style decision. Tests assert distinct overridden header/panel bounds and colors, fallback styles beyond the array and pointer toggling in both APIs. Opt into measured reveal with a zero-initialized `cui_disclosure_motion` kept in application state. Collapsible accepts its pointer; Accordion accepts an array and `motion_count`, with later panels retaining immediate mount/unmount. Set `dt` to elapsed seconds; optional positive `response` overrides the theme spring natural period in seconds. A reversible theme-configured spring drives a clipped viewport from zero to the full measured panel height. Initial state snaps; `reduced_motion` also snaps. Invalid/nonpositive dt leaves progress unchanged. Measurement updates at end_frame, so changed content sizes affect the viewport on the following frame. The motion state and array must remain valid through end_frame and be dedicated to stable trigger IDs; reusing a state for another ID resets it. With motion enabled, panel callbacks also execute while collapsed to measure their full natural layout. They must submit UI rather than perform application side effects. Settled collapsed bodies use layout-only boxes: no paint, semantics, events or focus. Closing bodies keep painting inside the shrinking clip but become inert immediately when the controlled boolean becomes false. Pending animation and changed measurement invalidate the frame. Custom panel styles remain inside the reveal viewport. Header and controlled expanded semantics change immediately; the return value still reports only controlled state changes. Headless tests exercise actual pointer/keyboard expansion, measured initial hidden content, intermediate height, reversal, closing paint with immediate focus/event withdrawal, dynamic content size, reduced motion and bounded Accordion storage. Styled panels use `theme.spring_control` response/damping/epsilon/travel. Natural frequency is TAU/response, as in the reference. A zero response or false travel snaps even at zero dt. Damping below one may overshoot; the retained spring value keeps that trajectory while reveal height clamps to zero/full height. Settings with invalid response/damping/epsilon use safe defaults. Tests compare differently configured response/damping, preserve underdamped overshoot, and verify theme travel/zero-response snap through actual trigger clicks. The public `_step_ex` accepts the same portable policy; the original `_step` keeps critical damping and its legacy .2-second default response. A demonstrated gallery remains unfinished. --- ## Distribution test compilation Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DISTRIBUTION_TEST_BUILD.md # Distribution test compilation Design checkpoint: share a private test-only `CUI_IMPLEMENTATION_ALL` object between feature distribution consumers. Keep `dist_all` as an independent self-contained implementation and consumer in one translation unit. Keep every single/multi-file, standalone, legacy and additive module implementation target unchanged, including standalone DateTimePicker and Stepper. Production libraries, headers, amalgamations and install/export rules are outside this change. At revision ad4c6f37, ten source fixtures plus the generated Popover fixture compile the full umbrella implementation. Eligible feature consumers use public APIs; any consumer requiring private static helpers must remain independent. Compile the shared object and consumers with the existing warnings, assertions, sanitizers and configuration optimization. Do not link the source CUI library into these umbrella tests. Feature tests continue to run against the shipped amalgamation. The independent `dist_all` retains same-translation-unit optimized umbrella coverage. Consolidated feature tests lose their repeated per-feature same-translation-unit optimization/inlining proof; they exercise separate consumer and implementation objects instead. Packaging and standalone entry contracts stay independent. Completed [Windows Release run 39774911352](https://github.com/mattmezza/cui/actions/runs/39774911352) spent 463 seconds building (12:01:13–12:08:56 UTC, 22 October 2026) and 410 seconds running CTest. This was MSVC Release, not a GCC `-O3` measurement. Distribution target diagnostic-to-link spans overlap and cannot establish isolated costs or predicted savings. CTest also spent 149.25 seconds on package-source checks and 140.24 seconds on installed-skill checks. Consolidation does not remove those checks. This run is the historical comparison point, not an isolated compilation benchmark. Alternatives are retaining all repeated compilations (maximum same-TU coverage) or adding compiled-output caches (more invalidation and provenance complexity). Lowering optimization or dropping runtime/standalone tests is excluded. A local fresh Ninja Release sample on Linux/GCC 16 built only VideoControls and Stepper ALL targets with parallelism 2: before consolidation 130.277 seconds; after consolidation 118.969 seconds. Both configurations kept `-O3`, `-UNDEBUG`, strict C11 and the existing warnings. This is one wall-clock sample on a shared host, not a controlled benchmark or a Windows speedup claim. The after sample includes compiling the shared provider once; later feature consumers reuse it. A subsequent [Windows Release run 39781543234](https://github.com/mattmezza/cui/actions/runs/39781543234) at `ab8fddbbbca4b78e3b2cc1b14752dd0c4ac96b30` completed the build in 204 seconds (12:49:57–12:53:21 UTC) and CTest in 347 seconds (12:53:21–12:59:08 UTC). Both steps passed, with the same MSVC Release configuration and parallelism2. This is an observed reduction from 463/410 seconds in the earlier run; the commits, hosted runners and workload differ, so it does not isolate the shared-object change or establish a repeatable speedup. The overall workflow was still running when these completed job-step timings were recorded. Full optimization and the runtime, standalone and independent self-contained checks remain enabled. --- ## Styled Dock Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DOCK.md # Styled Dock The Dock view composes the portable Dock model, Tabs, Buttons and Resizable into a themed workspace. Each leaf shows an overflow-scrolling tab strip and calls only its active panel's content renderer. Nested horizontal and vertical splits use pointer and keyboard resize handles; changed ratios or opt-in n-ary slot sizes are written back to the model and therefore included in its serialization. This implementation was checked against the frozen upstream kit 0.7.1 reference, commit `87d10ae5e1299d1be18670a37570c5402f952e34`, including `crates/component/src/dock/dock.rs`, `tab_panel.rs` and `website/component/dock.md`. It implements a specific subset, not full Dock family parity. Panel menus are implemented. Native floating windows are outside the frozen Dock API audited here. Edge regions have explicit limits described below. Programmatic `cui_dock_move` and `cui_dock_split` remain available. No platform or Clay types appear in the public API. ## Minimal composition ```c #include "cui/cui_dock.h" static void editor(cui_context *ui, uint64_t key, void *user) { (void)key; const cui_theme *theme = user; cui_text(ui, cui_string("Your editor controls go here"), 16, theme->text); } /* Create once, outside the frame loop. */ cui_dock *model = cui_dock_create((cui_dock_config){0}); cui_dock_view *view = cui_dock_view_create(0, 0); /* Check both allocations before use. Panel keys are stable application IDs. */ cui_dock_insert(model, cui_dock_root(model), 42, 0); /* Inside a begun CUI frame; theme and registry stay alive through rendering. */ cui_dock_panel registry[] = { {.key = 42, .title = cui_string("Editor"), .closable = true, .render = editor, .user = &theme} }; cui_dock_view_options options = cui_dock_view_options_default(); options.width = available_width; options.height = available_height; cui_dock_view_result result = cui_dock_view_render( ui, 100, &theme, model, view, registry, 1, options); /* Check result.error. Destroy view and model after the frame loop. */ ``` `width` and `height` must be finite and positive. Content callbacks submit ordinary CUI controls inside a clipped active-panel region; the host provides frame/event processing and rendering. Registry keys must be unique. An absent registry entry produces an unavailable-panel placeholder rather than invoking a callback. Panel keys include zero and `UINT64_MAX`. Panel-key-derived tab and close IDs remain stable across reorder and persistence restore; node-derived group/handle IDs change when model generations change. View storage is allocated once, with defaults of 128 nodes and 256 panels. Its capacities must cover the entire model; insufficient capacity returns `CUI_DOCK_CAPACITY` before submitting the view. Keep one retained view per model/workspace ID. Rebinding to another model or ID resets retained state; `cui_dock_view_reset` explicitly clears it. Registry strings, callback user data and retained view storage must remain valid through frame rendering. ## Interaction and state - Clicking a tab selects its stable panel key. Tabs provide roving focus, arrow/Home/End navigation and overflow reveal; disabled tabs are skipped. - A closable, enabled panel has a real close button. Ctrl/Meta+W closes the active panel when its tab or close button has focus, outside IME composition. Closing collapses empty nonroot groups through the model and restores focus to a surviving tab. - Same-group pointer drag reorders tabs without changing their panel keys or active selection. `allow_reorder` disables this. Cross-group drops in the center append and select the panel in the target group. Content edges create a 50/50 horizontal or vertical split; the tab strip itself accepts center moves. Edge zones extend up to 32 logical pixels (20% for small groups); left/right take precedence at corners. A six-pixel pointer movement starts the gesture. Escape, pointer cancellation, dropping outside the workspace, disabled sources and disabled workspaces cancel it. - Split handles use existing Resizable pointer capture, keyboard stepping, focus and semantics. Aggregate child minimum sizes constrain feasible layouts; infeasible minima are proportionally compressed and reported by `result.fit_minimum == false`. Split handles overlay the zero-gap model layout rather than consuming a separate gutter. - `focus_content` optionally moves focus to the selected panel's declared `focus_target` after its callback submits controls. With this option disabled, selection keeps tab focus. - `disabled` prevents workspace interactions and marks content inert. The panel callback still renders its contents. Selection and resizing update the model during the call. Structural close/reorder/move/split changes commit after scene submission and invalidate the next frame; redraw before inspecting their new geometry. At most one structural action commits per view call, with close taking precedence over a cross-group/edge drop, then same-group reorder. Rejected drops return a model error and preserve the layout; the initial pointer-down selection remains an ordinary selection. `on_event` receives selected/closed/reordered/resized/moved/split notifications; callbacks must not mutate or destroy the model/view during rendering. Do external model edits between frames. Serialization persists model layout, active keys and ratios, not registry callbacks or transient view state; see [Dock model](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DOCK_MODEL.md). `cui_dock_split_layout` exposes the same pure split geometry/minimum calculation used by model layout. It accepts a split node and finite nonnegative rectangle/gap, returns its two child rectangles and aggregate minima, and leaves output untouched on failure. Its `fit_minimum` reports fit along the split axis; the view's result reports the whole workspace's two-dimensional minimum fit. During a drag, an inert title preview follows the pointer inside the workspace and an outlined translucent region shows a center or half-group edge target. Default colors come from the supplied theme. `custom_palette` enables `drag_palette.accepted`, `rejected`, `background` and `text`, including alpha. `disable_preview` suppresses these portals; `disabled` suppresses gestures and previews. Preview geometry changes immediately without animation, including when `reduced_motion` is true. The underlying Tabs adapter retains its own same-group insertion marker. The target indicates host-policy permission; model/view capacity can still reject the release. `allow_operation(policy_user, request)` is a reusable veto for `CUI_DOCK_CLOSED`, `MOVED`, `SPLIT` and `REORDERED`. The request carries stable panel/source IDs and operation-specific destination/index/axis/before fields. For close there is no destination; for reorder `index` is the final index and `source` identifies the group. Move uses `SIZE_MAX` to append; split uses a 50/50 ratio. NULL allows every operation. The callback must be pure and must not mutate the model/view: it can run during preview and runs again immediately before commit. A denial sets `result.denied`, emits no structural event and leaves layout unchanged; normal pointer-down tab selection may already have occurred. Programmatic model calls intentionally bypass view policies, allowing the host to implement its own trusted actions. `cui_dock_move_split` stages removal and split creation in the model's bounded scratch storage and commits only on success. Rejection preserves layout, node generations and output. The new leaf inherits the source group's minimum sizes; target constraints remain unchanged. A sole panel cannot split itself. View storage must accommodate two additional nodes for an edge drop (a conservative check even when a source collapse could free nodes). For generated standalone distribution use, `CUI_DOCK_BASE_ONLY` opts out of the styled Dock implementation so the pure model can be embedded without the component library. Define it before `CUI_DOCK_IMPLEMENTATION` and including `dist/cui_dock.h`. The normal styled bundle requires its documented CUI component dependencies; this macro does not remove public model declarations. ## Active-panel toolbars and zoom An optional `cui_dock_panel.toolbar` callback submits ordinary controls in a clipped row below the tab strip. It receives the same key/user data as content. Only the active panel in each visible leaf runs this callback. `toolbar_height` defaults to 32 logical pixels when the row is present; content receives the remaining height. Disabled panels/workspaces render the toolbar inert. `panel.zoomable` exposes a maximize control. Its stable ID is `cui_dock_zoom_id(view_id, panel_key)`. A view retains a stable maximized-panel key and renders its leaf across the workspace, hiding other split leaves. Tab selection within that leaf updates the retained key. Zoom changes presentation, not split ratios or model serialization. `cui_dock_view_zoomed` queries it; `cui_dock_view_set_zoom` allows trusted host actions and activates the requested panel. Zoom-in consults `allow_operation` with `CUI_DOCK_ZOOMED` and emits that event on success. Restore emits `CUI_DOCK_RESTORED` and is always available while maximized, even when zoom capability, policy or workspace interactivity is later revoked. It bypasses veto to avoid trapping the user. Restoring requests focus on the panel tab; disabled tabs follow the core's normal focus eligibility rules. Node generations can change during model restore while the maximized key survives. Removing the maximized panel automatically restores the workspace and requests a surviving tab's focus on the next frame. View reset clears zoom. Toolbar callbacks and all policy/event callbacks must respect the rendering ownership contract. ## Independently resizable edge regions `cui_dock_workspace` wraps four independent model/view/registry descriptors ordered `CENTER`, `LEFT`, `RIGHT`, `BOTTOM`. Left/right run the full workspace height; bottom sits below the center between the side regions. Each open region can itself contain nested splits and tabs. Stable `cui_dock_region_id` values namespace controls, and `cui_dock_edge_resize_id` exposes keyboard-focusable resize handles. ```c cui_dock_workspace *area = cui_dock_workspace_create(); /* Create and check distinct models/views for every region you will open. */ cui_dock_region_content regions[4] = { {.model = center_model, .view = center_view, .panels = center_registry, .panel_count = center_count}, {.model = left_model, .view = left_view, .panels = left_registry, .panel_count = left_count}, {.model = right_model, .view = right_view, .panels = right_registry, .panel_count = right_count}, {.model = bottom_model, .view = bottom_view, .panels = bottom_registry, .panel_count = bottom_count} }; cui_dock_workspace_set_edge(area, CUI_DOCK_LEFT, true, 200); cui_dock_workspace_set_edge(area, CUI_DOCK_BOTTOM, true, 160); /* Within a frame; an unopened descriptor may be empty. */ cui_dock_workspace_options area_options = { .view = cui_dock_view_options_default() }; area_options.view.width = available_width; area_options.view.height = available_height; cui_dock_workspace_result area_result = cui_dock_workspace_render( ui, 100, &theme, area, regions, area_options); /* Destroy area and separately destroy all owned models/views when done. */ ``` Use `cui_dock_workspace_set_edge` between frames to open/close a region and assign its preferred size; a closed region runs no panel callbacks. Actual sizes respect aggregate model minima and optional region minima, defaulting to 64 logical pixels for center and 48 for edges. Infeasible minima are proportionally compressed inside the viewport and reported by `fit_minimum == false`. Preferred sizes survive closing and temporary viewport compression. Real handle adjustments update them and invoke `on_resize` with the edge and new logical-pixel size. Disabled/motion settings propagate to all handles and views. The wrapper performs descriptor/capacity validation before submitting its root. Configured region models/views must be distinct, including closed regions prepared as drop destinations. `cui_dock_workspace_save` and `restore` copy a portable field-based snapshot containing three open flags, preferred sizes and noncollapsible flags. Restore validates every positive finite size before changing state. Encode these fields in the host's persistence format alongside each region model's ordinary serialization; the snapshot is not a specified binary file format. Model callbacks, panel registries and transient focus/drag state are not serialized. Mutate neither workspace state nor region models from render/policy/resize callbacks. Zoom is local to the selected region's view; other edge regions remain present. Drag/drop can transfer between configured region models as described below. The wrapper supplies layout and callbacks, not built-in toggle menus or native floating windows. ## Cross-region transfer and closed-edge landing zones A workspace observes tab drags using clipped core focus-scope hits. Dropping into another visible region appends/selects the panel, or creates a 50/50 leaf when released at a content edge. A closed left/right/bottom region has an outer landing zone up to 24 logical pixels (20% of a small viewport), with left/right precedence at corners. A successful drop inserts into its first leaf and opens the edge using its retained preferred size. An empty closed model is a valid destination. Opening commits after transfer; cancellation, disabled input, policy rejection, duplicates or capacity failure never open it. `disable_cross_region` suppresses these transfers; `disable_edge_opening` removes closed-edge landing zones. Regular in-region reordering/splitting retains its existing behavior. Modals/higher interactive layers block workspace gestures through core hit eligibility. Both source and destination descriptors must already register enabled metadata for the panel key. Models are separate containers; registries, strings, callback user data, views and models remain host-owned and must survive the frame/renderer and notifications. Nothing copies/frees registry data. After success, only the destination active content callback runs for that key; duplicate panel keys in the destination are rejected. Internal Dock IDs are namespaced by region, but callback-created control IDs must still be globally unique in the CUI frame. `cui_dock_transfer` stages source removal and destination insertion/splitting in each model's bounded scratch storage, then swaps both states only on success. Failure preserves both serialized layouts, node generations and output. Split leaves inherit source-group minima. Ordinary model APIs and direct transfer calls bypass host view policies. Workspace gestures also restore the source group's pre-drag active key on cross-region rejection/cancellation, so dragging an inactive tab cannot leave a serialization change behind. If incidental selection occurred, the view emits a corrective `CUI_DOCK_SELECTED` notification for the restored key; no transfer notification is emitted. Ordinary clicks and same-group gestures retain their selection behavior. The source view's `allow_operation` checks MOVED/SPLIT intent. Its destination node belongs to the other model; use workspace `allow_transfer(transfer_user, request)` for policies needing both models/region IDs. This pure callback can also run during target preview and cannot mutate model/view/workspace state. A denial sets workspace `result.denied`. `on_transfer` runs after both models commit and receives source/destination regions/models, stable key, final destination leaf and whether the edge opened. The request pointer is borrowed only during the callback; the source node ID can be stale after removal collapses its former group. Redraw before inspecting new geometry; destination tab focus is requested on the following frame, or the destination's `focus_target` when `focus_content` is enabled. Zoomed destination views reject drops, matching the frozen reference's zoomed-group safeguard. The frozen reference distinguishes panel drops (`base/src/dock/tab_group.rs`) from dock resize listeners (`component/src/dock/dock.rs`). This implementation supports panel-drop opening of configured closed edges. The opt-in collapsed bottom strip also supports handle-driven reopening as documented below; no native floating-window behavior is implied. Accepted/rejected cross-region landing indicators use the same custom palette and preview settings as the view; actual model capacity remains checked at release. The Dock clips callback paint/input to each allocated pane. A nested GROW callback box with a long intrinsic line can still report raw bounds wider than that pane; those bounds do not enlarge the pane or allow hits into its neighbor. Hosts displaying semantic geometry should use clipped visible bounds or cap/wrap their own content boxes. Headless oversized-content tests verify pane allocation and clipped hover isolation. ## Panel action menus Each active leaf displays an SVG ellipsis menu button by default; `hide_menu` opts out. The adapter composes the existing Menu tree reducer, popup painter and ghost icon buttons. The toolbar zoom button is also an SVG icon with an accessible action name. Custom borrowed `cui_menu_entry` trees are supplied through `panel.menu_items/menu_count`; selected custom IDs invoke `panel.menu_action` after scene submission using `panel.user`. Trees must have unique nonzero interactive IDs, valid descriptors and at most `CUI_DOCK_CUSTOM_MENU_LIMIT` entries across all descendants. Builtin action IDs are reserved. Keep descriptors and callback data alive across frames; do not mutate model/view state from callbacks. Builtins provide Close, Close Others, Close All, Maximize/Restore, horizontal/vertical split and Balance parent split. Close Others/All operate on the current leaf and skip protected, disabled or unregistered panels. Every eligible key passes the close policy before an atomic bulk removal; one veto preserves the complete serialized layout. `result.closed_count` reports the number removed and each successful close emits its usual notification. `cui_dock_remove_many` exposes the same transactional model primitive without view policies. Split moves the active tab into a new 50/50 leaf and requires at least two tabs; Balance sets the immediate parent ratio to 0.5. Existing split/resize policies apply. Disabled actions cannot activate, while restore stays reachable for an already maximized panel. `cui_dock_menu_id` and `cui_dock_menu_action_id` provide stable semantic IDs. The frozen component `dock/tab_panel.rs` composes host dropdown entries with zoom and close actions, using ellipsis and maximize/minimize SVG controls. CUI follows that composition; Close Others/All, split and balance are explicit CUI extensions, not claims about the frozen menu. Customizable zoom-control placement and native floating hosting remain separate work. ## Validation The headless styled test exercises active-only callbacks, stable keys including zero/`UINT64_MAX`, disabled controls, keyboard focus/navigation, close shortcuts, collapse, same-group pointer reorder, nested pointer/keyboard resize, infeasible minima, restore/reset and capacity rejection. The model unit test checks split geometry against leaf layout and transactional validation failures. Cross-group and all four edge drops are tested with queued pointer events, including cancellation, outside drops, disabled/reorder-off and full-capacity rejection. Draw-command tests verify accepted/rejected custom preview palettes, preview suppression, motion settings and cancellation cleanup. Host veto tests cover close buttons/shortcuts, reorder, move and split. Toolbar/zoom tests cover active callbacks, controls, focus, persistence and removal recovery. Edge-region tests cover independent geometry, real pointer/keyboard resize, callbacks, hide/reopen, model minima, disabled controls, constrained viewport preference retention and rejected snapshot restoration. Two-model transfer tests cover queued region/edge gestures, callback ownership/focus, empty closed destinations, cancellation/modal blocking, duplicate keys, disabled/missing metadata, policy veto and full model capacities, with serialized/snapshot equality on rejection. Menu tests cover SVG draw commands, custom and disabled actions, all four zoom placements, restore, atomic bulk vetoes, protected tabs and split/balance actions. Collapsed-bottom tests exercise real pointer/keyboard opening and snapping, same-tab reopening, protected close shortcuts, no content/actions while closed, disabled gestures and snapshot rollback on cancellation or a blocking modal. No native window or browser-specific behavior was tested for this adapter. Until the integrator wires the new component source and test into CMake, reproduce from the repository root: ```sh cmake -S . -B build -G Ninja cmake --build build ctest --test-dir build --output-on-failure cc -std=c11 -Wall -Wextra -Wpedantic -Werror \ -Iinclude -Ithird_party/clay src/components/cui_dock.c \ tests/unit/test_dock_styled.c build/libcui.a -lm -o build/test_dock_styled ./build/test_dock_styled ``` After integration, applications link the usual CUI library containing the styled adapter; no added dependencies are required. ## Remaining reference work The frozen panel presentation trait exposes `toolbar_buttons` and `zoom_control` separately from base capabilities such as closable/zoomable. The active-panel toolbar callback and retained zoom support now cover that composition, with tests for focus, persistence, model edits/removal and toolbar ownership. The `zoom_control` field supports Both, Menu, Toolbar and None. Its zero default preserves the original CUI both-controls behavior; choose Menu for the frozen presentation default. None prevents user-initiated zoom, while an already zoomed panel always offers restore. The programmatic view setter has no registry and intentionally bypasses this presentation gate. The reference's edge docks are independently openable/resizable left, right and bottom regions around the center Dock area. The workspace wrapper now implements those retained regions, minimum allocation, pointer/keyboard resizing, toggles and field-based persistence. The opt-in collapsed bottom strip now covers continuous resize/snap behavior; per-edge collapsibility is retained in the workspace snapshot. Native floating windows require a host window-management contract and are not implied by portable layout/render support. ## Frozen source and export audit This audit uses the frozen commit above, both Dock `mod.rs` export lists, `website/base/dock.md`, `website/component/dock.md`, `base/src/dock/{dock_area,dock_placement,panel,registry,state,state_convert,tab_group,drag}.rs`, the layout modules, and component `dock/{panel,tab_panel,dock}.rs`. Names below group every public export family; mapping is behavioral, not Rust ABI compatibility. | Frozen exports / presentation | CUI coverage and precise limits | | --- | --- | | `DockLayout`, `PaneTree`, `PaneNode`, `PaneRef`, `NodeId`, `PanelId`, `RootKind`, `InsertTarget`, `EditResult` | Bounded model, stable keys, node inspection, insert/move/split/reorder/remove/activate, transactional restore and normalization. The default constructor preserves binary v1 layouts. The opt-in constructor supports canonical n-ary children, optional sizes, same-axis normalization and transactional v2 persistence. Explicit source-style root policy is available; no identical fluent builder. | | `DockArea`, `DockAreaRenderer`, `DockContext`, `DockEvent` | Styled view and workspace own no panels; callbacks compose ordinary CUI controls, region handles and post-edit notifications. No arbitrary renderer trait override per chrome element. | | `Dock`, `DockSizing`, `DockPlacement` | Retained left/right/bottom open flags and preferred sizes, bounds/minima clamping and pointer/keyboard resizing. Frozen component deliberately does not re-export base `Dock`. Opt-in bottom collapse includes its strip/live-size snapping. Per-edge collapsibility is retained and guards closing and bottom drag snapping. | | `TabGroup`, `TabGroupConstraints`, `TabGroupContext`, `TabGroupEvent`, `TabGroupRenderer` | Active selection, close/zoom, focus, drag eligibility, policy vetoes and preview paint. The view has a collapsed-strip mode. Sealed/in-split constructors and a pure per-node constraint callback cover lock, close permission, last-panel preservation and collapse. These optional policies differ from global disabled state, which also blocks ordinary controls. | | `AnyDrag`, `DragPanel`, `DropIndicator`, `DropPlaceholderBounds`, `DropTarget`, `DragPanelPreview` | Portable queued tab gestures, cross-group/region transfer, content-edge splits, accepted/rejected target indications and previews. No upstream entity drag payload or opaque host drag union is needed for CUI events. | | Base `Panel`, `PanelView`, `PanelEvent` (component aliases `BasePanel`, `BasePanelView`) | Stable metadata, render callback, closable/zoomable/disabled state, focus target and edit events. Hosts retain user data; dynamic visibility predicate; caller-owned next-tick lifecycle reconciliation and factory payload dump callbacks; no automatic view-owned lifetime management. | | `PanelRegistry`, `PanelBuildContext`, `register_panel`, `PanelBuilder`, `PanelSource` | Host-supplied borrowed descriptor registry and placeholder for absent keys. Model serialization and edge snapshot are available; host reconstructs content and separately persists panel payloads/schema versions. Named caller-owned factories reconstruct live descriptors and preserve unknown payloads; typed frozen `PanelState` conversion is available; JSON text parsing remains host-owned. | | `DockAreaState`, `DockState`, `PanelInfo`, `PanelState` | Portable model text, validated edge snapshot and typed `PanelState`/`PanelInfo` import/export. Typed atomic four-model/workspace envelope conversion is available; no JSON text reader/writer; callback data and focus are transient. | | Component `Panel`, `PanelView`, `PanelControl`, `PanelStyle`, `TitleStyle`, `panel_handle`, `DockSkin` | Themed title strings, tabs, toolbar callback, custom Menu trees, SVG controls, four zoom placements and portable scene composition. Title and active title-suffix callbacks compose ordinary CUI controls. Auto/TabBar modes, single-panel title-bar opt-out and multi-panel top-padding override are supported. Optional per-panel simple-title background/foreground match the frozen `TitleStyle` scope. | | Component `ToggleZoom`, `ClosePanel` | Real controls and close shortcut with focus/policy gates; user zoom is withheld when controls are None, and restore stays reachable. No Rust action dispatch registration. | Native floating is not exported or described as a Dock feature in the frozen modules/docs. The occurrences of detach refer to panel removal/reinsertion or detached asynchronous tasks, not native window creation. A future CUI multiwindow host example is an optional extension and cannot stand in for the source gaps above. The frozen `CLOSED_BOTTOM_STRIP` is 29 pixels. `dock_extent` gives closed side docks zero extent and explicitly leaves reopening to the application. The bottom strip retains a reachable handle; `resize_dock` follows the pointer below the minimum and `end_dock_resize` snaps to closed or minimum by the midpoint. CUI covers collapsed **bottom** strip resize/open/close through the opt-in behavior below; it does not invent invisible side handles. ## Collapsible bottom strip Set `workspace_options.collapsible_bottom = true` for the frozen closed-bottom behavior. The default remains false for compatibility with clients expecting a completely hidden closed region. A configured closed bottom model retains a 29 logical-pixel strip, compressed if the viewport cannot fit region minima. Its tabs show no active highlight, content, close buttons/shortcuts, toolbar/menu or panel drag source. The strip still supports roving keyboard focus. A pointer click or Enter/Space on an enabled tab opens the bottom dock at its retained preferred size. Closed left/right docks retain zero extent. The bottom handle permits continuous resizing down to the strip, temporarily showing content above it. Release snaps to the strip or natural bottom minimum according to their midpoint; an open snap never leaves content below that minimum. Preferred size survives closing, so clicking the closed strip restores it. Keyboard handle resize also settles to a valid state. `on_resize` reports live changes and completion with logical size; save the validated workspace snapshot for persistence. Cancel/Escape, disablement or a blocking modal restores the complete pre-drag edge snapshot. Model content and serialization are untouched by this resize gesture. This adds no native window ownership. `view_options.collapsed` independently requests tab-only presentation for an ordinary styled view; it is the workspace's building block, not an automatic reopen controller. The caller owns open/close behavior when using it directly. Multiple/nested groups retain the model topology and each visible leaf's tabs; CUI exposes optional sealed/locked constraints through the policy described below. Optional arbitrary title rendering hooks are described below. ## Per-edge collapsibility `cui_dock_workspace_set_collapsible(workspace, edge, false)` withholds closing for that edge; it preserves its current open flag and preferred size. This matches frozen `DockArea::set_dock_collapsible` and the open-edge guard in `toggle_dock`. An already closed edge may remain closed and can still be opened. Calling `set_edge` to close an **open** noncollapsible edge returns false before changing any state. Making the edge collapsible again permits closing. Center is not an edge and is rejected. Snapshots append `noncollapsible[3]` in left/right/bottom order; zero-initialized old host snapshots preserve the previous collapsible default. Persist these flags by field, together with open flags and sizes. A closed noncollapsible state is valid, as it is in the frozen reference. Restore remains atomic on invalid sizes. For an open noncollapsible bottom dock, resize respects the normal region minimum instead of snapping shut. A closed noncollapsible bottom still retains the opt-in strip; opening/resize returns it to a valid normal size. Headless checks cover all three flags, close rejection without snapshot mutation, valid closed-state restoration, invalid snapshot rollback and real keyboard resizing. ## Panel title composition The frozen component Panel trait exposes `title` and `title_suffix`; `tab_panel.rs` paints every tab title and places the active panel's suffix outside the scrolling strip. CUI supports those hooks through `panel.title_render` and `panel.title_suffix`. Both callbacks receive the context, stable panel key and existing `panel.user`; descriptors and user data stay host-owned. The descriptor's `title` string remains the accessibility name, even when its visual body is an icon, badge or custom text. Do not mutate model/view/registry data from presentation callbacks, and keep callback-created control IDs globally unique across regions. A title callback requires a positive finite `title_width`; its body paints inside that fixed clipped slot. Without custom title callbacks, the original built-in title drawing is unchanged. A group mixing custom and ordinary titles draws ordinary labels with the same default tab metrics and palette. Oversized callback descendants can report raw bounds beyond the slot, but paint and input are clipped and cannot expand the pane. This hook replaces the body, not all tab chrome or its selected/hovered palette. A title-suffix callback requires positive finite `title_suffix_width`. Only the selected panel's callback runs, including the frame in which selection changes. The group reserves its largest declared suffix width (capped below pane width) and subtracts that space from the scroll viewport, preventing selection changes from shifting the strip or overlapping its trailing controls. The suffix wrapper is inert for a disabled workspace/panel; a collapsed group paints no suffix. Title callbacks still paint collapsed tab labels. Widths are validated before submitting the scene, and zero widths without callbacks preserve existing callers. ```c static void title(cui_context *ui, uint64_t panel, void *user) { (void)panel; const cui_theme *theme = user; cui_text(ui, cui_string("Editor • modified"), 14, theme->text); } /* Append to the ordinary panel descriptor. */ panel.title_render = title; panel.title_width = 140; panel.user = &theme; ``` Headless tests verify real custom text/clip commands, unchanged semantic names, active-only suffix ownership and immediate selection routing, clickable suffix controls, disabled/collapsed gates, 160px pane allocation/hit isolation, stable key behavior after restore and atomic descriptor rejection. Per-title chrome colors remain separate audited work; modes and padding are described below. ## Auto title mode and panel-owned chrome Set `view_options.panel_style = CUI_DOCK_PANEL_AUTO` to choose a 30 logical-pixel simple title when a group contains one panel. It retains the panel's semantic name, stable title key, focus/drag source, custom title/suffix callbacks and SVG close control. When groups merge to hold multiple panels they automatically return to real tabs. `CUI_DOCK_PANEL_TAB_BAR` (zero) preserves the original always-tabs presentation. A simple title clips long content; it does not replace it with a synthesized shortened semantic name. In Auto single-panel mode, `panel.hide_title_bar = true` lets a self-chromed panel use the whole allocated pane: no title, close/menu or ordinary toolbar row is submitted. Multiple-panel groups still show tabs so every panel remains reachable; collapsed groups still show their reopening strip. An already maximized panel always retains its restore control even if it hides its own title bar. This is view presentation only; serialization and the panel key are unchanged. Frozen `TabGroupSkin::panel_frame` applies its `inner_padding` hook as an 8px **top** spacer only in groups with more than one panel. Set `view_options.inner_padding = true` for that behavior; `panel.omit_inner_padding = true` removes it for the active panel. Single-panel content receives no spacer, regardless of title mode. Defaults preserve the original CUI zero-padding behavior. Choose Auto and inner_padding explicitly when adopting the frozen presentation defaults: ```c options.panel_style = CUI_DOCK_PANEL_AUTO; options.inner_padding = true; /* A panel that paints its own header can use: */ panel.hide_title_bar = true; panel.omit_inner_padding = true; ``` Headless tests assert simple-label versus tab semantics, exact content-origin changes for title hiding and top spacing, active-panel padding override, collapsed reachability, custom-title/suffix invocation in Auto mode, close-policy veto and real cross-group dragging from a simple title. Mode validation rejects invalid enum values before callbacks or scene submission. ## Group constraints and protected last panels Frozen `TabGroupConstraints` combines alone, dock-locked, collapsed and closable state. A draggable group is unlocked and does not hold the last visible panel in an alone container; closing additionally requires container and panel permission. `sealed()` starts locked, alone and unclosable. CUI provides `cui_dock_group_sealed()` and `cui_dock_group_in_split(alone)` plus an optional pure `view_options.group_constraints(user, model, node)` callback returning `locked`, `unclosable`, `preserve_last` and `collapsed`. A missing callback or all-zero result preserves prior CUI behavior. `locked` suppresses tab reordering, source dragging, incoming drops, splitting and user closing while selection, content controls and zoom remain usable. `unclosable` alone suppresses closing without blocking moves. `preserve_last` protects a group's sole panel against drag/close; with several panels, Close All retains the active key rather than emptying the group. `collapsed` paints that leaf as a tab-only strip without suppressing siblings. User close buttons, shortcuts, menu actions and transaction release checks all apply the constraints. The callback receives the actual model and tab-node ID, including configured closed-edge targets. Cross-region constraints are checked against both models; foreign node IDs are never interpreted as source-model nodes. A denied closed-edge drop leaves both serialized layouts and open flags intact and does not fall through to an unrelated in-region split. Locked workspace destinations paint a rejected target indication. A source that becomes locked while dragging cancels the gesture. Model APIs remain independent of UI constraints and bypass them. `cui_dock_workspace_set_locked` retains the frozen `DockArea::set_locked` policy across frames. It composes with every host group constraint: user close, reorder, drag, split and drop are blocked across all regions, while tab selection, content controls, zoom and splitter resizing remain available. Locking during a workspace drag cancels it. The lock is transient UI state, separate from snapshots and typed persistence. Render again after changing it so the scene reflects the new affordances. `cui_dock_workspace_bounds` reports the actual laid-out workspace rectangle from the last completed frame, matching the frozen area's prepaint bounds. It starts at zero, and `cui_track_bounds` updates it at `cui_end_frame`; the workspace object must remain alive until that call completes. This is the current layout result, including host positioning, rather than the preferred width and height passed in render options. ```c static cui_dock_group_constraints constraints(void *user, const cui_dock *model, cui_dock_node group) { (void)user; /* Derive node identity from a stable panel key after every restore/edit. */ cui_dock_node editor_group; if (cui_dock_panel_find(model, 42, &editor_group, NULL) && editor_group == group) return cui_dock_group_sealed(); return cui_dock_group_in_split(group == cui_dock_root(model)); } options.group_constraints = constraints; ``` Callbacks and user data remain host-owned; evaluate deterministically and do not mutate model/view/registry data. Constraints are presentation policy, not serialized model data. Restore can invalidate node IDs, so derive them from stable keys or refresh host mappings. `preserve_last` counts visible panels through the optional visibility predicate. The per-node callback permits additional host policy rather than a second frozen pinned-group primitive. The workspace lock protects panel rearrangement, not splitter geometry; hosts can separately veto `CUI_DOCK_RESIZED` through `allow_operation`. Headless checks exercise constructors in model-only linkage, sealed-source selection/content, blocked close/shortcut/menu and drag, locked targets with byte-equal model serialization, unclosable-but-movable groups, sole-panel preservation, isolated collapse, preserved active key after bulk close, cross-model locked-source/target rejection, closed-edge non-opening, target permission revoked after preview and successful transfer after unlocking. ### Dynamic panel visibility Set `view_options.panel_visible` and `visibility_user` to filter panels without removing them from the model. The callback receives the owning model and stable panel key; a null callback means every panel is visible. It must be deterministic during a frame and must not mutate model, view or registry data. Visibility is host state and is not serialized. ```c static bool panel_visible(void *user, const cui_dock *model, uint64_t key) { const bool *show_inspector = user; (void)model; return key != 42 || *show_inspector; } /* Keep show_inspector alive while these options are used. */ options.panel_visible = panel_visible; options.visibility_user = &show_inspector; ``` `cui_dock_visible_count(model, node, predicate, user)` counts visible members of a tab group. `cui_dock_displayed_panel(model, node, predicate, user, &key)` returns the stored active panel when visible, otherwise the first visible member; it returns false without changing the output when no member is visible. Neither query changes the active key or layout. Invalid groups return zero/false. The styled adapter uses that same fallback, omits hidden tab/title/content callbacks and semantics, and moves focus from a hidden tab to the displayed panel. Showing the original active panel restores its presentation unless the user explicitly selected another panel. Auto mode uses the visible count; the optional inner-padding rule retains the frozen source's total group-member count. Filtered reordering maps visible anchors back to model indices, retaining hidden members. Close-all and close-others affect visible panels only, and preserve-last protects the displayed visible member. An all-hidden group gives up its geometry slot; an all-hidden zoomed group restores the normal layout. Workspace transfers evaluate visibility against each region's model. Hiding a dragged source cancels the gesture; hiding the incoming key at the destination rejects release with `CUI_DOCK_INVALID`. Both layouts remain unchanged on rejection. Hosts should update visibility between frames, including after a drop preview. Headless tests exercise fallback, focus, unchanged serialization, Auto mode, visible-count protection, filtered reorder, bulk close, zoom restoration, hidden-slot geometry and real queued cross-region gestures. ### Concrete multi-slot sizing The frozen `layout/node.rs` exposes n-ary split children and optional pixel sizes; `layout/edit.rs::set_sizes` rejects a vector whose length differs from the child count. The default constructor offers concrete measured sizing while preserving binary topology and v1 persistence. The opt-in canonical model below implements immediate n-ary children and optional sizes. `cui_dock_split_slots(model, split, slots, capacity, &count)` flattens descendants with the same axis in visual order. A tab group or opposite-axis subtree is one slot. Pass null output to query the count; insufficient capacity reports the required count and leaves output untouched. Tab nodes reject the query. `cui_dock_set_slot_sizes(model, split, sizes, count, gap)` atomically converts positive finite slot extents into the existing split ratios, including internal gaps. The vector must match the projected slot count. Invalid nodes, dimensions, counts or unrepresentable ratios leave the serialized layout unchanged. It preserves node IDs, active panels, topology and opposite-axis ratios. No host callback or view wiring is needed: the existing layout, styled adapter and splitter handles consume those ratios. ```c /* Three same-axis slots, with four pixels between adjacent slots. */ const double sizes[] = {100, 200, 300}; cui_dock_result result = cui_dock_set_slot_sizes(model, split, sizes, 3, 4); /* At an axis extent of 608, these widths are exact if minima allow them. */ ``` At the measured extent `sum(sizes) + (count - 1) * gap`, layout reproduces the requested sizes unless minima constrain them. At other extents the existing binary ratios govern resizing; use the same gap and adopt new measured sizes when appropriate. For a legacy model this remains ratio projection, rather than canonical optional-size storage. Persisted ratios round-trip through the existing v1 format and older layouts still restore unchanged. Headless tests cover three slots with an opposite-axis subtree, gap geometry, minima precedence, query output on insufficient capacity, invalid-vector rollback and persistence. ### Opt-in canonical n-ary models Use `cui_dock_create_nary(config)` to select canonical splits. The existing `cui_dock_create(config)` keeps its binary edits and exact v1 serialization. Both use the same caller-specified bounded node/panel pools and stable panel keys. A same-axis split inserts one sibling instead of introducing another binary container; opposite-axis splits introduce a new container. `cui_dock_node_get` exposes `child_count` and `nary`; `first` and `second` remain the first two children for compatibility. Enumerate every immediate child with `cui_dock_child_at`. ```c cui_dock *model = cui_dock_create_nary((cui_dock_config){0}); cui_dock_node first = cui_dock_root(model), second, third; cui_dock_insert(model, first, 10, 0); cui_dock_split(model, first, CUI_DOCK_SPLIT_HORIZONTAL, .5, 20, false, &second); cui_dock_split(model, second, CUI_DOCK_SPLIT_HORIZONTAL, .5, 30, false, &third); cui_dock_node split = cui_dock_root(model); const cui_dock_slot_size sizes[] = { {.has_size = true, .size = 100}, {.has_size = false}, {.has_size = true, .size = 200}, }; cui_dock_result result = cui_dock_set_sizes(model, split, sizes, 3); /* At width 400 and gap 4, these occupy 100, 92 and 200 pixels. */ ``` Check allocations and operation results in application code. `set_sizes` requires exactly the immediate child count. Known sizes may be zero and must be finite, nonnegative and at most 1e9; unknown numeric fields are ignored. The complete vector is validated before mutation. With unknown children, known sizes reserve pixels and unknown children share remaining space. An all-known positive vector scales proportionally to the available extent; an all-zero vector shares it equally. Minima take precedence, and infeasible minima compress proportionally. `cui_dock_children_layout` returns each immediate child's bounds, aggregate minimum and visibility; a null output queries the count, and insufficient capacity leaves output untouched. Hidden children retain their stored sizes and IDs but consume no geometry or gap. Same-axis normalization follows frozen `distribute_slot`: when an outer size and every inner size are known and the inner sum is positive, inner sizes are scaled to the outer size. If any relevant size is unknown, inner sizes pass through unchanged. Surviving child IDs remain stable; a flattened container ID expires. Explicit nonzero CUI split minima retain a constraint boundary instead of flattening it. Removing a singleton container promotes its child and preserves the container's minimum. Loading does not flatten same-axis descendants or infer pixel sizes; the explicitly selected root policy may wrap/promote the root. A split of a known slot divides its stored size using the requested ratio; splitting an unknown slot retains unknown sizes rather than inventing a measured viewport. Canonical models serialize as `CUIDOCK 2`, using `X`/`Y` splits with child counts and explicit known-size flags; tab and legacy binary node encodings remain available in v2. Restore accepts both v1 and v2 transactionally and selects the encoded editing mode. Restoring v1 into a n-ary-created object therefore resumes legacy binary editing without migration, except when an explicitly pinned root requires canonical root preservation as described below. Malformed counts, duplicate keys, invalid sizes and capacity failures preserve the previous model and output values. Legacy ratio and two-child geometry APIs reject canonical splits with more than two children using `CUI_DOCK_INVALID`; use `set_sizes`/`children_layout` instead. `cui_dock_balance` assigns equal canonical weights, or the legacy .5 ratio. The styled adapter submits one real Resizable handle per visible adjacent child pair; `cui_dock_resize_id_at` identifies a handle by its preceding child index. Pointer and keyboard changes persist accepted measured sizes; merely rendering at a new viewport does not overwrite stored optional sizes. Cancellation ends capture while retaining the last accepted live size, matching the source resize interaction. Disabled state and operation policies block changes. Topology/visibility changes invalidate held splitter state. View capacity checks remain conservative for split gestures: reserve two spare cache entries even when a canonical sibling insertion would need only one model node. Headless checks cover three-child geometry, unknown/zero sizes, minimum compression, nested same/opposite-axis normalization, malformed v2 rollback, exact v1 round trips, full-capacity two-model rejection and 7,000 random edits in each mode. Styled tests exercise the second divider, cancellation, disabled/policy rejection, hidden siblings and edge split/merge with unchanged child counts. ### Frozen method-family mapping The export-family table above is complemented by these operation mappings. CUI exposes portable operations rather than Rust entity types or method signatures. | Frozen method family | CUI operation / limit | | --- | --- | | `PaneTree` node/panel lookup, root, insert/remove/move/split, active selection, sizes and normalization | `root`, `node_get`, `child_at`, panel queries, `insert`, `remove`, `move`, `move_split`, `split`, `activate`, `set_sizes`; canonical same-axis normalization is automatic after edits. `create_with_root` selects source-style root preservation. | | `PanelBuilder` horizontal/vertical splits, child optional sizes, tabs and active index | Compose canonical model operations and `set_sizes`; typed schema conversion is available; no fluent builder or JSON parser. | | `DockArea` center/edge installation, open/toggle/collapsible, lock, add/remove/select/move, zoom, dump/load | Workspace descriptors, retained layout lock, edge setters/snapshot and model/view operations; hosts supply independent models and caller-owned factory payload records. | | `TabGroup` sealed/in-split constraints, active/displayed panel, close/zoom and renderer | Group constraint constructors/callback, visibility-aware queries, real view controls, menu/policy callbacks and scene callbacks. | | `Panel` visible, closable, zoomable, title/style/suffix, toolbar, menu, focus and lifecycle | Borrowed descriptors and presentation callbacks, visibility predicate, factory/dump helpers and caller-owned lifecycle reconciliation. Optional simple-title palettes match the source; custom title scenes choose their own explicit ink. | | `DockSizing` bounds/minima, pointer resize, collapsed-bottom reopen | Retained workspace handles, minimum compression and collapsibility flags; no native window creation. | The frozen public `DockArea` methods have these more precise counterparts: | Source methods | CUI counterpart and remaining boundary | | --- | --- | | `new`, `with_renderer`, `id`, `version`, `set_version` | Caller constructs a workspace and four models/views, supplies the view ID/theme at render, and uses workspace version accessors. There is no Rust entity or renderer object. | | `bounds`, `layout`, `panel`, `is_empty` | `workspace_bounds` retains completed-frame geometry; hosts query each model and borrowed descriptor registry. `visible_count`/`displayed_panel` plus edge presence answer emptiness; there is no one-object area lookup. | | `is_locked`, `set_locked` | Retained workspace lock composes with host group constraints and leaves resizing available. | | `set_center`, `set_dock`, `remove_dock`, `has_dock` | Models are caller-owned; typed area import atomically replaces all four and tracks optional edges. Individual add/remove uses model edits and workspace edge state. No single CUI call owns/reclaims live panel instances. | | `is_dock_open`, `toggle_dock`, `is_dock_collapsible`, `set_dock_collapsible`, `dock_size`, `set_dock_size` | Edge snapshot and setters carry open, collapsible and preferred size. Hosts can read the snapshot; absent and closed are distinct in typed area export. | | `add_panel`, `add_panel_view`, `remove_panel`, `move_panel`, `select_panel`, `set_split_sizes`, `split_at` | Model insert/remove/move/transfer/activate/sizing operations and styled gestures. Host descriptors supply the live panel behavior; explicit callbacks and model operations replace entity ownership. | | `set_zoomed_in`, `set_zoomed_out`, `is_zoomed`, `zoomed_group` | View zoom setters/query identify a panel and its group; zoom remains transient. | | `load`, `dump` | Atomic typed area/model conversion and host JSON/payload callbacks. Workspace export resolves positive split sizes from matching rendered views, stored sizes, then the frozen minimum. | Frozen `StackPanel` and `TabPanel` state names and the bare default Panel are represented by the typed schema converter. The styled title accepts host render callbacks in explicit clipped width slots; upstream element flex sizing for arbitrary title children is not reproduced. CUI's event targets come from the preceding completed frame's clipped hits, so an event in the same frame as a new layout uses prior hit geometry. Lifecycle deliveries remain explicit next-tick net-state reconciliation instead of automatic Rust entity updates. These differences still prevent a full Dock-family parity claim. Lifecycle reconciliation is explicitly deferred and net-state based; it does not reproduce every synchronous Rust entity arrival or intermediate zoom event. Typed source-state conversion preserves the frozen field contract while JSON text parsing/encoding and payload envelopes remain caller-owned. These remaining differences prevent a full Dock-family parity claim. ### Caller-owned panel reconstruction and payloads The frozen `registry.rs` registry is keyed by persisted panel name, and returns a rich panel view whose `dump` can write updated payloads. An unknown name must retain its original state across load/save. CUI's `cui_dock_panel_factory` provides this seam without a global registry or platform types. A `cui_dock_panel_state` carries a stable key, factory name and opaque payload bytes. Pass records plus a borrowed factory array to `cui_dock_panels_reconstruct`. Records must cover every model key exactly once; duplicate keys/names, missing keys, incomplete coverage and insufficient output capacity reject before invoking builders. A builder receives the owning model, current tab ID and record, and fills a live `cui_dock_panel` with the same key. Copy each successful instance's `panel` into the contiguous descriptor array passed to `cui_dock_view_render`. ```c /* build_editor/destroy_editor/dump_editor use the factory signatures above. */ cui_dock_panel_factory factories[] = { {cui_string("Editor"), host, build_editor, destroy_editor, dump_editor} }; cui_dock_panel_state records[] = { {42, cui_string("Editor"), cui_string("{\"document\":7}")} }; cui_dock_panel_instance instances[1] = {0}; cui_dock_result result = cui_dock_panels_reconstruct( model, records, 1, factories, 1, instances, 1); if (result == CUI_DOCK_OK) { cui_dock_panel descriptor = instances[0].panel; /* Render with &descriptor/count=1 while all borrowed data stays alive. */ (void)descriptor; cui_dock_panel_state saved; if (cui_dock_panel_dump(&instances[0], &saved) == CUI_DOCK_OK) { /* Copy saved.name/payload into the host's persistence envelope. */ } cui_dock_panels_release(instances, 1); } ``` Factories supply `build`, `destroy` and optional `dump`. Successful instances retain a borrowed factory pointer. Unknown names produce a descriptor with the original key/title and no content callback, while retaining the exact name/payload bytes, including embedded NULs. A dump callback returns borrowed updated payload bytes; without one, `cui_dock_panel_dump` returns the original payload. A failed dump leaves output untouched. The factory name and key remain the original identity. For frozen `PanelBuildContext` consumers that need the full typed leaf, use `cui_dock_panels_reconstruct_typed` with keyed `cui_dock_panel_typed_state` records. The named builder receives `context.source` with the original `PanelState`-shaped leaf, including its borrowed children and opaque payload; the simpler reconstruction path sets this pointer to null. Instances keep a shallow copy of the full leaf. `cui_dock_panel_dump_schema` returns that complete state for unknown panels, preserving nested fields during a schema round trip. Known factories may provide `dump_schema` to replace the complete leaf, or keep the older `dump` callback to update only its payload. Typed records and all nested borrowed data must survive through the final dump or release. The typed method uses the same exact key coverage, preflight, staged construction and failure cleanup as the simple method; no builder runs for a rejected non-leaf record. Reconstruction stages descriptors before publishing output. On a failed builder or mismatched returned key, successful staged instances are destroyed and output/model remain unchanged. A builder that returns failure must clean up its own partial resources. Builders, destroy and dump callbacks must not mutate the model, registry, records or output arrays, or recursively invoke reconstruction on the same storage. Arbitrary external callback side effects cannot be rolled back. The caller owns instance storage, descriptors, registry, payload bytes and all factory-created user data. Keep borrowed registry/strings alive until `cui_dock_panels_release`; that function destroys each successful known instance once and clears the array. Do not overwrite live instances with reconstruction. Release descriptors only after the UI no longer references them. Dump payloads remain valid according to the factory's documented lifetime and should be copied into host persistence before it expires. The v1 layout remains unchanged. Restore the layout first, reconstruct its records into new storage, then publish the model and descriptors together; preserve the old model/instances until both steps succeed. Hosts can wrap the layout, panel records and application schema version in their own JSON or other format. This factory seam does not parse JSON, manage application schema migration or deliver lifecycle notifications. The typed schema converter below handles frozen tree structure. Headless tests reconstruct and render a real control, dump updated known payloads, retain byte-exact unknown payloads, reject invalid coverage/duplicate registry names before callbacks, roll back a later failed builder and wrong-key builder, preserve serialized layout, and verify destruction occurs once. ### Deferred lifecycle reconciliation The frozen `panel.rs`, `active.rs` and `tab_group.rs` distinguish group arrivals from genuine removals. Initial reconciliation announces only the active panel; inactive panels never receive an initial `false`. Active changes use frame-end net state, with deactivation before activation. A hidden stored-active panel still receives `true`, independently of visible rendering fallback. Moves preserve prior notified active state and re-add to the destination group without removal. Removal itself is the deactivation signal. CUI exposes those rules through caller-owned `cui_dock_lifecycle` bookkeeping. Append `on_added`, `on_removed`, `set_active` and `set_zoomed` callbacks to descriptors, using the existing panel `user`. Keep two distinct, disjoint `cui_dock_lifecycle_snapshot` arrays alive for the tracker's lifetime. Initialize once; capture the complete workspace after committing edits/end-frame, and dispatch on the next host tick. Include closed regions: closing an edge is not removing its panels. Missing descriptors are still tracked by key but have no callbacks. ```c cui_dock_lifecycle lifecycle; cui_dock_lifecycle_snapshot current[64], pending[64]; if (!cui_dock_lifecycle_init(&lifecycle, current, pending, 64)) { /* Invalid storage/capacity. */ } /* At the beginning of the next host tick: */ (void)cui_dock_lifecycle_dispatch(&lifecycle); /* After all region edits and rendering have committed: */ cui_dock_lifecycle_region regions[] = { {.model = center_model, .view = center_view}, {.model = inspector_model, .view = inspector_view} }; cui_dock_result result = cui_dock_lifecycle_capture( &lifecycle, regions, 2, descriptors, descriptor_count); ``` Pass each region's visibility predicate to determine its visible zoom recipient; active notifications use the stored active key. Set `collapsed` or a pure `group_collapsed` callback to mirror collapsed group constraints: collapse deactivates the stored active panel, and reopening activates it again. Ordinary closed edges should remain uncollapsed unless the host intentionally presents the collapsed bottom strip. The lifecycle capture itself does not change layout, focus, policies or visibility. Repeated successful captures replace pending state until dispatch, so within-frame selection churn produces only net active edges. Capacity, duplicate descriptors, repeated model regions or duplicate keys across models reject before changing pending notifications. All regions must be captured together to recognize cross-region moves. A failed or vetoed edit whose model stays unchanged yields no lifecycle edge. Dispatch commits bookkeeping before invoking callbacks. It delivers group arrivals first, genuine removals next, then all active deactivations before activations. Moving the same instance to a different model/tab calls `on_added` with the new location; it never calls `on_removed`. An optional `lifecycle_identity` token distinguishes a newly constructed instance at an existing stable key: changing the token emits new-added, old-removed and initial activation for the replacement. With null tokens the stable key is the instance identity. Restore-invalidated tab IDs produce a fresh group arrival while retained instance active state remains seeded. Group zoom-state edges notify only the currently visible displayed panel, including restore even when that panel never received zoom-in. Selecting another tab in an already zoomed group does not retroactively notify it. Capture reports net group zoom state; it does not reconstruct every intermediate zoom toggle within one tick. The frozen source dispatches zoom operation events asynchronously, so hosts requiring that event stream should retain their operation results separately. Callbacks run outside rendering and can edit a model for the next capture. Recursive capture/dispatch on the same tracker is rejected. Do not reinitialize, directly modify or free tracker storage during dispatch. Callback/user/token resources from both old and new snapshots must remain valid until dispatch completes; callback edits cannot invalidate another scheduled callback's resources. Group/model pointers passed to callbacks are borrowed location identities; retain models through dispatch before destruction. Do not release old reconstructed instances until their removal callbacks finish. For shutdown, capture zero regions and dispatch removals before releasing factories/models; abandoning the tracker emits no implicit callbacks. This explicit host seam batches group-add notifications with next-tick dispatch rather than invoking them synchronously from a Rust entity update. It provides portable net-state bookkeeping, not ownership of panel instances. Tests cover deferred initial activation, coalesced selection churn, ordering, hidden stored-active behavior, collapse/reopen, visible-only zoom delivery without retroactive notifications, cross-region moves, genuine removal without `false`, rejected-capture rollback, postcommit callback edits, reentry rejection and instance replacement. ### Hidden subtree geometry Frozen `Panel::visible` specifies that an all-hidden container gives up its slot. `cui_dock_layout_visible` and `cui_dock_split_layout_visible` apply the same host predicate used by the styled adapter. Hidden leaves contribute no rectangle, minimum constraint or gap. A split with one surviving child assigns that child the whole parent bounds; if neither child survives, neither is rendered. Surviving split-node minimums still apply. A null predicate treats every panel as visible, but an empty tab group has no visible member and is omitted by these filtered APIs. The original unfiltered layout APIs retain their behavior. Filtered leaf metadata counts visible panels and reports the displayed fallback key. The split query provides explicit first/second visibility flags, so zero-size allocated bounds are distinguishable from hidden children. Count queries and insufficient-capacity output follow the existing layout contract. The visibility callback must remain pure and deterministic throughout each query/frame. The styled renderer omits hidden groups and their splitter semantics, cancels held splitters when a branch disappears, and uses surviving subtree minima. Open all-hidden workspace edges are omitted too. Ratios, node IDs, panel order, serialized layout and workspace open/preferred-size state remain unchanged; showing the panels restores their prior geometry. An entirely hidden root paints the workspace background. Center remains the host's workspace area when no edge is present. Meaningful tests cover nested same/opposite axes, hidden minima/gaps, filtered metadata, all-hidden zero geometry, unchanged short output, equality with legacy geometry when every panel is visible, stored-ratio restoration, real held-pointer cancellation, omitted splitter semantics and open-edge omission/reappearance with unchanged preferred state. ### Per-panel simple-title palettes Frozen `component/src/dock/panel.rs::TitleStyle` contains background and foreground colors. `tab_panel.rs::render_title` applies them to the Auto single-panel title; the tab-bar renderer does not read this override. CUI follows that scope with a borrowed optional `cui_dock_panel.title_style` pointer: ```c cui_dock_title_style warning_title = { .background = {83, 47, 17, 255}, .foreground = {255, 225, 177, 255}, }; registry[0].title_style = &warning_title; options.panel_style = CUI_DOCK_PANEL_AUTO; ``` Keep the palette alive through the frame. Changing it between frames updates the header immediately without rebuilding the model or changing persisted data. A null pointer uses the theme. TabBar, multi-visible-panel groups, collapsed strips and a hidden title bar ignore it; content retains its ordinary palette. Disabled default titles retain the theme's muted ink. Explicit custom title/suffix callbacks submit their own colors because CUI scenes do not inherit Rust text styling. Ordinary close/menu controls retain their themed control palette. Tests inspect actual fill/text commands and check geometry, focus, disabled ink and all excluded presentation modes. ### Source-style root preservation Frozen `layout/tree.rs::PaneTree::new` starts an empty horizontal split for both `RootKind::Any` and `RootKind::Split`. `normalize.rs::collapse_root` permits singleton promotion only for Any; `builder.rs::from_layout` wraps a tab root for Split. The new `cui_dock_create_with_root(config, kind)` follows those semantics using canonical storage. `cui_dock_root_policy` queries the retained policy. Existing `create` and `create_nary` continue starting with an empty tab root and unconstrained root policy for compatibility. ```c cui_dock *center = cui_dock_create_with_root( (cui_dock_config){0}, CUI_DOCK_ROOT_SPLIT); cui_dock_node root = cui_dock_root(center); cui_dock_insert(center, root, 42, 0); /* The root remains a split with one tab child. */ cui_dock_remove(center, 42); /* The same root remains a split with zero children, ready for another panel. */ ``` Check allocations/results. Root insertion into an empty canonical split creates a tab child; insertion into its sole tab child may use the root ID as a convenience. A multi-child split is ambiguous and requires the actual destination tab ID. In Any mode first insertion promotes the sole tab child, invalidating the former root ID. In Split mode closing/transferring the last panel preserves the empty split and closing one of two groups preserves a singleton root; ordinary nested singleton containers still collapse. Empty roots submit no title/content/splitter controls; singleton roots fill their viewport without a divider. The policy belongs to the caller's tree configuration, as in the frozen source, and is not encoded as a new persistence field. V2 permits zero/one-child canonical roots but continues rejecting such nonroot nodes. Restore retains the destination's policy: Split wraps a nonempty tab root with an unknown-size horizontal child, converts an empty tab root to an empty split, and retains an existing split root. Any promotes a loaded canonical singleton root. A pinned root selects v2 editing/serialization even when restoring legacy v1 data; legacy binary ratios remain intact until subsequent edits. No pixel sizes are inferred. Capacity/depth failures while inserting or wrapping reject atomically and preserve the model. Successful restore continues invalidating node IDs, so refresh the saved root ID afterward. Structural tests cover empty and singleton construction/layout, nested opposite-axis collapse, stable pinned roots after remove/transfer, duplicate-transfer rollback, v1 wrapping and binary-root removal, v2 empty round trips and capacity/depth rejection. Styled tests close both actual groups, verify divider disappearance and focus repair, then reopen content beneath the retained root. ### Typed frozen persistence schema `cui_dock_schema_node` mirrors the exported `PanelState` / `PanelInfo` data contract from frozen `state.rs`: | Frozen serialized field | Portable typed field | | --- | --- | | `panel_name` | borrowed `panel_name` | | `children` | borrowed contiguous `children` and `child_count` | | `info: {"stack":{"sizes":[...],"axis":...}}` | `SCHEMA_STACK`, `sizes`/`size_count`, `axis` | | `info: {"tabs":{"active_index":...}}` | `SCHEMA_TABS`, `active_index` | | `info: {"panel":}` | `SCHEMA_PANEL`, opaque borrowed `payload` | This is a typed import/export seam, not a JSON text parser. The host decodes/encodes these fields with its own JSON library, keeps payload bytes and strings alive, and handles the outer `DockAreaState` envelope. That envelope has optional `version`, required `center`, and omitted optional `left_dock`/`right_dock`/`bottom_dock`; each `DockState` has `panel`, `placement` (`center`, `left`, `right`, `bottom`), `size` and `open`. The outer converter below stages the complete four-model/workspace envelope. JSON text decoding/encoding remains host-owned. `cui_dock_schema_import` stages the complete model and commits only on success. A pure key callback maps each source leaf to a stable application key. The source schema contains no panel IDs: use host identity data or precompute unique traversal keys, rather than assuming names are unique. Do not construct live panels or mutate models in the callback; rejected imports may have called it for some leaves. Duplicate keys, invalid descriptors, nonfinite/out-of-bound sizes, callback failure and node/panel/depth limits preserve the old model and IDs. Import selects canonical v2 editing, while ordinary v1/v2 restore stays available. The converter follows frozen `state_convert.rs`: it wraps bare leaves in tabs, recursively flattens nested tabs, ignores the old `TabPanel` carrying a Panel variant defect, clamps an excessive active index, drops empty child containers, promotes nonroot singleton splits and normalizes same-axis stacks. Axis zero is horizontal and every other value is vertical. Short size vectors and nonpositive entries become unknown; excess entries do not create children. Values must be finite and bounded to CUI's 1e9 dimension limit. The caller's RootKind policy applies after construction. Source descriptor traversal is bounded by the configured node plus panel capacities and a maximum depth of 64, with model construction also respecting its configured depth; oversized input can reject before normalization would shrink it. `cui_dock_schema_export` takes a pure dump callback equivalent to frozen `PanelSource::dump`, returning complete borrowed leaf states. This supports unknown plugins retaining their original names, payloads and child states. Hosts can use the existing factory `dump` result as the opaque payload and retain original unknown descriptor children. Output container names are `StackPanel` and `TabPanel`; active selection is unconditional even for an empty tab group. Known canonical slot sizes are emitted directly and unknown slots emit zero, matching the frozen writer's sentinel. Real known zero sizes also emit zero and import as unknown, an ambiguity of that source schema. Legacy binary ratios have no absolute pixel value, so their exported sizes are zero; retain v1 serialization or resolve measured canonical sizes when ratio-preserving persistence is required. The existing panel factory records can supply ordinary leaf dumps without giving the model ownership of instances: ```c typedef struct { const cui_dock_panel_instance *instances; size_t count; } schema_host; static bool dump_leaf(void *user, uint64_t key, cui_dock_schema_node *out) { const schema_host *host = user; for (size_t i = 0; i < host->count; ++i) { if (host->instances[i].state.key != key) continue; cui_dock_panel_state state; if (cui_dock_panel_dump(&host->instances[i], &state) != CUI_DOCK_OK) return false; *out = (cui_dock_schema_node){.panel_name = state.name, .payload = state.payload, .kind = CUI_DOCK_SCHEMA_PANEL}; return true; } return false; } ``` A host retaining an unknown full leaf descriptor can instead return that descriptor unchanged, including its borrowed children. The JSON adapter interprets the opaque payload as the Panel variant's value; the base converter does not validate application JSON. Query required capacities with null `nodes`; provide node and double buffers to export. The root is `nodes[0]`, and container child/size pointers point inside those buffers. Callback-supplied leaf strings, payload and descendants remain borrowed. Failed callback/validation leaves counts and buffers untouched; insufficient capacity reports required counts and leaves both buffers untouched. Do not alias buffers with live descriptor data that callbacks read, and keep all borrowed leaf data alive while using the exported tree. Tests transcribe all 16 center story payloads and exact two-tab `[704,263]` vertical geometry from the shipped `fixtures/layout.json`, check typed round trips, query/short-buffer rejection, callback rejection, duplicate IDs, malformed descriptors, capacity failure, nested tabs, unknown children, size sentinels and nonzero-axis compatibility. Styled tests import a selected panel, exercise its real tab/content callbacks, export changed active selection and reimport it. This covers tree conversion; source JSON text parsing and application version migration remain host obligations. ### Atomic typed DockArea envelopes `cui_dock_schema_area` carries the exact outer fields: optional version, required center and three optional DockState records, each holding panel/placement/size/open. `cui_dock_schema_area_default()` mirrors the frozen serde default: no version/docks and a bare unnamed Panel with opaque `null` payload. This differs from the live DockArea constructor's empty split center. Zero-initializing the C struct selects the Stack enum's zero value; use the default helper when that serde default is intended. `cui_dock_schema_area_import_models` requires four distinct caller-owned models in CENTER/LEFT/RIGHT/BOTTOM order. It builds all four replacements in temporary bounded storage, selects Split root policy for center and Any for edges, checks globally unique panel keys, then publishes without callbacks. Missing edges clear former contents to empty unconstrained roots. Rejected source/key/capacity validation preserves every model, ID and editing mode. Keys must be unique across the entire area, not merely one region. Each model retains its configured capacities, and successful replacement invalidates prior node IDs. `cui_dock_workspace_schema_import` adds atomic edge snapshot/version/presence publication and view-capacity preflight. On success it cancels held workspace gestures, resets each supplied view (including zoom), and restores collapsibility to the source load default of true. It emits no resize, transfer or lifecycle callbacks; run the existing caller-owned lifecycle reconciliation after publication. Failed import preserves models, edge flags/sizes, version, zoom and view state. Models are required even for omitted edges; views may be null for headless hosts, and supplied views must be distinct. Frozen `DockArea::load` uses each record's placement rather than its containing field name, and later records win when placements repeat. CUI matches routing/overwrite in left_dock, right_dock, bottom_dock order; overwritten records are not constructed by the pure key mapper. Export canonicalizes fields to their actual left/right/bottom placement. Present edges require positive finite sizes at most 1e9, following the existing CUI workspace bounds contract; the frozen live `Dock::new` itself accepts smaller values, so this is an explicit portable constraint. Center-as-an-edge is rejected because CUI's center has no edge open/size state. Absent descriptors are ignored. Preferred float sizes may be constrained at render time while the retained value remains available for persistence. `cui_dock_schema_area_export_models` and the workspace wrapper stage all region dumps before writing any output tree, size buffer or envelope. Supply four `cui_dock_schema_buffer` records. Query with null nodes for every present region; counts are filled and the envelope stays untouched. Capacity rejection fills required counts but leaves all trees/sizes/envelope untouched. Callback or metadata failure leaves counts untouched too. Output uses the same borrowed leaf lifetime contract as single-tree export. Buffers must not alias each other or live source descriptors. No partial first-region output is published when the final region fails. Frozen serde accepts a missing version on input via its default and serializes None as `"version":null`; optional docks are omitted rather than nulled. The host JSON adapter must preserve that distinction. Workspace version defaults to absent; `set_version` / `version` distinguish absent from present zero. `set_edge` establishes a present edge even when closed. Typed import/export retain omission separately from open=false; legacy edge snapshots continue containing only their existing open/size/collapsibility fields and do not encode version or optional presence. The key/dump callbacks remain pure mapping/serialization seams, not ownership hooks. No live panel factories run inside the atomic transaction. Hosts retain original schema/payload records and reconstruct descriptors with the existing factory seam in temporary caller-owned storage before exposing them. If factory construction must also be atomic with publication, perform typed import against temporary models/workspace, reconstruct there, and publish that host-owned set only after both succeed. Factory cleanup and any external callback effects remain the caller's responsibility; these functions provide no JSON parser or automatic application version migration. Tests cover the complete shipped fixture's center plus left/right/bottom story records and preferred sizes 350/320/200, absent/present versions, outer round trips, routed/duplicate placements, omitted edges, global duplicate keys, final-region callback/capacity failures and all-output rollback. Styled workspace tests verify actual region geometry, closed-but-present export, optional edge omission, model/view/workspace rejection rollback, zoom reset and source collapsibility reset. The workspace exporter resolves every split slot to a positive pixel size as frozen `DockArea::dump` does: a current matching view's last rendered measurement wins, followed by the retained positive model size, then the frozen 100-pixel minimum. A view is used only when it still belongs to the same model and its measured children match the current split, so a model edit before the next render uses stored sizes. This happens after the atomic typed export succeeds; query and failure paths leave output untouched. The pure four-model exporter retains its zero sentinel for unknown sizes because it has no renderer measurements. Preferred edge sizes come from workspace state. ### Owned area reconciliation `cui_dock_area_create` is an optional owner for the four models, four views, workspace, and a bounded registry of panel descriptors. Register each panel key before inserting or importing it. Registration copies the descriptor and optionally retains/releases its `user` through paired hooks; title string storage and other borrowed descriptor data must remain valid while the area lives. `cui_dock_area_regions` exposes the registry for existing workspace rendering. The center starts as an empty Split root, while edge models accept any root shape. The area edit functions reconcile synchronously after successful model edits. A new panel or a panel moved to another tab receives `on_added` after the model has its final structure; a departed panel receives `on_removed` after all arrivals. Cross-region moves keep the same panel identity and do not report removal. Hosts using the returned raw model pointers for edits call `cui_dock_area_reconcile` afterward. An invalid aggregate edit leaves models and notifications unchanged. Imported typed envelopes publish four models and workspace atomically, then reconcile callbacks. `cui_dock_area_tick` emits net active changes after all edits in a frame, with deactivations before activations. A removed panel does not receive a false active event. Zoom edges from `cui_dock_area_set_zoom` are queued individually and delivered in order at the tick, including a true/false pair in one frame. Tick also bounds the queue: an operation requiring more zoom events than remaining capacity fails before changing zoom. Workspace edge open/close changes made through its pointer require a reconcile call before tick so stored active state follows visibility. Callback reentry into the area is rejected; callbacks may inspect the settled models. The host calls tick at its frame boundary. This owner covers the source's model membership and deferred callback sequencing. The host remains responsible for deciding when to call tick and for retaining borrowed panel titles and schema payloads. Pure models, views, and typed envelopes remain available independently. The owned area's edge methods mirror DockArea's optional dock distinction. `has_dock` and the size query distinguish an absent edge from a closed one. Toggling an absent edge returns NOT_FOUND; an open noncollapsible edge stays open. Size updates retain the open state and enforce the workspace's positive finite bounded size. `remove_dock` clears that edge's model and view, clears typed persistence presence, and reconciles panel departures; calling it on an already absent edge succeeds without notifications. Closing a dock merely defers an active=false edge and keeps its panels. These methods operate on the aggregate; callers editing the workspace pointer directly still call `reconcile`. --- ## Retained dock tree and panel model Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DOCK_MODEL.md # Retained dock tree and panel model `cui/cui_dock.h` provides an application-owned retained model for dock trees. Leaves are ordered tab groups; interior nodes are horizontal or vertical splits. Each panel/tab item has an application-supplied stable 64-bit key, including zero. Keys are globally unique within the model. Application content, labels, icons, and platform resources remain outside the model. Tab groups and splits have generational node IDs. IDs remain valid while their nodes survive moves and reorders; collapsed/freed nodes reject stale IDs even if their storage slots are reused. Successful restore invalidates every previous node ID. Applications can rediscover a panel's current tab group by its stable key. Generation exhaustion rejects operations requiring new nodes. Creation preallocates two node/panel state banks. Defaults are 128 nodes, 256 panels, depth 32, and 65536 serialized bytes. Explicit supported ceilings are `CUI_DOCK_NODE_LIMIT` (4095), `CUI_DOCK_PANEL_LIMIT` (4096), depth 64, and `CUI_DOCK_SERIALIZED_LIMIT` (1048576 bytes). Counts and allocation products are checked before allocation. Operations, geometry queries, serialization, and restore allocate no additional memory. `cui_dock_memory_bytes` reports requested handle/bank storage, excluding allocator bookkeeping. The initial model is an empty root tab group. Insert creates a panel at a tab index; `SIZE_MAX` appends. Split wraps a nonempty tab group with a new split and a new tab group containing the supplied panel. Horizontal splits divide width; vertical splits divide height. Ratio refers to the first child's share of the available span after the gap. Move transfers a panel to another group and activates it there. Reorder uses its final index in the original group and preserves its active state. Removing or moving a group's last panel removes that empty leaf and promotes its sibling, collapsing the redundant split. An empty root is retained. Active-panel removal chooses its next neighbor, or previous neighbor at the end. Duplicate keys and invalid destinations reject without changing state. Each node may declare nonnegative minimum dimensions up to 1e9 logical pixels. Child minima combine through the tree with the requested gap. Geometry returns one rectangle per tab group, with active key and panel count. Ratios clamp to child minima when those minima fit; otherwise children compress proportionally to their minimum spans and `fit_minimum` is false. When both minima are zero, the configured ratio applies. Gaps shrink to the available span. Geometry remains within the supplied rectangle even when the minimum requirements cannot be satisfied. NULL output queries the count; insufficient output capacity leaves geometry storage untouched. The model uses fixed arrays and scans for panel/free-slot lookup. Most mutations are O(configured capacity), while linked tab insertion/reorder includes an ordinal walk. Layout computes minima through the bounded tree and may revisit subtrees, taking O(nodes * depth) work. Restore performs bounded scans for allocation and duplicate detection and has quadratic worst-case work in the configured node/panel counts. These deliberately modest caps suit desktop docking rather than huge datasets; the separate virtual-list model handles large row collections. Serialization is deterministic for a given topology, panel order, active selection, ratios, and minima. Format version 1 is an ASCII prefix tree: ```text CUIDOCK 1 T min_width min_height active_ordinal panel_count panel_key... H ratio min_width min_height first_child second_child V ratio min_width min_height first_child second_child ``` Whitespace separates tokens; the writer emits canonical whitespace, decimal numbers with 17 significant digits, and unsigned decimal keys. Split children recursively use the same grammar. The writer normalizes locale decimal punctuation without changing process locale. The parser validates bounded ASCII decimal tokens, translates their radix to the current locale in a bounded local buffer, and delegates conversion directly to `strtod`, without changing process locale. This avoids rounding decimal digit accumulation and power-of-ten multiplication when `long double` has the same precision as `double` (including macOS ARM). Integer overflow, nonfinite values, oversized tokens/input, unsupported versions, duplicate keys, invalid active ordinals, excessive depth/capacity, incomplete trees, embedded NUL, trailing tokens, and nonroot empty groups reject. The existing 17-significant-digit format remains unchanged. Roundtrip tests require equal canonical serialization and exact restored values for ordinary, adjacent representable, and subnormal binary64 values through the platform C library conversion. Serialization first measures required bytes, excluding the terminating NUL. A NULL output queries that length; insufficient capacity or configured byte-budget exhaustion leaves the supplied buffer untouched. Restore parses into the preallocated scratch bank and only swaps the current tree after full validation. Failed restores preserve the entire current state and IDs. Calls belong on the owning UI thread; concurrent mutation and concurrent process-locale changes during serialization are unsupported. Tests cover nested geometry and minimum compression, tab order/active selection, move/remove collapse, stale IDs, stable keys including zero and UINT64_MAX, deterministic roundtrip, transactional parser rejection, huge/deep inputs, explicit capacity rejection, 7000 deterministic mutations with tree/panel invariants, and 2000 malformed random restore inputs under ASan/UBSan. This model does not implement styled Dock widgets, drag/drop targeting, resizing gestures, floating native windows, focus scopes, or panel rendering. It supplies the retained tree, operations, geometry, and persistence required for a later widget layer; it does not claim full Dock component parity. ## Browser demonstration The Dock gallery paints visible panes from the retained tree. Select Panel 1 or Panel 2 to change the active tab, then use Split panel to divide that pane. The demo supports up to eight panes; Reset layout recreates the original two-tab pane. The region count and serialized size update with the same model. This is a composed demonstration of the existing docking model. It does not implement a public styled Dock widget, tab drag-and-drop, divider dragging, floating windows, or persistence across a browser reload. The gallery painter lives in `web/gallery.c`; the retained model's public API remains `cui/cui_dock.h`. --- ## Dock schema accessor failures Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DOCK_SCHEMA_ACCESS.md # Dock schema accessor failures The schema writer checks `cui_dock_node_get`, `cui_dock_panel_at` and `cui_dock_child_at` before using their outputs. These public accessors return false for a stale node ID, an inappropriate node kind or an unavailable index; failure does not initialize the caller's output. The writer now returns `CUI_DOCK_INVALID` when a required read fails instead of consuming an uninitialized key, child or slot size. This also resolves GCC 16's optimized release warning about the panel key without substituting a fictitious zero key or size. Export already traverses into private scratch nodes/sizes and publishes the caller's buffers only after valid traversal. An accessor failure preserves those buffers and the caller's count values. A callback's edits to its live model remain its own edits; export does not roll them back. Callbacks must keep the model alive throughout export, and this change does not provide thread safety or a general snapshot of arbitrary concurrent/reentrant mutations. The regression test uses only valid public operations. A dump callback for panel 1 removes upcoming panel 2, then supplies a valid leaf state. In a tabs-only model the next panel index is unavailable; in a split model removing the second leaf collapses the parent and makes the next child lookup unavailable. Both exports must stop with `CUI_DOCK_INVALID`, invoke no second dump callback, and preserve output bytes and counts. The remaining model is serialized and restored successfully. Existing schema JSON fixtures, round trips, version-1 persistence and model equality tests remain unchanged and run in the same suite. Validation uses GCC 16 release optimization with warnings treated as errors, headless CTest through the repository's invisible-display runner, and the complete Dock test executable under ASAN/UBSAN. Distribution and SDK copies are regenerated by the integrator. --- ## DropdownButton names and focus ordering Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DROPDOWN_BUTTON_METADATA.md # DropdownButton names and focus ordering `cui_dropdown_button_metadata.h` adds independently optional semantic names and signed tab ordering for the action and menu trigger. Existing options/state layouts and legacy entry points stay unchanged. NULL or zero metadata uses the original path; paint remains independent through the optional `cui_dropdown_button_styles` argument. ```c #include "cui/cui_dropdown_button_metadata.h" void submit_dropdown(cui_context *ui, const cui_theme *theme, const cui_menu_entry *items, size_t count, cui_menu_tree_state *state, cui_id *command) { const cui_dropdown_button_metadata metadata = { .action = {.custom_name = true, .name = {"Save document", 13}, .custom_tab_index = true, .tab_index = -2}, .trigger = {.custom_name = true, .name = {"More document actions", 21}, .custom_tab_index = true, .tab_index = -1}, }; (void)cui_dropdown_button_with_metadata_ex( ui, 100, 101, 102, theme, cui_string("Save"), cui_string("More"), items, count, command, state, (cui_dropdown_button_options){.width = 180}, NULL, &metadata); } ``` Descriptors copy at entry. Custom name bytes are borrowed and immutable through submission; Core copies semantic name bytes into frame storage. Names need valid UTF-8 with no embedded NUL. An explicit empty custom name is supported (NULL plus zero length). Invalid visible custom names reject before input consumption, state changes, callbacks or painting. Hidden halves and unmasked fields are ignored. `skip_tab` affects keyboard traversal independently of signed native-int ordering; pointer and accessibility activation remain governed by the existing enabled state. Dynamic changes use existing previous-frame routing and focus rules. Metadata is registered before existing synchronous action/menu callbacks, which retain their original mutation and replacement behavior. No deferred callbacks or new dispatch mechanism are introduced. Visible labels/custom children remain unchanged. `toggle_semantics` applies the existing Button checked/value convention to the action, independently of selected paint. The trigger finishes unchecked (the existing menu callback still sees its transient open/checked state); expanded, controls and busy metadata continue to work. This does **not** provide optional toggled presence or a pressed-button accessibility adapter: that frozen-source contract still requires a separate Core/adapter change. No binding facade is shipped. All consumers must use matching revision headers and library. The gallery DropdownButton story offers opt-in French or explicit-empty semantic names, signed action/menu ordering, independent skip-tab and checked/value selectors. Visible export labels stay unchanged. Disabled/loading and hidden-half controls keep their original behavior. Changing stories resets the metadata selectors. The copied C snippet uses the real sibling API; the demo does not expose aria-pressed presence. The browser host follows existing Core tab eligibility and group-prefix ordering when deciding whether Tab leaves the canvas. --- ## DropdownButton paint refinements Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DROPDOWN_BUTTON_STYLES.md # DropdownButton paint refinements Include `cui_dropdown_button_styles.h` with matching rebuilt library sources. The independent header leaves the legacy options/state layout unchanged. NULL or an all-zero descriptor calls the existing paint path. This slice adds paint, not metadata forwarding, arbitrary layout, or a binding facade. ```c #include "cui/cui_dropdown_button_styles.h" static void action_paint(void *user, const cui_button_style_info *info, const cui_button_style_paint *current, cui_button_paint_patch *patch) { (void)user; (void)info; (void)current; patch->fields = CUI_BUTTON_PAINT_FOREGROUND; patch->paint.foreground = (cui_color){250, 240, 210, 255}; } void draw_commands(cui_context *ui, const cui_theme *theme, cui_menu_tree_state *menu, cui_id *command) { static const cui_menu_entry entries[] = { {.id = 104, .label = {"Export", 6}, .kind = CUI_MENU_ACTION}}; const cui_dropdown_button_styles paint = { .paint_policy = CUI_DROPDOWN_BUTTON_PAINT_BUTTON, .action = {.instance = action_paint}}; (void)cui_dropdown_button_styled_ex( ui, 100, 101, 102, theme, cui_string("Save"), cui_string("More commands"), entries, 1, command, menu, (cui_dropdown_button_options){.width = 120, .variant = CUI_DROPDOWN_BUTTON_PRIMARY}, &paint); } ``` Initialize the caller-owned menu once with `cui_menu_tree_init(menu, 103)`. Names, menu entries, callbacks and userdata follow the existing submission and menu ownership rules. Style descriptors are copied before reduction; callback arguments are borrowed for the synchronous call. Callbacks must be pure: no CUI calls, input consumption, owner/options/style mutation or reentry. Only the output patch changes the submitted paint. The legacy body still runs once, after the same Base/event reduction; this API does not invoke Button reduction. Each visible half gets an independent Button-style instance callback, then its eligible pointer/selected/disabled callback. The instance patch is captured once and replayed after selected and disabled, including an explicit transparent color or zero radius/opacity. Loading applies its .8 opacity after replay; focus is last. Hidden halves have no callbacks. Invalid callback patches are discarded atomically; accepted input remains accepted. Geometry, clip, and border width are inspectable but cannot be patched. To replace joined corners use the CORNERS mask, since RADIUS alone retains the existing custom corner record. The BUTTON policy uses existing CUI palette tokens with frozen Component state ordering. Selected/open/loading/disabled suppress pointer refinements; only the trigger treats an open menu as selected. Ghost action held-group backgrounds use half hover alpha (dark: quarter accent alpha). Dark ghost hover uses half accent alpha. Outlined state wins disabled paint, including transparent special variants. Disabled filled intents use their normal token for both background and border; Secondary retains alpha (source opacity clamps its 1.5 multiplier to 1). Custom transparent mixes preserve RGB and scale alpha, with CUI's existing byte truncation. Source theme token values and sub-byte color precision differ. LEGACY policy retains old palette/state rules with optional refinements. A nonzero descriptor with no callbacks may still request container paint. Container patches accept the Button mask vocabulary except FOREGROUND: there is no implicit text cascade. Invalid policy/container patches reject before state or input reduction. Unknown masks and nonfinite/negative radius/corners or opacity outside 0..1 are invalid. An unmasked member is ignored. Custom shadows require BUTTON, CUSTOM, `custom_shadow=true`, and `host_shadows_enabled=true`. Both gates default false; they do not imply a global theme setting. Enabled halves receive `CUI_SHADOW_XS` with resolved corners; disabled suppresses it, loading retains it. The host renderer must support CUI shadow commands. Focus paint uses focus-visible and `theme.hide_focus_ring` in BUTTON; LEGACY preserves the old focus rule. No full DropdownButton parity is claimed: metadata/name/tab/toggle forwarding remains a separate slice. Canonical builds register the styles unit test, optional compiled guide and C++ declaration check. The portable WASI runner exposes `dropdown_button_styles` and `dropdown_button_styles_{all,legacy,styles}_distribution` suites. Standalone users may define `CUI_DROPDOWN_BUTTON_STYLES_IMPLEMENTATION` before including `dist/cui_dropdown_button_styles.h`; it delegates to Choice once. The legacy `CUI_CHOICE_IMPLEMENTATION` entry also defines these additive functions, and `CUI_IMPLEMENTATION_ALL` includes their implementation. Include the explicit styles header for declarations. Link the remaining required CUI modules as usual; these entry points do not create a second Button reducer. Source SDKs include the header and implementation. Python, JS/TS, Go and Rust builders do not expose this style facade or its borrowed callbacks. --- ## Editor Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/EDITOR.md # Editor `cui_editor` is a retained multiline editing model with an immediate styled view. Create a multiline `cui_edit`, then initialize `cui_editor_state` with that borrowed model and a caller-owned `cui_textarea_line` workspace. Both must outlive the state. The retained editor model and search add no allocations; edit history allocation remains controlled by `cui_edit_config`. Fold chevrons use the existing context-owned SVG icon cache, which prepares masks on demand. ```c cui_editor_state state; cui_textarea_line rows[1024]; cui_editor_state_init(&state, edit, rows, 1024); cui_editor_options options = cui_editor_default(); options.textarea.width = 600; options.textarea.height = 400; cui_editor(ui, id, theme, cui_string("Source"), &state, options); ``` Defaults enable line numbers, disable wrapping, and show twelve rows. Textarea options control wrapping, readonly/disabled behavior, size, indentation, and clipboard integration. The view handles caret blinking, selection, pointer hit testing/dragging, keyboard navigation, scrolling, undo/redo, and Tab indentation through the existing textarea reducer. Logical line numbers appear once for wrapped lines. Gutter scrolling follows content vertically and stays fixed horizontally. Accessibility exposes the underlying multiline textbox. `cui_base_editor` provides the drawing-free reducer with explicit metrics and caller-managed viewport geometry; the line-number and syntax options apply only to styled rendering. `cui_editor_find` performs case-sensitive literal UTF-8 search and selects the next or previous match, optionally wrapping. No query is retained. The next draw reveals the selection using textarea caret scrolling. Missing matches and invalid queries preserve selection and text; errors use existing edit result codes. Selection offsets and syntax token boundaries are UTF-8 byte offsets. The optional `highlight` callback receives the borrowed language identifier, whole document, and a visible token range beginning. It returns the next token's exclusive end and color. It may inspect surrounding document text to support multiline lexical context. Ends must advance, stay within the current visual line, and fall on UTF-8 boundaries; invalid ends render the rest of that row in the ordinary foreground color. The callback runs only for visible rows and must not mutate the model. Language selection itself does not invoke a parser: the host supplies actual language recognition and syntax classification. Token segments use measured prefix positions; splitting a shaping run can alter ligatures/contextual shaping. Disabled text may still receive host syntax colors. Verified scope includes search direction/wrap, editing selected matches, undo, readonly input, line-number output, colored syntax text, invalid-hook fallback, invalid dimensions, and caret reveal. Frozen upstream Editor has much broader display maps, diagnostics, completion, language services, and search features; those are not implemented here. This is a usable adapter, not full Editor parity. Ordinary keyboard navigation and erasure use Unicode extended grapheme clusters; visual bidirectional navigation is unsupported. Editor defaults select the portable monospace style. Set `options.textarea.text_style` to choose the registered font family, weight, italic style, and monospace flag; an all-zero style explicitly selects the ordinary default font. Measurement, syntax tokens, gutter numbers, selection, caret, and pointer geometry all use this complete style. Font size and line height continue to follow textarea size/design metrics. Fonts and shaping follow the configured core/text backend. Capacity errors require a larger visual-row workspace; document mutation is exclusively through the attached edit model. The optional `cui_editor_find_bar` renders a single-line query input, match count, Previous/Next actions, and Close. Initialize `cui_editor_search_state` with a borrowed **single-line** edit model. Call the bar before the editor every frame, including when closed, passing the editor's ID. Ctrl/Meta-F on that editor opens and focuses the query, selecting its current contents. Enter navigates forward, Shift-Enter backward, and Escape closes and returns focus to the editor. Buttons expose ordinary button semantics; no-match navigation buttons are disabled. A host may also set `search.open` directly. The query remains caller-owned and no buffer or match array is allocated. Match counts use nonoverlapping literal matches; query edits update counts immediately, while navigation explicitly selects a match. Search bars use the existing Input/Button styled components, so editor amalgamations require the basic components module as well as textarea. This panel adds no replace mode, regex, case-folding, or all-match decorations. Attach sorted caller-owned `cui_editor_fold` ranges with `cui_editor_set_folds`. Line indices are zero-based, starts must be unique, and each range needs at least one interior line within the document. Nested or overlapping collapsed ranges hide the union of their interiors. This follows the frozen upstream FoldMap boundary rule: opening **and closing** logical lines stay visible. Every wrapped row of an interior line is hidden. Ranges are validated on attachment and layout; malformed caller mutations reject layout rather than reading beyond bounds. `cui_editor_set_folded` changes presentation without modifying text/history. Collapsing while either selection endpoint is inside moves both endpoints to the opening line's end. A selection spanning a whole fold is preserved, and copy/delete still operate on the original full document. Programmatic selection, find results, or horizontal navigation entering hidden lines automatically expand containing folds on layout. Vertical navigation and pointer hit testing use visible rows and skip folded interiors. The line-number gutter exposes Expand/Collapse buttons with expanded semantics. Activation requests redraw; its updated projection is rendered on the next frame. Disable line numbers to use folding through the model API without gutter controls. Any document revision detaches all ranges, including after undo/redo; the host must refresh and reattach candidates against current text. This deliberately avoids applying stale line indices after arbitrary edits. It differs from upstream's incremental parser/candidate remapping. No fold discovery, automatic indent/syntax folding, fold-all command, hidden-text placeholder, or parser-owned persistent range tracking is supplied. Array memory stays caller-owned and must remain alive and unmodified except for `collapsed` until detached. Styled syntax callbacks receive original byte ranges of visible document rows. Host completions ---------------- `cui_editor_show_completions` borrows immutable UTF-8 label/detail/insertion items and one validated document byte replacement range. It selects the first item and opens the popup; zero items cancel it. The host owns fetching, language analysis, ranking, and filtering. No provider or LSP connection runs implicitly. The styled popup is shown while the editor owns focus. Up/Down cycle suggestions, primary Enter accepts, and Escape cancels. Tab retains the existing indentation behavior; it does not accept a suggestion. Pointer activation also accepts. Readonly/disabled views suppress the popup and acceptance without changing document text. The popup displays at most eight suggestions by default, keeping the selected one in view; `completion_rows` allows up to 32 and `completion_width` defaults to 320 pixels. It exposes a listbox with selected option semantics and retains editor focus during pointer selection. Labels and details use the complete configured code font. Positioning uses the last completed viewport layout; opening before the first layout requests another frame to obtain an anchor. The popup prefers below the caret and flips above when it fits inside the editor viewport. Width, visible-row count, and position are bounded to that viewport; a very small viewport without room for one item suppresses popup drawing while keyboard acceptance remains available. If neither side fits, the popup may cover the caret while staying inside the viewport. Global screen-edge placement outside the editor is not supplied. Acceptance uses `cui_edit_replace_range` as one atomic history step. Undo restores the original selection as well as text. Capacity or validation failure preserves text/selection/history and leaves the current menu open. Document revisions cancel stale suggestions; normal editing, cursor movement, focus moving to another control, or an outside pointer press also dismisses them. A host may refresh suggestions after those edits. Earlier queued text/navigation events run before any later acceptance attempt, so an old proposal cannot replace a newly typed prefix in that queue. Borrowed items must remain alive and unchanged until cancellation or acceptance; `cui_editor_cancel_completion` releases the references. A programmatic accept operates on the attached edit model independently of styled readonly settings, just like direct edit-model mutations. Verified completion scope includes UTF-8 range/item rejection, undo selection, capacity failure, stale revisions, bounded popup windows, code-style propagation, Up/Down wrap, keyboard and actual pointer acceptance, Escape, readonly behavior, invalid sizing, and queued typing followed by Enter. The frozen reference also supports asynchronous provider resolution, richer completion documentation, snippets, additional edits, and inline suggestions; these are not implemented. Unicode grapheme editing ----------------------- Ordinary Left/Right (including Shift selection), Backspace, and Delete now follow Unicode 17.0.0 default extended grapheme clusters (UAX #29 revision 47). This matches the Unicode version used by the frozen upstream reference's pinned `unicode-segmentation` 1.13.3. Combining marks, emoji modifiers/ZWJ sequences, regional-indicator flags, Hangul, and Indic conjuncts remain whole. Textarea wrap boundaries, pointer hit testing, and preferred-x visual row movement use the same clusters. A cluster wider than the viewport occupies one overflowing row and is clipped by the existing viewport; it is never split into scalar rows. Offsets remain UTF-8 bytes. Explicit `CUI_EDIT_PREVIOUS`/`NEXT`, `cui_edit_select`, `cui_edit_replace_range`, `cui_edit_backspace`/`delete`, and direct logical vertical motions retain their scalar contracts. Hosts can opt into `CUI_EDIT_GRAPHEME_PREVIOUS`/`NEXT` and `cui_edit_backspace_grapheme`/ `cui_edit_delete_grapheme`. Grapheme erasure expands partial cluster selections outward; a collapsed scalar cursor inside a cluster removes that whole cluster. Undo restores the original byte selection. Search/completion replacement ranges and host syntax token ranges remain scalar byte boundaries, so host-controlled operations can intentionally target part of a cluster. `cui_grapheme_next`/`previous`/`boundary` validate complete length-bounded UTF-8, including embedded NUL (which the edit buffer itself continues to reject). Invalid UTF-8, continuation-byte offsets, and out-of-bounds offsets are rejected. They allocate nothing and scan the supplied text. The forward iterator validates once and traverses clusters in linear total time; its borrowed text must remain unchanged. Textarea seeds this iterator at established row boundaries to avoid rescanning the document for every wrap measurement. Pinned property files, conformance data, SHA-256 checksums, and Unicode License V3 are in `third_party/unicode/17.0.0`. Run `python3 scripts/generate_grapheme.py --check` to verify generated properties and embedded test fixtures. Headless tests cover all 766 official Unicode conformance cases, iterator suffixes, keyboard selection/erasure/undo, scalar compatibility, invalid inputs, and whole-cluster wrapping/hit geometry. This does not add bidirectional visual navigation, language services, or font shaping; those remain separate host/backend responsibilities. Vertical selection at document edges ------------------------------------ Shift+Up on the first visible row extends the cursor to byte 0; Shift+Down on the last visible row extends it to document end. The selection anchor stays fixed. Plain Up/Down retain the preferred horizontal position at those edges. This follows frozen Input `vertical_selection_target`, including soft-wrapped rows and the visible row projection after folding. Readonly text remains selectable; disabled or composition-owned key events remain ignored. Movement changes selection only, without adding an undo step or changing the document revision. Shift+PageUp/PageDown retain their existing CUI row-clamping behavior. Plain Up/Down collapse of an existing selection now uses the frozen directional effective-point behavior described below. Explicit legacy `WORD_PREVIOUS`/`NEXT` motions retain their heuristic contracts; modified keyboard word behavior is described below. Unicode word movement and deletion ---------------------------------- Ctrl/Alt+Left targets the start of the last non-whitespace Unicode word segment in the text before the cursor. Ctrl/Alt+Right targets the end of the first non-whitespace segment after the cursor. Shift extends the selection with the same targets. This follows frozen Input `previous_start_of_word_at` and `next_end_of_word_at`: it uses default Unicode word segments, including punctuation, rather than moving between identifier starts. For `one, two`, Right visits offsets 3, 4, and 9; Left visits 6, 3, and 0. Default boundaries keep apostrophes in `can't`, numeric separators in `3.14`, and underscores in `foo_bar`; ideographs remain separate segments without dictionary segmentation. Unicode White_Space segments are skipped. Targets are clipped outward to extended-grapheme boundaries for the existing whole-cluster keyboard contract. Ctrl/Alt+Backspace and Ctrl/Alt+Delete erase to those targets as one history step. A nonempty selection takes precedence and uses whole-grapheme selection erasure. Undo restores the original byte selection. Readonly views permit navigation while rejecting erasure; disabled and composition-owned events are unchanged. These are portable modifier bindings; hosts may translate platform conventions before routing events. OS-specific macOS Command line-erasure bindings are not introduced by this portable model. Hosts can call appended `CUI_EDIT_UNICODE_WORD_PREVIOUS`/`NEXT` motions and `cui_edit_backspace_word`/`delete_word`. Explicit legacy `CUI_EDIT_WORD_PREVIOUS`/ `NEXT` continue to use their original identifier heuristic and next-start behavior. `cui_word_next`/`previous`/`boundary` expose the Unicode 17.0.0 default boundaries with the same complete UTF-8 validation and byte-offset contract as the grapheme queries. They scan caller-supplied text without allocation; the edit model continues to borrow its NUL-terminated buffer. This does not add code Editor inline-token integration, multi-cursor editing, or dictionary segmentation; ordinary atomic inline content is described below. Pinned `WordBreakProperty.txt`, `WordBreakTest.txt`, and `PropList.txt` supply the word properties, 1,944 official conformance cases, and Unicode White_Space. `python3 scripts/generate_word.py --check` verifies their hashes and generated inline properties/test fixture. Headless tests additionally cover both modifiers, Shift selection, punctuation/ideographs, Hebrew quotes, numeric separators, Katakana, identifiers, emoji/Indic/combining clusters, NBSP, partial-cluster selection, atomic erasure/undo, scalar compatibility, readonly view behavior, and Editor completion dismissal after modified navigation/deletion. Plain vertical selection collapse --------------------------------- Plain Up/Down from a nonempty selection derives a directional effective point before moving one visible row, rather than moving from whichever endpoint is the active cursor. It recomputes preferred x at that point and collapses the selection at the target. Shift movement continues from the active cursor with the original anchor; PageUp/PageDown also start from the active cursor, matching the frozen reference's non-collapsing page calculation. The calculation follows frozen Input `move_vertical` literally: Up calls `previous_boundary(start.saturating_sub(1))`, whose helper subtracts another byte before left clipping. CUI therefore floors `max(start - 2, 0)` to an extended-grapheme boundary. Down calls `next_boundary(end - 1)`, which right-clips the selection end. A point inside a folded gap clamps backward to the preceding visible row end, or forward to the next visible row start. Down retains upstream soft-wrap affinity only if the effective point equals the active cursor; otherwise it starts on the downstream row at that shared byte offset. These details matter at logical line starts, wrap boundaries, and folded gaps. Tests cover both selection orientations, fresh/preserved preferred x, exact line-start math, wrapped geometry, active-endpoint affinity, folded gap clamping, readonly/disabled views, page behavior, whole-grapheme targets, and unchanged document revision/undo history. This implements the retained single-selection behavior; frozen multi-cursor merging remains outside this adapter's scope. Atomic inline content belongs to ordinary Input/Textarea, as described below. Atomic inline content for ordinary Textarea ------------------------------------------- The frozen `inline_tokens.rs` exports `InlineToken`, `InputContent`, and token replacement APIs only for ordinary Input and Textarea. Its `check_token_mode` and `install_tokens` explicitly exclude code Editor mode. CUI therefore rejects annotated models in Editor initialization and base/styled Editor preflight; this feature belongs to `cui_edit` and the ordinary Textarea adapter. `cui_edit_content` borrows the document and a sorted caller-owned collection of `cui_edit_token_span`. Each span carries an ID, source text, and display-label metadata. IDs may repeat; they must contain a non-whitespace scalar. Source text and label are nonempty NUL-free UTF-8 without control characters or U+2028/U+2029. Ranges must be nonempty, nonoverlapping, on grapheme boundaries, and exactly match the token's source text. `cui_edit_content_valid` performs validation with one forward grapheme traversal. No host callback runs during validation or normalization, and no metadata allocation is hidden in these APIs. `cui_edit_set_content` replaces the text as one atomic edit/history step, then adopts the borrowed spans. Rejection preserves text, selection, history, and the old attachment. When replacing annotated content, token strings must not alias mutable edit storage; that alias is rejected before mutation. Use `cui_edit_set_tokens` to attach annotations to unchanged text while preserving selection/history. `cui_edit_get_content` returns a borrowed current snapshot: the document view lasts until the next mutation/destruction, while arrays and all token strings must remain immutable and alive until detachment. Call `cui_edit_set_tokens(edit, NULL, 0)` before releasing their storage. Pure `cui_edit_token_boundary` snaps strict interiors to the token start or end according to the requested bias. `cui_edit_normalize_token_range` expands nonempty ranges outward and moves collapsed insertion points to token end; output is untouched on rejection. Attached spans protect insertion, deletion, and range replacement using this normalization. Ctrl/Alt word deletion remains one undo step even when its initial Unicode target is inside a token. Keyboard motions skip token interiors, and Textarea hit testing/view selections use atomic boundaries. Raw source text remains visible; wrapping keeps each atom whole, with an oversized atom on one clipped overflowing row. Display labels are metadata for the host, not automatically painted chips. Explicit scalar `cui_edit_select`, PREVIOUS/NEXT and legacy WORD motions remain available. `cui_edit_select_atomic` expands selections outward and snaps a collapsed view cursor left. Attached atoms protect subsequent edits even when a host selected a scalar interior. Whole-document indent is unsupported while annotations are attached, so Textarea releases Tab ownership for those models. Any text revision, including undo/redo, detaches annotations. Hosts must refresh and reattach them; undo restores document text and the original byte selection, but does not restore token metadata. This scoped borrowed-content model does not implement owned content snapshots, incremental span/history remapping, chip/label rendering, masked/secret Input mode integration, grammar registries, or language services. Ordinary Input adapter wiring outside this module must enforce its own supported-mode rules. Headless tests cover source validation, repeated IDs, adjacency/overlap, grapheme/text mismatch, controls/Unicode whitespace, biased boundaries, normalization, scalar compatibility, atomic modifier deletion/undo, collapsed insertion, invalid/capacity/alias rejection before mutation, invalid borrowed range preflight, lifetime detachment, readonly/pointer/wrap geometry, Tab semantics, and explicit code Editor rejection. The ordinary edit model also provides `cui_edit_replace_with_token` and `cui_edit_replace_range_with_token`. These validate the original grapheme endpoints, expand existing atoms, remove intersected spans, and shift surviving spans. The host supplies a separate output span array; success attaches that borrowed array. All strings and output storage must remain alive and immutable until detachment. Rejected operations preserve text, selection, history, output spans, and count. Candidate insertion and surviving-span boundaries must remain grapheme boundaries. Exact token/range replacements preserve selection and document revision. Undo still restores document snapshots only and detaches annotations; token metadata has no history payload. This is ordinary Input/Textarea functionality, not CodeEditor token support. Masked/secret Input modes themselves are not currently implemented in CUI. Literal replacement is available through `cui_editor_replace_current` (the selection must exactly match the query) and `cui_editor_replace_all`. Replace-all uses a caller-provided byte scratch buffer, scans nonoverlapping matches, and commits one document replacement for one-step Undo. Its count is untouched on failure; scratch contents are unspecified. Successful replace-all resets selection and scroll to the start. These programmatic operations ignore view readonly and disabled options; host UI must enforce its editing policy. These direct APIs remain case-sensitive; retained ASCII-insensitive matching and current-index replacement are provided by the separate matcher APIs below. `cui_editor_matcher` retains a borrowed immutable query and caller-owned match ranges. Set-query activates it; close retains query/ranges but deactivates it. Synchronization rebuilds after document revisions and resets current index to zero. Next increments before selecting and wraps; Previous decrements and wraps. ASCII case-insensitive matching folds only A-Z, preserving distinct non-ASCII case forms, matching the frozen Aho-Corasick configuration. Queries must not borrow mutable edit storage. Capacity rejection preserves session/range storage. Retained current replacement preflights candidate match capacity, commits one edit, and keeps the logical index (last replacement wraps to zero). No hidden allocation or callback is involved. The existing literal APIs and find-bar retain their prior contracts. The find-bar can opt into a built-in replacement row with `cui_editor_search_enable_replace`, borrowing a retained matcher, distinct single-line replacement edit model, and byte scratch buffer. Ctrl-H or Meta-Shift-F opens replacement mode; Enter in the replacement field replaces the current retained match. Semantic buttons provide case matching, replacement mode, Replace, and Replace all; Escape from either field closes and returns editor focus. `replace_disabled` lets the host enforce readonly policy while keeping find navigation available. Replace-all respects ASCII-insensitive matching and remains one Undo step. Existing find-only callers retain their original behavior. Search matches are retained for navigation/status. Attach the matcher through the editor options `search` field to paint visible active and non-current matches. Retained search activation (`cui_editor_search_open`) seeds a nonempty document selection into the query model, without changing document selection or history. Only a changed query anchors its current index at the first visible projected row; reopening an unchanged query preserves the current index. Every successful opening increments `activation_revision`; the built-in bar reselects/refocuses its query. Single-line query restrictions and capacity rejection are transactional. The projected row anchor respects folding. Existing no-matcher find-only callers retain their original query-retention behavior. The editor options `search` pointer borrows the matcher. Active match rectangles use measured prefixes with the complete code font style, including family. Hidden fold interiors do not paint matches; viewport clipping applies to long lines. Current matches use the selection color; other matches use a subdued selection color. Hosts may supply exact colors with `custom_search_colors`. Document selection paints after search backgrounds, and syntax callbacks remain read-only and paint text afterward. Closing the matcher suppresses all search highlights. Revision synchronization uses caller range capacity; capacity errors are surfaced rather than drawing stale ranges. Match arrays and public matcher fields must remain unchanged by callers while attached (except through matcher APIs). The edit model has an opt-in bounded multi-selection foundation: `cui_edit_attach_selections` borrows up to 64 live selections and one caller-owned selection snapshot per existing document-history slot. It neither allocates new storage nor changes document history sizing. `cui_edit_select_many` validates extended-grapheme endpoints, merges overlapping/adjacent ranges, and preserves the active selection's ID and orientation. `cui_edit_replace_selections` repeats one text at every range in one transaction; before/after cursor collections round-trip through Undo/Redo, including document-history eviction. Capacity/validation errors preserve document, selections, and paired history. Candidate cursor endpoints must remain grapheme boundaries. Inline-token annotations are excluded while this storage is attached. Reattaching clears cursor metadata for older document entries, which restore their legacy primary selection; detaching preserves text/history. Legacy single-selection APIs collapse extra cursors. After attaching model storage, call `cui_editor_multicursor_init` with a separate caller-owned array of `cui_editor_cursor_anchor` entries covering the model's selection capacity. Keep all model/history/anchor/visual-row arrays disjoint, alive, and unchanged by the host while the editor is submitted. The adapter preflights this resource before consuming events; no model storage means the existing single-cursor path. The Editor accepts the frozen platform add-cursor combinations: Ctrl+Alt or Meta+Alt Up/Down, and Shift+Alt Up/Down. Each existing cursor contributes a target on the adjacent visible row; duplicate targets and targets inside selected ranges are skipped. Alt-click adds a measured cursor while preserving the active cursor; Escape keeps only the active range. Each cursor has a measured visual column, including short rows, soft-wrap affinity, and folded-row projection. All carets and selections paint using the complete configured text style. A hidden selection endpoint reveals its fold before layout. Style, font size, and document changes reset preferred columns. Call `cui_text_metrics_changed` after changing a host measurement provider to invalidate anchors and measured rows. Preferred columns are view metadata and do not round-trip through Undo. Typing and Enter repeat text at every range in one document/history transaction. Backspace/Delete use extended grapheme boundaries; Ctrl/Meta/Alt deletion and horizontal movement use Unicode word targets. Arrow, visual Home/End, Page, and Shift selection motion apply to each cursor and merge overlapping/adjacent ranges while preserving the active ID/orientation. Document Home/End and Ctrl Up/Down retain the source behavior of collapsing extra cursors. Readonly permits cursor selection and navigation while blocking edits. Pure `cui_edit_selection_motion` computes a single target without mutation; `cui_edit_move_selections`, `cui_edit_erase_selections`, and `cui_edit_add_cursors` provide bounded atomic model operations. Add-cursor preserves an endpoint cursor next to a selected range; replacement coalesces coincident resulting cursors. Errors preserve the document, collection, and paired history. Read-only Textarea row helpers expose measured positions without modifying selection or pointer state. Tab and Shift-Tab now use source-backed multicursor indentation. A noncollapsed range anywhere in the collection makes the operation a block action for every cursor: all touched LF rows, including a range's endpoint row, are processed once. Collapsed inline Tab inserts exactly the configured unit at each cursor (not a visual tab-stop calculation). Outdent removes only an exact leading unit from each touched row, once even when cursors share that row. Partial/mixed indentation is left unchanged. Hard tabs use one tab byte; soft tabs use `tab_size` spaces. `cui_edit_indent_selections` also exposes explicit block mode. Every endpoint maps through every earlier edit, including edits belonging to other cursors; points inside removed indentation clamp to the remaining line start. IDs, orientations, and collection order survive. The operation records one Undo transaction. Ctrl/Meta bracket block actions dispatch through `cui_key_character`; the host's portable key mapping must supply `[` or `]`. Hosts may also invoke explicit block mode directly. These actions use the attached multicursor adapter. Multicursor clipboard commands use the existing synchronous `textarea.clipboard` platform hooks. `cui_edit_paste_selections` treats empty text as no operation. It normalizes overlapping ranges, then splits on LF, retaining a trailing empty line. An equal number of lines and selections distributes one line per range in document order; otherwise the whole text repeats at every range. CR bytes are retained. One Undo restores the prior collection and text. `cui_edit_copy_selections` joins nonempty ranges in document order with LF, leaving collapsed cursors out. It writes a NUL-terminated caller buffer and returned slice only after capacity/alias preflight; failure leaves both outputs unchanged. Set `clipboard_scratch`/`clipboard_capacity` on Editor options for Copy/Cut. This borrowed buffer must fit joined text plus NUL and stay disjoint from document, model/history, visual rows, and cursor anchors. Paste uses model scratch and does not require this buffer. Cut preflights the document operation before calling the host write; a failed write preserves document and collection. Readonly Cut copies without deletion; readonly Paste does not call the read callback. Callbacks are synchronous, must not reenter UI/Editor or mutate the model/resources, and returned paste bytes must stay immutable through the operation. The adapter checks the revision and selection collection after a callback and rejects a stale paste/cut if the host changed them; host mutations are not rolled back. The same-editor base reducer rejects reentrant submission while a clipboard callback is active. `cui_edit_can_replace_selections` provides a read-only model preflight; internal scratch contents may change. No async clipboard permission/request API is claimed. With attached selections, Alt + primary click adds a caret. Hold and move the pointer to select a rectangular block; Shift+Alt + primary drag replaces the collection with a block immediately. Ctrl+Alt works the same as Shift+Alt on Linux hosts. The start row remains active, and each pointer update allocates fresh IDs for the visible rows between the endpoints. Release or Cancel stops the drag; moving near the viewport edge scrolls and extends it. Readonly still allows block selection. The caller owns the model selection/history arrays, Editor cursor anchors, and visual row array for the full document lifetime. The row array needs enough entries for every displayed row, including wrapped rows. An undersized row array reports `CUI_TEXTAREA_CAPACITY`; an undersized selection array reports `CUI_EDIT_CAPACITY` without changing the collection or ID counter. Hosts can also call `cui_editor_select_rectangle` after a current-revision Editor layout. Each `cui_editor_column_point` contains a byte offset on a visible row and a count of virtual space-width columns beyond that row's end. The method clips columns to the end of shorter rows; virtual columns do not insert padding into the document. Soft-wrapped rows and collapsed folds follow display order, and hidden fold interiors cannot be endpoints. Grapheme endpoints clip left, an intentional CUI extension to the upstream byte-column behavior. Selection changes create no document Undo step; a later edit restores the block through Undo. Block geometry depends on the current text measurement provider; call `cui_text_metrics_changed` after changing that provider. Textarea and Editor accept documents beyond 64 KiB when the caller supplies enough visual rows. A headless test exercises selection, scrolling, and editing near the end of 200,000 LF rows. Layout stores the complete display-row set and reuses measured rows while document revision, style, width, wrap mode, and font metrics remain unchanged. The Edit model reports the earliest changed byte for each revision. A single ordinary edit retains preceding hard lines and rebuilds the affected logical line and suffix; wrapped lines rebuild from their logical-line start. Caret and dirty-row lookup use binary search. Undo/Redo, indentation, skipped revisions, attached folds, and inline tokens conservatively rebuild the full layout. Edits at the document start rebuild all rows; the caller still owns storage for all visual rows. The reproducible headless benchmark is `tests/bench_editor_200k.c`. Build the portable library with CMake at `-O2`, then compile the benchmark with `cc -std=c11 -O2 -UNDEBUG -Iinclude tests/bench_editor_200k.c build/libcui.a build/libcui_software.a -lm -o bench_editor_200k`. It prints process CPU time, text measurement calls, and draw commands for cold, unchanged, tail-caret, tail insert, tail removal, and middle insert frames. On an Intel Core Ultra 5 235U, Linux x86_64, GCC 16.2.1, headless software command generation, one release run measured 18.6 ms cold/400,003 measurements, 0.024 ms unchanged/0, 0.022 ms tail caret/2, 0.022 ms tail insert/9, 0.463 ms tail removal/5, and 6.82 ms middle insert/200,007. Tail removal still copies document/history bytes in the Edit model. The caller-owned row array occupied 6,400,032 bytes, plus 400,000 document bytes. These are single-run CPU measurements; host font providers, document content, and load change the results. No 60 Hz guarantee follows from this headless workload. The actual Editor workload (gutter, highlight callback, 80-byte lines, keyboard input, wheel scrolling and pointer dispatch) and raw 2K/20K/200K samples are in [the Editor operations benchmark](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/benchmarks/EDITOR_OPERATIONS.md). Model ASCII grapheme navigation reuses validated-buffer local helpers, including CR/LF handling; non-ASCII context retains the full Unicode scan. Public grapheme utilities still validate the whole input. Document editing/history and affected layout rebuilding can remain linear; these measurements do not establish Unicode navigation or renderer performance guarantees. Consecutive interactive text or same-direction grapheme deletion batches with unchanged cursor collection coalesce by intent into one Undo step, up to 1000 cursor changes. Newlines, navigation, selection changes, folds, clipboard actions, word deletion, and atomic edits break the group; paste and completion remain individual Undo steps. This slice does not implement multiple IME composition ranges. Optional caller-owned `cui_edit_column_anchor` storage and one `cui_edit_column_snapshot` per document-history slot retain each cursor's preferred pixel x, logical grapheme column, and soft-wrap affinity across Undo/Redo. Attach it with `cui_edit_attach_columns` after selection storage; the Editor uses it automatically for multi-cursor vertical navigation. It recomputes x from the logical column when text style or font size changes. Without this optional storage, preferred columns live only in the view. Inline-token annotations are excluded from these attached multicursor models and CodeEditor, so token-aware clipboard/indent remapping is not claimed. Search mode buttons show selected presentation as well as their semantic checked state. --- ## Styling named elements with shadows Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/ELEMENT_SHADOWS.md # Styling named elements with shadows For a custom open box, continue using `cui_set_box_shadows` or `cui_set_shadow_preset`. To style a box that a composition already closed, call `cui_element_set_box_shadows` or `cui_element_set_shadow_preset` after submission and before `cui_end_frame`. These APIs address a named paint box, including a portal, in the current frame. They do not imply that every component's public ID is its rectangular paint root or expose private anonymous subparts. ```c cui_begin_box(ui, card_id, (cui_box){.width = 160, .padding = 16, .radius = 8, .background = theme->background}); /* Submit application content here. */ cui_end_box(ui); bool styled = cui_element_set_shadow_preset( ui, card_id, CUI_SHADOW_MD, (cui_corner_radii){8, 8, 8, 8}); ``` A successful call copies at most eight total DROP/INSET layers and replaces the entire list. Last successful assignment wins. Zero count or `CUI_SHADOW_NONE` clears both kinds without removing underlay, outline or other custom paint. Caller stack layer storage can be reused immediately. No style persists into a later frame. Existing components retain their default appearance unless styled. A missing, zero, previous-frame-only or layout-only target rejects with `CUI_ERROR_INVALID_ACTION`. A frame with a submitted duplicate/folded-colliding box ID rejects element styling to avoid ambiguous ownership. Call only during composition, outside diagnostic, measurement and prepaint callbacks; layout-only submission cannot mutate another painted target. Invalid lists, kinds, radii or numeric values reject before replacing decoration. Zero-count radii have no paint and follow the existing empty-list validation policy. Outside an active frame the call returns false. `true` means accepted style values, not completed layout or renderer resource success; check frame and renderer results normally. Custom CSS-inspired values use an explicit constructor: ```c cui_box_shadow layer; if (cui_box_shadow_from_css(0, 8, 24, -4, (cui_color){0, 0, 0, 48}, CUI_BOX_SHADOW_DROP, &layer)) { styled = cui_element_set_box_shadows( ui, card_id, &layer, 1, (cui_corner_radii){8, 8, 8, 8}); } ``` `blur_radius` converts to Gaussian `sigma = blur_radius / 2`; radius must be finite in `[0,512]`. Offset/spread must be finite in `[-4096,4096]`. Invalid input leaves the constructor output unchanged. Direct `cui_box_shadow.layer.sigma` and named presets keep their existing meanings. The CSS spec describes the half-radius Gaussian relationship: [CSS Backgrounds §6.1.2](https://www.w3.org/TR/css-backgrounds-3/#shadow-blur). This convenience does not claim browser pixel identity: CUI retains its bounded kernel, source spread/radius and mask-culling behavior, and RGBA8 quantization. DROP paints before background; INSET after background, before local content and children. Each phase retains supplied order. Ancestor clipping/opacity and portal ordering remain the existing box-shadow rules; local child-overflow clipping does not remove the box's outer shadow. Decoration changes no layout, hit target, semantics or input behavior. See [DROP_SHADOW.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DROP_SHADOW.md), [INSET_SHADOW.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/INSET_SHADOW.md) and [SHADOW_PRESETS.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SHADOW_PRESETS.md) for renderer limits, masks, owned cache budgets and failure boundaries. The generic setter is a C API. The additive [bridge V1 authoring slice](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_SHADOWS.md) implements six explicitly listed builder roots with focused C/Python/JS/Go/Rust runtime and strict TypeScript checks. Combined release validation remains pending; bundled C headers alone do not establish other typed language support. Popup/trigger/backdrop and anonymous or repeated component parts need explicit owner-specific public addressing and tests. Full 78-family component-part and binding coverage remains planned in `design/ELEMENT_SHADOW_STYLING.md`. The [78-family ownership audit](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/ELEMENT_SHADOW_COVERAGE.md) identifies actual paint targets and remaining addressing gaps; source eligibility is not per-family test or binding acceptance. ## Component paint ownership Apply styling after the component submits its boxes. These C entry points have specific paint targets; IDs do not imply that every nested part is addressable. | Component | Surface ID | Notes | | --- | --- | --- | | Button | caller ID | Includes custom/styled content; use resolved corner radii. | | Input | caller ID | Framed root; `cui_input_viewport_id` is the inner text viewport. | | Avatar | caller ID | Outer circular surface/ring, including the photo variant. | | Legacy `cui_badge` | caller ID | Standalone pill. | | `cui_badge_ex` | `cui_badge_indicator_id(owner)` | Caller ID wraps content; count0 omits the indicator, dot/icon still show. | | Switch | `cui_switch_track_id(owner)`, `cui_switch_thumb_id(owner)` | Caller ID includes label; thumb shadow remains clipped by track. | | Slider | `cui_slider_track_id(owner)` | Caller ID includes label/framing. This entry has no separate thumb. | | Popover / Dialog | `state.overlay.id` | Panel portal, independent of body, arrow, backdrop and trigger. | | Tooltip | caller tooltip ID | Only after tooltip submission returns true; separate from trigger ID. | Badge/Slider getters expose the IDs already used by their painters. They return0 for owner0 or a derived zero ID; zero cannot name an element style target. They perform no presence check. A hidden count badge or inactive tooltip has no panel to style that frame. Do not reconstruct internal ID salts or treat another part's semantic ID as the surface. Checkbox and Radio legacy caller IDs denote whole rows including labels and retain anonymous indicators. Explicit `_with_parts` entries can instead register caller-supplied indicator IDs; see [NAMED_SELECTION_INDICATORS.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NAMED_SELECTION_INDICATORS.md) for capture, early validation and late collision/capacity boundaries. Single Radio and RadioGroup remain separate paint owners. These C-only part contracts do not change legacy anonymous IDs or establish typed bridge/language support. For bounded semantic ROOT/MAIN/indicator/track/thumb authoring, read [typed part shadows](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_PART_SHADOWS.md). Slider has no thumb; owner topology, whole-group naming and separate reset are explicit parts of that contract. --- ## Empty source composition Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/EMPTY.md # Empty source composition Audited against frozen upstream kit source commit `87d10ae5e1299d1be18670a37570c5402f952e34`, `crates/component/src/empty.rs`, including every constructor, setter, renderer, media variant, parent-child implementation and test. `cui_empty_ex` composes optional header, optional content, and appended children. Header independently accepts optional media, title and description. The order is always media, title, description, content, appended children. Assigning another slot pointer replaces only that slot. A non-null empty slot retains its container; a null pointer omits it. All pointers are borrowed for the synchronous call. Each slot accepts text followed by arbitrary application children; use a callback for multiple custom children, icon/image/avatar compositions, rows and controls. Native buttons retain their standard pointer, keyboard, focus and disabled rules. Callbacks receive a temporary theme carrying their slot's font size and foreground; do not retain its pointer. Child IDs must be stable and distinct from the internal IDs derived from the root ID. Source defaults use an explicit 16 pixel rem, overridable independently of theme font size. Root grows in both axes, centers children, uses 24 pixel padding and 16 pixel gap. Header and content grow to available width with a 24rem cap and 8/10 pixel gaps. Title uses medium 14 pixel text; description uses muted 14 pixel text with 22.75 pixel line spacing. Media is an intrinsic column; icon variant is a centered 32 pixel muted square with large theme radius and 16 pixel inherited font. An additional 8 pixel media bottom space is represented by an empty spacer plus the header gap, keeping the normal media-to-title distance at 16 pixels. The root has **no background and no visible border**. Source sets a dashed border style/color but no border width. CUI preserves this invisible default. The legacy `cui_empty` wrapper keeps its existing visible border, sizing and typography. Call `cui_empty_default_style`, change desired fields, then attach the resulting style to a root/header/slot. This is independent style replacement with all values explicit, rather than a CSS cascade. Dimensions of -1 request growth; zero fits unless fixed flags request an explicit zero. Other negative/nonfinite metrics, invalid media variants and malformed nonempty spans reject before any callback, layout or semantic mutation. Callbacks themselves must emit balanced layout and valid controls; their application side effects cannot be rolled back. Remaining source gaps: CUI core lacks dashed border paint and paragraph alignment, so custom visible borders are solid and wrapped paragraphs remain left aligned inside centered containers. Generic `StyleRefinement` flex-wrap, text decoration, font inheritance into arbitrary external descendants and every CSS-style property are not reproduced by this typed box/text style surface. Root XL radius maps to CUI's large theme radius because the theme has no distinct XL token. Therefore this is a functioning named composition API, not a claim of complete visual/style parity. `tests/unit/test_empty_source.c` checks ordering, optional omissions, replacement, 24rem bounds, default paint/metrics, Unicode narrow wrapping, native keyboard and pointer actions, disabled actions and invalid preflight atomicity. The test is registered in CMake and the standalone distribution includes this API. --- ## Indexed pointer-region admission Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/EVENT_HOVER.md # Indexed pointer-region admission `cui_event_hovered(ui, event_index, id)` is a read-only Core query for a pointer event's position against a named semantic's **previous completed** clipped region. Read the complete contract in `include/cui/cui.h`. This is useful for release validation when later queued mouse or touch samples have already changed the context's final pointer position. Existing `cui_hovered` behavior is unchanged. Call during ordinary frame submission after opening the relevant named scopes. A valid prior input snapshot is required. The query returns false outside that phase, during measurement/prepaint/inert/layout-only submission, on a sticky error or invalid prior snapshot, for invalid IDs/indexes, disabled/unknown target semantics, nonfinite coordinates, and events other than POINTER_DOWN/MOVE/UP. It does not treat SCROLL or accessibility actions as pointer samples. Clearing an error alone cannot reconstruct a missing completed snapshot. The event's original indexed coordinates determine admission; capture and the context's final pointer position do not. Consumption and activation acceptance are separate: a consumed event can still be geometrically admitted. Callers retain their own consumed-event, drag ownership and value/callback policies. This query does not consume, activate, focus, capture, cancel or replay input. Prior clipping, prior modal eligibility, and currently active retained named scope ancestors apply. The target's prior scope ancestry must also belong to any active current modal, independently of the query caller's scope stack. A newly opened disjoint modal therefore denies old background target regions. The geometry remains prior input geometry; it is not current-frame paint bounds. Higher interactive layers or paint roots occlude the region, including popup or absolute descendants. Within the same layer and paint root, later unrelated interactive siblings occlude; ordinary actual layout descendants such as a Table's headers and grips do not. Ancestry uses Core's retained nearest layout semantic parent, not a `details.parent` override. Focusable and pointer-activatable semantics and explicit pointer-activation barriers participate. Disabled barriers still occlude; ordinary disabled controls do not. Passive painted siblings and custom nonsemantic paint are not pixel-occlusion evidence from this query. The query allocates nothing, adds no context fields, and borrows no caller memory. It performs bounded scans over the configured semantic/scope capacities and retained layout ancestry. Its worst-case work grows with those capacities; use it for selected event decisions rather than as a generic per-node observer. There is no event propagation or dispatch architecture change. The API is C11; foreign high-level builder facades are not introduced by this addition. ## Table touch behavior An enabled movable column header sets the existing `touch_drag_priority` semantic flag. A touch that starts there owns column reordering instead of ancestor pan. Nonmovable headers and body content retain scroll arbitration. Disabled/loading and disabled-column cases retain their existing mutation restrictions. Table validates a TOUCH drop using the indexed query. Its mouse branch continues to use `cui_hovered`; all midpoint, pinned-boundary, threshold and callback rules remain unchanged. Short taps still sort where sorting is enabled. Multicontact cancellation does not fabricate a move callback, and a later genuine touch can start a new reorder. This behavior does not implement Dialog reopen cancellation or other raw consumers' retained-state lifecycle policies. --- ## Form and Field Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/FORMS.md # Form and Field The frozen 0.7.1 Form composes application-owned controls. It does not store values, validate inputs, or submit automatically. CUI follows that contract: `cui_form` accepts a borrowed array of typed `cui_form_field` descriptors and callbacks for controls, labels, descriptions, and the optional footer. Callbacks run each frame for visible fields. The application owns callback data and strings. The default is one column, vertical labels, 140-pixel horizontal label width, medium density, and no footer. Use `cui_form_options_default`, or zero initialize options. Width defaults to 480. Columns and label orientation are independent. Small and extra-small use a 6-pixel row gap, medium 8, and large 12; the default column gap is three times that. Positive gap overrides and label text sizes are supported. Field alignment controls the horizontal label/control alignment. `column_span` defaults to one. `column_start` and `column_end` use one-based CSS grid lines; negative lines count backwards from the end, so `-1` is the final line. Zero means automatic placement. Explicit start/end determine the span. Fields flow in descriptor order without overlapping: when a requested start is behind the placement cursor or the span cannot fit, a new row starts. Hidden fields occupy no cells and invoke no callbacks. Set `no_label_indent` to omit the label slot and horizontal description indentation. The footer spans the full width below all fields and aligns its callback content to the trailing edge. `cui_form_plan` supplies allocation-free placement and widths for custom renderers. It validates all descriptors before changing output. Limits are 64 columns and 256 fields; invalid spans, lines, widths, strings, duplicate IDs, and insufficient output capacity are reported. Columns are explicit; applications choose their responsive column count. This is ordinary row/column composition over core Clay layout, with no additional general-purpose layout tree. `cui_base_form` submits passive group/field/label semantics without painting or a theme implementation dependency. Set each field's `control` to the actual input ID. `cui_form_associate_control` preserves its existing semantics while attaching field parent, label, description, required, invalid, and read-only metadata. Styled composition invokes it after the control callback. When rendering a custom base form, call it after submitting each control. Error text replaces the ordinary description when invalid, and styled forms use the danger token. For example, retain a `cui_edit` and `cui_input_state` in application state, and provide a control callback that calls `cui_input_ex` at the supplied width. Pass required, invalid, disabled, and read-only options to that control as appropriate. Then supply `.control = input_id`, `.render_control = callback`, and `.user = state` in the field. Arbitrary controls govern their own disabled behavior; passive form metadata does not prevent a custom callback from changing application state. Required fields show a themed asterisk. Supply an accessible label string even when drawing a custom label callback. Attach submission to the footer's Button. Tests cover validated placement and transactional failure, spans and negative lines, conditional fields, four themes, both label orientations, shared row geometry, full-width fields, dynamic descriptions, trailing footer, accessible associations, and real Input edits/read-only/disabled events. The base test links only core and form-base, with no styled or theme implementation. This provides the Form/Field composition contract, not a validation engine or a claim of full framework parity. Existing Input/Editor limitations carry through the application-supplied control, including incomplete multiline presentation, IME, grapheme navigation, and native accessibility bridges. # InputGroup For a search field with a leading magnifier, use one inline custom addon. Retain the editor and `cui_input_group_state` in application state. The callback paints only the icon; the group handles clicking the prefix to focus the editor: ```c #include "cui/cui_form.h" #include "cui/cui_icon.h" static void search_prefix(cui_context *ui, const cui_theme *theme, void *user, bool disabled, bool readonly, float width) { (void)user; (void)disabled; (void)readonly; (void)width; cui_icon_error error = cui_icon_named(ui, cui_id_from(ui, "search/icon"), theme, cui_string("search"), (cui_icon_options){.size = CUI_ICON_CUSTOM, .custom_size = 16}); if (error != CUI_ICON_OK) { /* report the missing asset through your host */ } } void draw_search(cui_context *ui, const cui_theme *theme, cui_edit *query, cui_input_group_state *state) { cui_input_group_addon prefix = { .id = cui_id_from(ui, "search/prefix"), .width = 24, .alignment = CUI_INPUT_GROUP_INLINE_START, .kind = CUI_INPUT_GROUP_CUSTOM, .render = search_prefix }; cui_input_group(ui, cui_id_from(ui, "search/group"), cui_id_from(ui, "search/input"), theme, query, state, &prefix, 1, (cui_input_group_options){.width = 300, .name = {"Search mail", 11}, .placeholder = {"Search mail", 11}}); } ``` This uses the embedded `search` artwork and one shared input frame. The Form headless test checks icon placement and prefix-click focus followed by typing. Input's own options do not provide adornment slots; InputGroup owns that layout. `cui_input_group` composes exactly one retained `cui_edit` with up to 64 borrowed addons. `cui_input_group_state` retains input drag state, horizontal scroll, and measured viewport bounds. Programmatic editor updates use the ordinary Edit API; only actual user text changes set the returned `input.changed` flag. Each addon has a distinct stable ID, position (`INLINE_START`, `INLINE_END`, `BLOCK_START`, `BLOCK_END`), optional width, and text/button/custom kind. Addons on the same side keep array order. Custom render callbacks receive the inherited disabled/read-only policy. Buttons default to ghost presentation, with primary, secondary, outline, and danger variants. Disabled or loading actions cannot activate. `activated_addon` returns the last activated built-in action in the frame; the application performs its action. Custom interactive content owns its callbacks and must respect the supplied disabled policy. The group paints one shared theme frame; the input's own frame is transparent. The field and addons share Input metrics: extra small 20px, small 24px, medium 32px and large 44px at the default 16px theme scale. The medium preset is the default. Theme scaling and an explicit group font size scale these dimensions together. Inline addons remain in the same row; block addons intentionally occupy rows above or below it. The gallery defaults to inline prefix/field/suffix/action and exposes block addons through its mode selector. Invalid edits highlight the shared frame. Disabled input disables the group and built-in buttons. Read-only preserves focus, selection/copy behavior, and addon actions. Clicking an addon or empty group inset focuses the editor; clicking an action keeps action focus. Root/child semantics retain input accessible name, hierarchy, read-only/error state, and loading action status. `cui_base_input_group` owns all input reduction and action behavior without theme painting. Link core, base, edit, and form-base for this API. A custom renderer supplies addon/root/input bounds and can retain its own input viewport rectangle. The styled group uses ordinary Input's paint-only path and measured scalar hit mapping, with no duplicate editor reducer. Its additional implementation link is components/theme, already required by styled Input. The group inherits the currently implemented Input/Editor slice. Multiline editors compose with block addons, but sophisticated Textarea row auto-growth, multiline caret/selection presentation, tokens, password toggle, attachment paste hooks, tooltips, and built-in dropdown/popover addon builders remain outside this module. Applications can compose existing menu/popover controls in custom addons; this does not establish full InputGroup/editor family parity. --- ## Go and Rust localized TimeField (focused dynamic proof, unreleased) Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/GO_RUST_TIME_FIELD_LOCALIZED.md # Go and Rust localized TimeField (focused dynamic proof, unreleased) This additive authoring slice is based on root `8a402c2b`. Focused Linux dynamic Go/Rust compile, private-wrapper tests and both authored examples passed; see [the exact receipt](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/validation/time-field-go-rust-dynamic.json). Root configured dynamic acceptance now passes for current/old/partial providers and both actual authored examples; see the [root receipt](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/validation/localized-facades-root.json). Bundled-source static acceptance now also passes; installed-package gates remain open. The authoritative C contract is [BRIDGE_TIME_FIELD_LOCALIZED.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_TIME_FIELD_LOCALIZED.md) and `include/cui/cui_bridge.h`. Existing scalar TimeField APIs stay unchanged. This does not bind direct Base/Styled options, drafts, clipboard/IME policy or claim full source focus/accessibility parity. The new modules are `bindings/go/cui/time_localized.go` and `bindings/rust/src/time_localized.rs`. They copy an exact V1 configuration616, result80 and change64 record. Fourteen explicit UTF-8 prefix-free tokens have 1–16 bytes; four optional segment names have0–64. English/Arabic constructors are conveniences containing explicit tokens, not a locale registry. Same-day inclusive bounds are optional. Minute precision requires seconds0. Edit generation must be nonzero: convenience defaults use1, and explicitly authored0 is rejected rather than normalized. Tokens/names and bounds are copied; rejected updates preserve the old C configuration and Go builder value. No foreign reducer, normalization or owner-value clamping. ## Go authoring ```go cfg := cui.ArabicTimeField() // H12, Arabic digits and explicit period tokens cfg.Minimum, cfg.Maximum = &cui.Time{Hour: 8}, &cui.Time{Hour: 18} cfg.EditGeneration = 1 field := cui.TimeField("appointment").Time(cui.Time{Hour: 14, Minute: 15}).LocalizedTime(cfg) field.OnTimeFieldChange(func(change cui.TimeFieldChange) { // Applied copied observation. Do not replay it as another edit. }) // Before Mount, optionally call app.EnableLocalizedTimeFields(capacity). // Otherwise a tree with localized configuration enables the default4096 queue. ``` After mounting, `SetLocalizedTime` validates/copies and commits builder state only after successful C configure. `LocalizedTimeConfig`, `LocalizedTimeResult`, `ClearTimeValidation`, `PollTimeFieldChange` and `DispatchTimeFieldChanges` are app operations. `Dispatch` also drains the typed queue after generic events and controlled Slider dispatch. Callbacks are never invoked inside step. Existing `SetTime`/`App.Time` remain scalar owner setters/getters. An unmounted builder does not look up a global provider or call C. Mount uses its owning app, preflights configuration, and uses existing rollback on any created node failure; enabling queue capacity is an app-lifetime opt-in and is not undone by failed mount. Go app creation locks its owner OS thread; all calls, close and callbacks must remain there. Goroutines are not an alternate owner. Removal clears callbacks, copied values remain safe after removal/close, and close during callback stops further dispatch. Panic propagates after the current record was consumed; a defer clears the dispatch guard. Step/Run/nested Dispatch are rejected during typed callbacks. Ordinary owner setters and removal follow existing mutation rules. ## Rust authoring ```rust let mut config = TimeFieldConfig::arabic(); config.minimum = Some(Time { hour: 8, minute: 0, second: 0 }); config.maximum = Some(Time { hour: 18, minute: 0, second: 0 }); config.edit_generation = 1; let field = app.localized_time_field( root, "appointment", Time { hour: 14, minute: 15, second: 0 }, &config)?; app.on_time_field_change(field, |change| { // Clone for an owned application observation, then update siblings after dispatch. })?; ``` The app-owned constructor validates before node creation and removes its new node if scalar time or configure fails. It enables default4096 capacity only if not yet enabled. `configure_localized_time` changes an existing node atomically. An existing app-borrowed `Builder::localized_time` is a setter; failure does not remove a preexisting node. Use the constructor when atomic creation is needed. Rust has no new unmounted declarative tree/provider: its existing builder already borrows App. `localized_time_config`, `localized_time_result`, `clear_time_validation`, `poll_time_field_change`, `dispatch_time_field_changes` map to the same C contract. Normal `dispatch` drains the typed queue after the existing queues. The new typed dispatch count reports consumed owned observations, including records without a registered callback; legacy dispatch counting is unchanged. App remains !Send/!Sync through its existing Rc marker; it and all native UI calls stay on the creating OS thread. Rust borrows prevent aliasing mutable App into callbacks; callbacks can retain owned copies in local Rc/RefCell state, and `run_with`'s post-dispatch hook applies UI updates. Panics unwind in Rust; the existing native run trampoline catches them and resumes only after returning from C. The dispatch guard resets on unwind. No copied record replays after a panic. Node removal prunes stale typed callbacks; close requests stop typed dispatch. Outstanding owned copies are independent of App lifetime and carry app-scoped node identity, not a live handle guarantee after removal. ## Optional group and failed steps All ten C symbols must be present, versions bit0 enabled and sizes616/80/64 match. A missing/partial/mismatched dynamic provider makes the new feature unavailable; no symbol is added to the existing mandatory loader. Old libraries can still load and run scalar APIs. Go resolves through its selected app library and weak current static symbols. Rust dynamic lookup follows its existing linked-library provider; current source-built static packaging binds the current group. Linking a new static wrapper to an older static archive is not promised as optional-symbol compatibility. Default/shared WASM and native NO_TLS are unsupported by the C owner policy. Cross-target Go/Rust package support and Rust MSRV for this new module are untested; no new compiler minimum is claimed. Existing toolchain prerequisites still apply. Capacity is immutable1–4096 (0 selects4096). Drain between frames. Changes are already-applied aggregates, including records whose later rendering failed: `FrameStatus`/`frame_status` is independent of value/validation. Explicit polling after a failed step is supported; `frame()`-style convenience propagation does not automatically drain after failure. A result getter rejects failed/omitted/unready frames under C rules; clear-validation is not result recovery. Polling and dispatch consume the same FIFO, so use one delivery strategy. Removing nodes prunes pending records under the bridge's full generation identity. No receipt acceptance or event replay occurs in either wrapper. ## Complete authored examples and pending gates `bindings/go/examples/time_field_localized/main.go` and `bindings/rust/examples/time_field_localized.rs` author real English24h and Arabic12h fields, same-day bounds, read-only/disabled/bounds toggles, validation clearing and summary updates from copied callbacks. Default mode is windowless scripted input; `--native` uses existing host run and real input, requiring `CUI_TEST_FONT`. The windowless scripts assert English10:45, Arabic15:20, exactly two copied callback observations and the actual summary node text. Native interactive mode has not run. Automated native runs must use the private-Xvfb wrapper; never launch these examples on the maintainer desktop during validation. Executed focused tests cover owned wire copies/prefix/precision validation, real typed changes after step, invalid replacement, wrong kind, capacity/constructor rollback, no result replay, copied failed-frame decoding, and Rust callback panic recovery. Matching current, old and partial-provider dynamic runtimes passed; Arabic read-only/disabled/bounds/clear, Go wrong-thread/close/panic and Rust panic/no-handler count also passed. Initial no-callback failures remain in the receipt. Scripted input first completes two ordinary frames and checks result admission; a minute-only field center is a separator, so the script clicks its first-quarter textbox. Still required: real later-failed-frame copied observations at the facade boundary, additional schema-poison providers, native run unwind, MSRV/installed-package and installed-package acceptance and fresh generated-consumer checks after further API changes. No full binding/source-family parity follows from these focused checks. The final decoder gate separately validates applied changes and latest results: applied records require a nonzero frame, non-EMPTY bridge status, validation OK/syntax/value/range and a genuine value difference. Latest results may be unchanged, but must identify the requested node, report a healthy frame, agree with their changed bit and never claim more queued changes than applied change. Malformed-wire and valid-unchanged controls passed alongside real queue tests. ## Durable opt-in CTest acceptance The reusable runner is `bindings/go/tests/test_time_localized.py`. Integration uses `CUI_TIME_FIELD_BINDING_TESTS=ON` (default OFF), with explicit existing actual old and partial DSOs, an existing current bridge target and retained Rust cache: ```sh cmake -S . -B EXISTING_BUILD -DCUI_BUILD_BRIDGE=ON \ -DCUI_TIME_FIELD_BINDING_TESTS=ON \ -DCUI_TIME_FIELD_OLD_LIBRARY=/absolute/actual-old/libcui_bridge.so \ -DCUI_TIME_FIELD_PARTIAL_LIBRARY=/absolute/actual-partial/libpartial.so \ -DCUI_TIME_FIELD_RUST_TARGET_DIR=/absolute/existing/cargo-target python scripts/test_local.py --build-dir EXISTING_BUILD -j1 -V \ -R '^(bridge_go_time_localized|bridge_rust_time_localized|bridge_time_localized_runner_offline)$' ``` Root owns the shared CMake wiring. When opted in, Go/Cargo and the explicit providers are required; missing prerequisites must fail configuration rather than silently skip acceptance. `bridge_go_time_localized` and `bridge_rust_time_localized` use the same runner with `--language go|rust`, `--build-dir`, `--library`, `--old-library`, `--partial-library`, optional `--go` and `--cargo`, and Rust's required `--target-dir`. Both language invocations accept all tool/cache arguments for common CMake wiring. Tests run serially with a 300-second outer CTest timeout. No runtime command is installed or downloaded. The runner requires the private wrapper's invisible-display marker and Linux; it never passes `--native` to examples. Go uses `cui_dynamic`, one build job, network-off settings and the selected exact provider in separate processes. Rust sets `CUI_BRIDGE_LIB_DIR` to the current library before Cargo, so build.rs cannot fall back to compiling the engine/SDK. Cargo is offline/locked, no default features and single-job. It reports the actual test executable through JSON; that same executable runs against current, actual old and partial providers. Two small symlink directories select the real old/partial artifacts with the required linker filename; no engine/DSO copy is made. Existing nonmatching files or aliases are never overwritten. Rust then executes strict wire units and the asserting English/Arabic example; Go executes its matching tests and example. All command failures stop the suite immediately. This is dynamic acceptance only; bundled-source static acceptance is recorded separately below; package installation remains pending. `bindings/go/tests/test_time_localized_runner.py` is an offline six-test harness proof: it mocks all tools and checks provider selection, offline/serial flags, reported-binary reuse, malformed Cargo output, desktop rejection, fail-fast and non-destructive aliases. It ran6/6 without Go/Cargo or native execution. Root configured execution now passes both dynamic suites plus the offline harness (3/3 CTest entries, 15.94s). Earlier scratch-harness evidence is retained separately; bundled-source static consumers now pass the separate root gate; packages remain unverified. ### Prepared default static source acceptance The same runner now accepts `--linkage dynamic|static`, defaulting to dynamic, so existing invocations retain their contract. In static mode no current/old/ partial library arguments are required or used. It explicitly removes `CUI_BRIDGE_LIB_DIR`, `CUI_BRIDGE_LIBRARY`, `LD_LIBRARY_PATH` and preload overrides. Go omits `cui_dynamic`, compiles `go test -c -o` and the asserting example into `EXISTING_BUILD/time-localized-static/go`, then inspects and runs those exact artifacts. Rust's unset library override selects its bundled-source build.rs route using the explicitly reused static Cargo target directory. It discovers integration-test, wire-unit-test and example executables through Cargo JSON, inspects each, then runs the exact reported artifact. Both modes remain offline and serial. Static mode deliberately may compile bundled C sources; unlike the dynamic mode it is not an engine-build-free gate. Each inspected ELF must lack a `libcui_bridge` NEEDED dependency, including versioned shared names. `readelf` failure or such a dependency stops the runner before executing the artifact. A truly static ELF with no dynamic section is accepted. This does not claim a fully static libc, native backend support or package publication. No actual old/partial-provider result is claimed in static mode; its optional-provider test returns without that separate dynamic fixture. Proposed root CMake integration (default OFF): ```sh cmake -S . -B EXISTING_BUILD -DCUI_BUILD_BRIDGE=ON \ -DCUI_TIME_FIELD_STATIC_BINDING_TESTS=ON \ -DCUI_TIME_FIELD_STATIC_RUST_TARGET_DIR=/absolute/existing/static-cargo-target python scripts/test_local.py --build-dir EXISTING_BUILD -j1 -V \ -R '^(bridge_go_time_localized_static|bridge_rust_time_localized_static)$' ``` Root wires the two named tests and passes `--readelf /path/to/readelf`; the tool is required when opted in. The retained integrator cache is `/home/matteo/.cache/cui-current-validation/native/rust-slider-static-target`. Do not create another Cargo cache or run this source-build gate without its coordinated compiler lease. All runtime tests require the private display marker; no desktop or `--native` launch is introduced. Offline runner coverage now passes10/10: static plans clear provider overrides, select tag-free Go commands, inspect each Cargo-reported executable, and reject a shared-bridge dependency before running. These tests use mocked tools only. Root configured static acceptance now passes **3/3 CTest entries (299.16s)**: offline harness10/10, Go201.24s and Rust97.76s, including compilation, owned wire and real authored UI tests/examples. ELF dependency inspection found no shared CUI bridge in any of the five artifacts. System libraries remain dynamic. See [root static receipt](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/validation/time-field-static-root.json). Native interactive, MSRV and installed-package acceptance remain open. --- ## Go controlled Single/Range Slider Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/GO_SLIDER_MODEL.md # Go controlled Single/Range Slider Unreleased bridge-owned V1 subset, separate from legacy `Slider(key)` scalar float/autocommit behavior and CHANGE timing. This does not bind arbitrary direct C Styled style/motion records, native numeric AT, typed SET/touch injection, V2 gradient adapters or vertical registered-scroll admission. The [Rust subset](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/RUST_SLIDER_MODEL.md) is separate, with MSRV1.85.1 validation pending; full Slider closure remains open. Read the [C contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_SLIDER_MODEL.md). ## Complete authored UI [Copy the complete Go program](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/go/examples/slider_model/main.go). It defines external Single/Range owner storage, a real nested Row/Column control, labels, an acceptance-policy button and callback. It focuses actual thumb bounds, submits keyboard input and verifies explicit acceptance/rejection; it is not a native launcher. Default execution is windowless. With existing [C11/Go/CMake prerequisites](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DEPENDENCIES.md), Go 1.23+ and no fetched dependencies, first build the C bridge from the repository root: ```sh cmake -S . -B build -G Ninja -DCUI_BUILD_NATIVE=OFF -DCUI_BUILD_BRIDGE=ON cmake --build build --target cui_bridge export CUI_BRIDGE_LIBRARY="$PWD/build/libcui_bridge.so" cd bindings/go GOMAXPROCS=1 GOPROXY=off GOTOOLCHAIN=local go run -tags cui_dynamic -p1 ./examples/slider_model GOMAXPROCS=1 GOPROXY=off GOTOOLCHAIN=local go run -tags cui_dynamic -p1 ./examples/slider_model -reject -vertical GOMAXPROCS=1 GOPROXY=off GOTOOLCHAIN=local go run -tags cui_dynamic -p1 ./examples/slider_model -single ``` Use an absolute shared-library path appropriate for the platform. The existing Linux default build without `cui_dynamic` embeds matching source SDK objects; that source build can require more compilation than the dynamic commands above. Do not assume optional weak symbols imply successful static extraction: the `TestSliderStaticClosure` test requires actual support and typed UI geometry. Automated native tests run only through the private `scripts/test_local.py` wrapper; SDL native tests additionally require an explicit pinned font. Local proof is Linux, not a registry/package release or physical accessibility claim. ## Owned values and explicit decisions `DefaultSliderConfig()` supplies one complete config. `NewSliderSingle(end)` and `NewSliderRange(start,end)` return `(SliderValue,error)`, using float64. Value tags and inactive fields are private; `IsRange/Start/End` expose owned scalar copies. Config/domain fields are ordinary Go values, with uint64 SourceGeneration, float64 domain/step, typed scale/orientation/layout and checked float32 geometry. Configure copies them; modifying an application-local config does not mutate C. Parent layout ignores authored Length and canonicalizes it to 0. Malformed native output with nonzero inactive parent length rejects instead of normalizing. `SliderModel(key,config,confirmed)` returns a retained typed node. Mount validates records, the complete optional symbol group and Row/Column-only ancestry before creating nodes. Bad builder records accumulate the existing node error; old trees do not require or enable typed support. Missing/unsupported symbols produce an explicit error, never scalar emulation. Typed node methods are `OnSliderRequest(func(SliderRequest) error)`, `ConfigureSlider`, `SetSliderValue`, `SliderValue`, `SliderConfig`, `SliderPartBounds` and `SliderPresentation`. Configure replaces config plus whole pair atomically and retains captured reducer cancellation. SetSliderValue cannot change Single/Range kind. Existing Text/Disabled/Remove methods retain their roles; typed nodes have no old OnChange path. `App.SupportsSliderModel() (bool,error)` checks the full 16-symbol group, support bit and all five record sizes. `EnableSliderRequests(capacity)` enables the independent bounded FIFO (0 means 4096); typed trees enable lazily. Reenable does not resize/discard a backlog. `PollSliderRequest() (request,bool,error)` pops one owned copy; `DispatchSliderRequests() (count,error)` invokes registered handlers. Returned request/input/domain/value/receipt data contains no borrowed C buffers, pointers to C memory or retained App/native handles. Every C uint64 remains uint64, including frames, sequence/config/source identities, event indices and pointer/device/accessibility IDs. Unknown tags/masks and incoherent unavailable input evidence reject rather than being guessed. Receipts have private authority fields plus `Info()` returning inert metadata. Copied input records require zero numeric evidence when HAS_NUMERIC_VALUE is absent, including keyboard events and accessibility INCREMENT/DECREMENT. Explicit numeric SET evidence remains supported. Malformed records are rejected before a request or receipt authority is published; previously copied records stay valid. Assignment preserves an issued receipt; constructing only metadata does not invent authority. A nonzero-size private per-App namespace token retains no App or C pointer. Keep handles/receipts within the matching App and loaded bridge image; these tokens are not a security or cross-image uniqueness guarantee. Copied records remain readable after removal/Close; acceptance can expire. `AcceptSliderRequest(receipt,wholePair)` is explicit and may accept another valid full pair. Update external owner storage only after acceptance succeeds. Polling, callback absence or rejection never autoaccepts or emits CHANGE. Current stays the immutable C submission entry; requested intent evolves across original-order inputs. Already accepted effects are not rolled back by later failures. ## Timing, callbacks and OS-thread lifetime `Step` only steps. `Dispatch` preserves old FIFO/callback behavior first, then drains the independent typed FIFO when enabled; no global queue order is invented. Typed count is popped records, including entries without handlers. Each callback receives an owned Go copy after C returns. Application-local mutation cannot alter the C snapshot. A callback may mutate external owner state, accept, configure, replace/remove its handler, update labels, queue future input or request teardown. Nested Step/Run/Dispatch/typed-dispatch reject only during new typed dispatch. An error stops dispatch after consuming that entry; later entries remain queued. A panic resets the guard and propagates normally in manual dispatch. Native Run uses its existing panic/error trampoline, resuming only after leaving C. No C view/borrow or foreign callback invocation spans user code. Go keeps its existing affinity: New locks the creating goroutine to its OS thread; all App calls check that thread. Keep it alive through Close and serialize calls. Do not copy, overwrite or replace live App/Node storage during a callback; this protects UI ownership, while external application owner/userdata mutation remains allowed. RequestClose requests shutdown; Close destroys and balances the lock (native Run defers the unlock until it returns). Successful RequestClose records typed-local closing evidence so a typed handler stops before another poll even though App is not yet destroyed. Remove/Close release new typed handlers. Do not add finalizers, move live Apps between goroutines, race destruction or treat receipt snapshots as cross-thread UI authority. There is no temporary hide/reinsert contract. Part bounds are actual completed geometry or `present=false`; disabled track/fill remain and thumbs omit. Presentation copies render status and absolute Core-clock wake values; neither getter certifies physical rendering/accessibility or V2. ## Proof and fixture limits Actual headless tests cover Single/Range in both axes, full-pair decisions, double precision, callback error/panic/removal/Close/RequestClose, expiry, readonly, disabled parts, ancestry, owner thread and copied lifetime. Protocol providers are synthetic evidence, not actual UI input. Optional-symbol tests use separate processes loading a tiny provider that depends on an explicitly supplied real old bridge; Go's explicit module lookup cannot be tested by preload interposition alone. Default and dynamic/source modes are separate closure obligations. Historical notification/shadow/visibility fixtures retain their own skip gates; a passed current-library suite does not establish those omitted historical tests. The durable optional protocol runner builds only the dynamic Go test package and 17 tiny providers using existing tools/caches. Supply an actual independent old library; none is downloaded, copied into source, or substituted with fake old UI: ```sh python bindings/go/tests/test_slider_protocol.py --build-dir build \ --library /absolute/path/current/libcui_bridge.so \ --old-library /absolute/path/pre-typed/libcui_bridge.so ``` This always tests current typed UI, actual-old fallback and synthetic optional/ malformed-record cases in separate processes under private Xvfb. Add `--legacy --font /absolute/path/Inter-Regular.otf` only when the current library has SDL/text adapters; this runs the complete existing legacy suite, including native fixtures. CMake conditionally registers `bridge_go_slider_protocol` when configured with `-DCUI_GO_SLIDER_OLD_LIBRARY=/absolute/path/pre-typed/libcui_bridge.so`. It is not registered without that historical fixture. Matching default source closure is separate: `go test -p1 -run '^TestSliderStaticClosure$' ./cui` from bindings/go, with CUI_BRIDGE_LIBRARY unset; use the private wrapper for automated native tests. --- ## HoverCard desktop and tap policy Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/HOVER_CARD_EXTENDED.md # HoverCard desktop and tap policy Include `cui/cui_hover_card_extended.h`. This additive C API combines explicit tap-toggle policy, bounded outside taps and optional semantic relationships. Existing HoverCard/Tooltip functions retain their behavior, including global Escape dismissal for consumed, repeated and modified Escape. There is no new input dispatcher, Core schema, AT adapter or foreign binding API. Submit the trigger first. Pass its actual Button return value as `accepted_trigger_activation`; the extension trusts this application assertion and does not rescan consumed trigger events. A false assertion means no toggle. Do not substitute pointer-up coordinates, raw focus or a queued activation request. Keyboard/accessibility activation accepted by that trigger can toggle too. Choose `CUI_HOVER_CARD_TAP_TOGGLE` explicitly for touch/mobile behavior. Hover, focus and delays do not open or close this mode. One accepted trigger assertion sets open to the inverse of entry open; outside release is applied first and the trigger assertion uses that frozen entry value. Disabled or global Escape closes last. Placement can subsequently close for invalid geometry. A zero/NULL policy retains the existing desktop reducer and placement. No platform is auto-detected. Keep a zero-initialized `cui_hover_card_contact` next to the caller-owned `cui_hover_state`. Submit at most once each frame. Reset the workspace when the context is recreated; neither structure owns callbacks or input pointers. Mode change, frame omission, closed model and protected/frame-zero work discard a pending contact. Do not share one workspace across simultaneous cards. When `outside_tap` is enabled, the workspace must be provided. A primary down outside both previous valid card and trigger bounds arms one contact identified by type, device and contact ID. A matching unconsumed primary up outside both regions closes only when movement stayed below eight logical pixels. Movement at the threshold, even followed by a return to origin, cancels the pending tap. Include displacement at release. Consumed matching input, cancellation, scroll or gesture takeover cancels it. Unknown bounds, unmatched release and secondary buttons never close. Ambiguous simultaneous contacts disable outside dismissal until explicit workspace reset, card close or matching/global cancellation. No event is consumed and no outside pointer capture is installed. A child click retains the card. A press inside followed by a drag outside also retains it. This is intentionally stricter than the frozen upstream mouse-up-out handler, which does not require an outside press or a movement threshold. It supports ordinary outside taps without claiming every host gesture or full mobile parity. Modal permission uses existing Core policy; geometry and modal checks do not establish exclusive ownership among unrelated overlays. Call the helper after relevant leaf consumers; later consumption cannot undo an already applied decision. For raw release dismissal, call `cui_begin_hover_card_with_release` with the same arguments plus `CUI_HOVER_CARD_RELEASE_RAW_PRIMARY` before the handler. This requires TAP_TOGGLE and overrides `outside_tap`; no contact workspace is needed, and a supplied contact is cleared. Any finite, unconsumed primary POINTER_UP outside previous valid **content-only** bounds may close, including over the trigger. It needs no matching down or movement threshold. Accepted trigger activation then wins using frozen entry-open. Invalid enum/mode fails before mutation. Missing/invalid prior bounds and modal denial prevent release dismissal. CANCEL/SCROLL/GESTURE alone do not dismiss or veto a later release; the host must cancel or consume a suppressed release. Submit after leaf consumers. Multiple releases aggregate one final lifecycle transition. LEGACY=0 preserves the original conservative path and validation, including its contact requirement. Enable `relationship` only when this card owns the submitted trigger's `controls`/`expanded` fields. The extension copies all other semantic details. An admitted panel sets controls to its ID and expanded true; rejection/closed sets controls zero and expanded false. This reflects composition admission, not only `state.open`: resource rejection may leave the model open. Missing current trigger semantics yields `relationship_applied=false`; no node is fabricated. The card retains its GROUP role, explicit name and parent=trigger. Tooltip description behavior stays unchanged. Omission does not patch caller semantics. Only `result.lifecycle.control_result` determines whether to compose children and call the existing `cui_end_hover_card`, exactly once. The lifecycle result uses existing observer meaning: changed is a final model transition independent of handler; change_count counts actual callbacks. Callback runs after final relationship work and before arbitrary children, with UNKNOWN source and genuine eligible frame only. No input index, activation evidence, dismiss cause, veto, completed visibility or physical AT announcement is claimed. Copy the payload to retain it. Do not mutate/reenter the active model or input/options from its callback; handlers are borrowed only for the call. Inert/layout-only work keeps maintenance but emits no callback or relationship patch. Core semantic snapshots can prove controls/expanded and preserved details. The current AccessKit adapter emits expanded false for TREEITEM, but not ordinary buttons, so explicit collapsed AT state remains unsupported by this slice. Live screen-reader announcements, arbitrary overlay ownership and Python/Node/TypeScript/Go/Rust exposure remain separate. The compiling headless example is [`examples/hover_card_extended/main.c`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/hover_card_extended/main.c). --- ## Icon Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/ICON.md # Icon Icon renders named, host-loaded or raw SVG as a monochrome antialiased mask through CUI's portable RGBA bitmap draw path. It is decorative by default: it contributes layout and paint without a focus stop or pointer target. A nonempty `accessible_name` opts into a noninteractive image semantic; `decorative = true` suppresses that name. ```c #include "cui/cui_icon.h" cui_icon_state check = {0}; cui_icon_set_name(&check, cui_string("check"), NULL, NULL); /* Inside a frame, with a unique id and an existing theme: */ cui_icon(ui, 42, &theme, &check, (cui_icon_options){.size = CUI_ICON_MEDIUM}); /* After the renderer has consumed the returned draw list: */ cui_icon_state_collect(&check); /* After the final draw list has finished rendering: */ cui_icon_state_destroy(&check); ``` Use one caller-owned state per widget. A zero-initialized state is ready to use; `cui_icon_state_init` also initializes fresh storage. Do not copy an initialized state or initialize it again without destroying it. State operations are not thread-safe. Setters copy path/raw source bytes and replace the previous source. `cui_icon_set_empty` retains the requested layout but paints nothing. ## Sources and assets `cui_icon_set_name` accepts catalog names such as `check`; `cui_icon_set_path` accepts paths such as `icons/check.svg` or host-specific paths. An optional loader runs on the next preparation and again after `cui_icon_reload`. Its returned SVG bytes must remain valid until preparation returns. Returning false tries the embedded bundle. CUI performs no implicit filesystem or network access. Raw data uses `cui_icon_set_data`. The complete 1,830-name/path catalog remains available through `cui_icon_catalog_*`. The default build embeds the 106 frozen upstream defaults plus 17 application essentials from the same pinned archive (126 SVGs total). These include media controls `skip-back`, `skip-forward`, `gauge`, plus `pencil`, `pen-line`, `funnel`, `archive`, `trash`, `mail`, `mail-open`, `paperclip`, `send`, `reply`, `reply-all`, `forward`, `download`, `upload`, `link`, `log-out`, and `check-check`. `filter`, `trash-2`, and `more-vertical` are accepted aliases for `funnel`, `trash`, and `ellipsis-vertical`, including their `icons/*.svg` path spellings. Aliases do not add catalog entries. Define `CUI_ICON_ALL_ASSETS=1` when compiling the implementation to embed all 1,830; other catalog paths require a host loader in the default build. `cui_icon_asset` returns a borrowed static SVG string when embedded. Query `cui_icon_query(name_or_path)` before selecting artwork: | Result | Meaning | | --- | --- | | `CUI_ICON_UNKNOWN` | No catalog entry matches | | `CUI_ICON_CATALOG_NOT_EMBEDDED` | Known name/path, SVG omitted from this build | | `CUI_ICON_EMBEDDED` | SVG is embedded in this build | The query accepts catalog names, paths and the aliases above. It reports build assets, not whether an application loader can supply an SVG. For example, `clock-3` is known but is not embedded in the default build. Handle the `CUI_ICON_NOT_FOUND` result explicitly or supply a loader. For development, opt into `.debug_placeholder = true` in `cui_icon_options`. A missing named or state-backed icon then paints an outline inside its allocated box, preserving `CUI_ICON_NOT_FOUND` and the decorative/named semantic contract. The outline respects tint and custom opacity; it does not replace arbitrary SVG parse errors. Default behavior remains no placeholder. Do not use emoji as a fallback: font coverage and appearance vary. `scripts/icon_assets.py` regenerates the bundle offline from the pinned JSON catalog in `third_party/gpui_icons`; `--check` verifies reproducibility. Generated assets retain the Lucide ISC, Feather MIT and upstream Apache notices. The private NanoSVG parser/rasterizer is pinned and unmodified under its Zlib license. Its external symbols use a CUI prefix, so an application may link its own NanoSVG implementation in a separate translation unit. Implementation macros introduced by CUI are removed afterward. Including both implementations in the same translation unit is unsupported because their private types and static functions share names. Built-in artwork can be replaced across a theme by assigning `theme.icon_loader` and `theme.icon_loader_user`. The callback receives a canonical path such as `icons/close.svg` or `icons/chevron-down.svg`; return your SVG bytes and `true` to replace it, or `false` to use the bundled default. `cui_icon_named` and `cui_icon_spinner` use this provider, including the component controls that call them. Increment `theme.icon_revision` when artwork changes without changing the callback or user pointer. Cached masks otherwise survive ordinary redraws. The theme is borrowed during rendering; its provider user data must stay valid while the application uses that theme. SVG colors become a monochrome alpha mask, tinted with the control's semantic foreground color. ## Size, color and transforms Zero options inherit `theme.font_size` and `theme.text`. Hosts with their own text scopes can supply `inherited_text_size` and `custom_inherited_color`/ `inherited_color`. General automatic text-style scope inheritance is not yet provided by the core. XS, S, M and L are 12, 14, 16 and 24 pixels at a 16-pixel theme font size, scaled by `theme.font_size / 16` to represent source rem units. Custom size is an unscaled pixel square. With inherited size, `custom_width`/`custom_height` enable independent layout dimensions, including zero; an unspecified dimension becomes zero when the other is explicit. An explicit preset or custom size overrides those dimensions. SVG aspect ratio is scaled from the requested width and centered within the layout height. Rotation or a center-relative affine transform changes paint bounds while leaving layout unchanged, and may paint outside the icon's box subject to ancestor clipping. `cui_icon_rotation` returns a replacement transform in radians. SVG RGB colors are discarded; shape alpha becomes the mask. `custom_color` uses an explicit tint, and `custom_opacity` clamps an independent paint opacity to [0, 1]. Changing tint or opacity reuses the raster. Source content, dimensions and affine transform select raster cache entries. The counters in state expose parsing and rasterization for diagnostics. ## Draw lifetimes and bounds Preparation retains immutable masks: changing a source, size or transform does not invalidate bitmap pointers already borrowed by a draw list. Call `cui_icon_state_collect` only after **all** earlier draw lists using that state have finished rendering. It frees retired masks and retains the active mask. Destruction has the same renderer-completion requirement. Collection after each rendered frame keeps steady-state memory small. Reusing one state for several icons in a frame is supported, but consumes additional retained cache entries until collection. `cui_icon_prepare` also works without a UI context. After it returns `CUI_ICON_OK`, `cui_icon_state_bitmap` and `cui_icon_state_paint_bounds` expose the current borrowed raster and relative paint bounds. Empty or singular transforms produce no bitmap. After an error, do not paint a previously exposed bitmap as the new source. Default limits are 256 KiB SVG input, 1,048,576 pixels per raster, 8 MiB retained mask bytes and 16 retained versions. `cui_icon_set_limits` accepts smaller or bounded larger limits; zero fields use defaults. Dimensions and raster sides are capped at 4,096 pixels, paths at 4,096 bytes, SVG dimensions/coordinates at 1,000,000, shapes at 4,096 and total path points at 65,536. Affine coefficients and translation are also bounded. Exhaustion returns `CUI_ICON_LIMIT`; allocation failure returns `CUI_ICON_ALLOCATION`. Borrowed masks are never silently evicted to satisfy a new request. Collect completed draws or increase the configured budget before retrying. ## SVG coverage and remaining differences This implementation uses NanoSVG's supported SVG subset, rather than upstream resvg. It supports the frozen catalog's paths, fills, strokes and opacity, including tiny round-cap dots. It does not promise full SVG/CSS, text, filter, external image or resvg feature parity. The parser is permissive for unsupported constructs; resource checks bound accepted inputs and geometry but are not a complete XML validator. DOCTYPE/entity declarations and embedded NUL bytes are rejected. Vendor internal allocation failures may appear as parse failures or missing geometry; explicit CUI buffer allocation failures are reported separately. Headless tests inspect actual alpha geometry, aspect positioning, affine overflow, size precedence, tint/opacity cache reuse, host reload/fallback, source replacement and borrowed draw lifetimes. Both default and full-catalog configurations parse and rasterize every embedded asset. Build-system, amalgamation and adapter wiring are maintained by the integrator. ## Context-owned convenience icons `cui_icon_named(ui, id, theme, name_or_path, options)` uses a bounded context resource instead of caller-owned state. Equivalent name/path spellings retain the same source and raster. `cui_icon_spinner` renders Loader with a repeating 0.8-second quadratic ease-in-out rotation; zero options use Medium size. Its clock starts on first appearance and resets after absence for a complete frame. The spinner overrides the paint transform, retains layout dimensions and requests redraw while active. Host reduced motion makes it static and stops those requests. Convenience resources use a 1 MiB/four-version raster cache budget per widget, subject to the context's resource count and payload budget. Finish rendering before `cui_begin_frame`: that call collects retired masks and eventually destroys omitted widgets. Context destruction releases all caches. Source/raster preparation errors are returned; context resource exhaustion also reports `CUI_ERROR_CAPACITY`. ## Handling missing icons Check the result of `cui_icon_named` or `cui_icon`: `CUI_ICON_NOT_FOUND` means no host SVG or embedded asset was available; no icon is painted. A successful `cui_icon_set_name` only selects a catalog source and does not guarantee that its SVG is embedded. Check `cui_icon_prepare` (or the widget call) as well. For example: ```c cui_icon_error error = cui_icon_named(ui, 42, &theme, cui_string("mail"), (cui_icon_options){0}); if (error != CUI_ICON_OK) { /* Application policy: log error, report it in debug UI, or paint a fallback. */ } ``` Use `cui_icon_catalog_default` to inspect the default bundle, provide a theme loader for other names, or enable the full bundle. CUI does not print diagnostics implicitly; applications retain control of logging and fallback presentation. ## Numeric box styling Use `options.style` for uniform/per-edge padding, borders, backgrounds, radius, opacity and clipping. Padding does **not** inset SVG paint: the frozen upstream SVG paints its full final border-box bounds. Numeric width/height constraints apply before a final minimum of the padding-plus-border sums. For example, a 16px Icon with 24px padding on each edge occupies and paints a 48px square. Padding 4px leaves that same 16px Icon's size and paint unchanged. ```c cui_box style = {.padding = 4, .max_width = 32}; cui_icon_constraints limits = { .custom_min_width = true, .min_width = 20, .custom_max_height = true, .max_height = 0, }; cui_icon_options options = { .size = CUI_ICON_MEDIUM, .rem_size = 16, .style = &style, .constraints = &limits, }; /* During an active frame; state is retained until draw lists finish rendering. */ cui_icon_error error = cui_icon(ui, id, &theme, &state, options); ``` The explicit zero height maximum above is finally floored to the 8px vertical padding sum. Descriptor flags distinguish explicit zero from an unset constraint. Enabled descriptor maxima replace the corresponding positive legacy style caps; minimum constraints win if larger than a maximum. Explicit preset/custom Icon size overrides dimension options first, then constraints apply. Selected edge values and enabled constraints must be finite [0,4096], and final dimensions must not exceed 4096. Invalid numeric styling rejects before resource preparation. Style/constraint pointers are synchronous and never retained. Transforms change only SVG paint, around the resolved box center. Backgrounds, layout, hit bounds and opt-in named image semantics remain untransformed. Parent clipping and opacity continue to apply. You may submit one caller-owned Icon state repeatedly with different sizes/colors/transforms in the same frame: immutable raster versions remain valid together until renderer consumption. Collect only afterward. The context-owned named cache accepts the same canonical aliases as `cui_icon_set_name`, `cui_icon_query` and `cui_icon_asset`. The gallery's **Icon box styling** control demonstrates padding and numeric caps inside the existing Icon family. This batch does not add generic Styled margins, flex/grid/percentage constraints, automatic ambient text inheritance, full resvg features or a native raster-density key. DPR browser checks establish portable bitmap presentation, not density-aware native Icon rasterization. These remaining gaps preclude a full-family parity claim. ## Owned bridge resources The unreleased C bridge has an additive app-owned resource group with copied SVG/maps/bitmap utilities and explicit size/version negotiation. See [the resource contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_ICON_RESOURCES.md) before use. Root strict integration and 15 targeted headless checks pass. It does not yet add configured Icon/Badge rendering or Python, JS/TS, Go or Rust resource facades; existing named Icon builders remain. --- ## Icon accessibility and source audit Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/ICON_ACCESSIBILITY.md # Icon accessibility and source audit Frozen reference: upstream kit commit `87d10ae5e1299d1be18670a37570c5402f952e34`, `crates/component/src/icon.rs`. The reference Icon itself declares no accessible name, role, focus or input behavior. Existing CUI icons remain decorative by default. CUI adds an optional `accessible_name` application label: a nonempty label submits a noninteractive `CUI_ROLE_IMAGE` semantic with the icon's layout bounds, no focus and no Tab stop. `decorative=true` suppresses that semantic, including when a name was supplied. Asset names, paths, SVG title elements and raw SVG bytes are never used as labels. An empty source may still be intentionally labeled; its semantic uses layout bounds although it paints no SVG. Parent inert/layout-only behavior remains Core's. The audit covered all reference branches: - Legacy and full-catalog names convert to an Icon path; entity view constructors build the same source. CUI retains catalog/path APIs and context-owned named cache. - Default/empty path, path replacing data and data replacing path are handled by existing owned source state. Data is copied; masks are immutable across source replacements until collection after renderer completion. CUI does not expose Rust Entity or Arc cloning; initialized state must not be copied. - `same_layout` excludes source/color/transform. CUI layout uses the resolved numeric border-box size; transformation changes absolute paint bounds rather than semantic size. - `into_svg` inherits text size unless either style dimension exists; explicit size replaces both dimensions. Existing width/height/custom flags preserve these rules, including an explicit zero and a missing opposite dimension. - Presets use .75/.875/1/1.5 rem. New positive `rem_size` separates rem metrics from inherited text size; zero keeps legacy theme-font-based preset scaling. Custom pixels, inherited text size, dimension overrides and design metrics retain their existing precedence. Explicit size wins over style dimensions. - Explicit text color overrides fallback. RenderOnce falls back to inherited text color; entity Render falls back to theme foreground. CUI's existing `custom_inherited_color` bridges RenderOnce scopes; omitting it selects theme foreground as the entity branch does. `custom_color` wins over both. SVG masks are tinted with this current color; the supported parser does not preserve a multicolor SVG palette. - Rotation and affine transformation replace one another via options. Existing center-relative transforms preserve layout and allow paint overflow. - Source `Styled` accepts generic refinements. New optional `style` supports Core box decoration (background, border, radius, clip, opacity, inert/layout-only, offsets), while explicit icon dimensions remain authoritative. Uniform or per-edge padding participates in the border-box sizing floor. SVG paint covers the complete resulting bounds, without a content inset. This does not reproduce arbitrary upstream flex properties, margins, every SVG feature or automatic ambient style inheritance. Callers supply inherited metrics/colors explicitly; no global ambient style stack is introduced. Validation of the new fields occurs before state preparation, cache allocation, layout or semantics. Decorative labels are ignored entirely, so they need not carry valid text. Nondecorative nonempty labels require a valid borrowed pointer. Core copies the label into frame storage; the `style` pointer is synchronous and not retained. Existing opacity normalization and source parser errors keep their legacy behavior. `tests/unit/test_icon_accessibility_source.c` checks actual draw tint/background, layout and semantic dimensions, color precedence, independent rem presets, explicit sizing priority, label privacy/decorative suppression, pointer/focus ineligibility, invalid preflight atomicity and owned custom-SVG replacement lifecycle. Existing icon tests cover catalog assets, raster geometry, affine transforms, parser limits, explicit-zero dimensions and loader caching. The the new test is registered in CMake and generated distribution headers include the API. ## Numeric styled bounds `cui_icon_options.constraints` optionally supplies `cui_icon_constraints` with explicit per-axis minimum and maximum flags. Zero is a valid explicit maximum. Unset descriptor maxima use positive `style.max_width`/`max_height`; zero legacy style caps remain unbounded. Minimum constraints win over maxima, then sums of padding and border edges floor the resulting axes. A cap smaller than the padding/border sum therefore does not shrink the final box below that sum. Explicit Icon size still replaces both style dimensions before constraints. The resolver runs before parsing/rasterization or semantics. It accepts finite nonnegative enabled constraints/selected padding/border edges up to 4096 and rejects a resulting dimension above 4096. Descriptor and style pointers are borrowed synchronously. These numeric constraints do not imply percentage, flex, grid, margin or automatic ambient style support. `tests/unit/test_icon_style_source.c` covers padding/border floors, numeric caps, explicit zero and conflicting min/max, full-box paint, unchanged named semantic bounds, aliases and immutable simultaneous raster versions from one caller-owned state. `tests/web/test_icon_style.py` compiles the assertion-enabled contract into a dedicated real-WASM fixture and checks visible software-rendered SVG pixels, clipping and named semantics at desktop/390 and DPR1/2. This is not a proof of resvg equivalence or density-aware native SVG rasterization. --- ## Input behavior and presentation Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/INPUT.md # Input behavior and presentation `cui_input_ex` combines the editor with an application-owned `cui_input_state` and options for size, width, placeholder, appearance, text alignment, disabled, readonly, required, invalid and an optional synchronous `cui_platform` clipboard interface. The convenience `cui_input` supplies defaults. Retained state preserves horizontal scrolling and pointer selection across frames. Applications own the editor and buffer. Single-line inputs paint a caret and a selected-text background, clip text to the viewport, and adjust horizontal scrolling to keep the caret visible. Pointer placement measures UTF-8 scalar prefixes using the same configured font measurement as layout. Shift-click extends selection and captured dragging continues across frames. Secondary buttons do not mutate selection. Measurement is based on logical text order; shaping clusters, bidi and grapheme boundaries remain separate unfinished work. The renderer paints one unbroken text node with a selection underlay, preserving the same text measurement across selection boundaries. The legacy multiline rendering path still lacks caret painting, pointer placement and vertical movement; use the independent Textarea module for its bounded multiline engine. The drawing-free `cui_base_input_ex` accepts a host-defined pointer-to-byte-offset callback and reduces pointer, keyboard, text and clipboard events in order. Readonly fields allow navigation, selection and copying while rejecting mutations. Disabled fields ignore input. Semantics carry readonly, required, invalid and multiline states. Validation flags are controlled by the application; this API does not infer validation rules. Control/Meta+C copies the selection; X removes it only after a successful copy; V validates and inserts the returned UTF-8 text atomically. Missing/rejected clipboard access reports `CUI_EDIT_CLIPBOARD_UNAVAILABLE`, preserving the text. Control/Meta+Z, Shift+Z and Y use bounded editor history. `cui_edit_apply_event` lets other compound inputs preserve their own event ordering. Browser clipboard permissions and asynchronous integration belong to the browser adapter; supplying the native synchronous interface does not establish browser clipboard parity or IME support. `tests/unit/test_input.c` checks UTF-8 clipboard round trips, copy failure, invalid paste, readonly and disabled behavior, semantic state, ordered undo/redo, variable-width pointer selection, captured dragging, all four themes, caret/selection draw geometry and horizontal scrolling. Its base-only target links core/base/editor without styled or theme objects. Existing editing property tests continue to exercise history and UTF-8 validity. `cui_input_paint` exposes presentation without reducing events or registering a second textbox semantic. Compound components can run their own reducer once and reuse the caret/selection appearance. `cui_input_viewport_id` and the drawing-free `cui_base_input_hit_test` geometry helper let their reducers share measured pointer positioning. Tests prove painting alone leaves queued edits untouched and composition inserts each character once. ## Source sizes and fixed-height centering `cui_input_options.size` defaults to `CUI_INPUT_MEDIUM` (zero), with SMALL, LARGE, XSMALL and CUSTOM choices. `cui_input_measure` exposes the exact renderer metrics before layout. Presets use `density` when positive, otherwise `theme.font_size / 16`: | Size | Height | Font | Horizontal padding | Vertical padding | Line box | | --- | ---: | ---: | ---: | ---: | ---: | | XS | 20 | 12 | 4 | 0 | 20 | | S | 24 | 14 | 8 | 2 | 20 | | M | 32 | 14 | 10 | 8 | 20 | | L | 44 | 16 | 12 | 10 | 20 | Custom size sets the height directly and font to `custom_size * .875`, with horizontal/vertical padding 8/2 at the selected density. A positive `height` refines the frame height; `custom_height` also allows exact zero. Invalid/nonfinite metrics are rejected before interaction. The horizontal text inset includes the one-pixel border when present. The source single-line child has a fixed 20px line height and its row frame centers it on the cross axis: Medium's vertical padding does not enlarge its 32px frame. Actual glyph measurement is centered inside that line box. Numeric and custom compound renderers can reuse this through `cui_input_paint`. `name` labels the semantic node and is no longer painted as a second row. This corrects the previous Input appearance. `no_appearance` suppresses the frame surface/border; `no_border` keeps the surface. Focus/invalid border colors remain separately controlled. There is no outer source focus shadow yet. `text_align` supports Start, Center and End. Both growing and fixed-width fields align text in the current layout pass. Selection uses `theme.selection` without changing the foreground, and the caret uses independent `theme.caret` with source height 85% of the line box. Disabled appearance uses input background at 20% alpha and muted foreground at 50% alpha. Source caret blinking, IME, shaping and native context menus remain separate gaps. Growing single-line inputs now align text through the current layout pass. Their inner content no longer uses a previous-frame viewport width as a minimum, so changing parent width or horizontal padding does not force a stale viewport size. Headless tests cover left, center and right alignment on the first frame and after shrink/grow transitions with changing padding; the regression fails against the previous implementation. Single-line inputs render both their value and placeholder as one unwrapped line, including when the host supplies only a measurement callback. The content viewport clips overflow; focused values scroll horizontally to keep the caret visible. A long placeholder does not increase the input height or wrap into extra lines. Growing single-line fields (`width = -1`) constrain long populated values to the resolved frame width on the first frame and after parent resizing. The outer and text-viewport clips remain active; InputGroup prefix/suffix segments retain their widths. An extra internal layout row provides this containment. Remaining resize limitation: horizontal scroll, caret/selection projection and host IME geometry can use the previous frame's viewport during a width change. A focused end caret may be clipped for the first shrinking frame, or retain excess scroll for the first growing frame; the next frame converges. Width containment does not fix that separate projection defect. See [the characterization and opt-in failing probe](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/INPUT_GROW_WIDTH.md). --- ## Optional Input regex acceptance Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/INPUT_REGEX.md # Optional Input regex acceptance The portable matcher is an opt-in synchronous whole-value gate in `cui_edit_apply_checked` and Base/styled Input `.matcher`. A zero descriptor preserves existing behavior and requires no Rust. Public `cui_text_match.h` contains only C11 types; any host/provider can implement its by-value begin/match/end operations. The source contract is upstream-component0.7.1 at `87d10ae5e1299d1be18670a37570c5402f952e34`: nonempty single-line candidate predicates run custom acceptance, token/number validity, then regex boolean matching, with short circuits. Empty values pass without predicates. A failing candidate rejects only if the previous visible value passes; an invalid old value can heal. Hard provider errors never become a false match or healing permission. Final formatting and secure presentation resource preparation happen before the lease or custom callback. IME UPDATE gates normalized unformatted composed text; COMMIT formats once and creates one Undo step. Replay, PRESENT, START/CANCEL and multiline edits do not invoke matching. Host COMMIT rejection ends the host session through the existing Base lifecycle; engine checked rejection preserves the prior prepared session. A nonempty candidate acquires one lease before the custom predicate; candidate and old evaluation share it. End runs exactly once before adoption, including rejection and hard-error paths. End failure is a hard error while document/history/selection/coalescing and the prior defined IME view remain unchanged. `CUI_EDIT_MATCHER` denotes provider FAILED; STALE and BUSY have separate appended error tags. Invalid provider result codes become INVALID_ARGUMENT. Existing same-model mutation and cache-getter guards cover begin/match/end; unrelated side effects and direct caller-buffer writes are outside protection. Declare the actual object and optional scratch extents. They must be valid, disjoint from each other and all known model, event payload, session, format and presentation storage. Ops live by value, avoiding a borrowed ops-table pointer. The descriptor is borrowed only during the checked call. A successful begin must publish a non-null lease; a failed begin leaves it untouched. No matcher descriptor or callback is retained in the model after return. Matcher-enabled single-line multi-selection/inline-token requests are explicitly unsupported; raw engine APIs and zero-matcher requests keep their existing behavior. This is partial Input parity, not a full-family claim. Portable proof: `tests/unit/test_input_matcher.c` covers lease order/counts, custom/mask/regex short circuits, empty/replay bypass, invalid-old healing, all hard errors, unsupported result codes, aliases, callbacks attempting model destruction/insertion, and IME update/rejection/commit/Undo. It passes strict C11 warnings and ASan/UBSan. Unchanged registered CTest passes155/156; the sole failure is expected stale generated distribution after public header/source edits. Root owns regeneration/registration. No global build files or distribution were edited. Registration needed: include the standalone public `cui_text_match.h` in header/package/amalgamation checks; register `test_input_matcher` linked to ordinary `cui`. Default Core/Base/Components must remain Rust-free. The optional provider is described in the follow-up section once its independent proof is frozen. ## Pinned optional provider `cui_regex.h` exposes caller-owned zero-initialized compiled and session handles containing opaque state/generation only. Compile copies the pattern and performs the **actual source RegexBuilder admission before** reduced capture-free runtime compilation. Flags cover Unicode (default on), case, multiline, dot-newline, CRLF, greed, whitespace, octal and custom byte line terminator. Explicit limits cover source size/DFA-cache/nesting admission. Zero options preserve source defaults: nest250, NFA10MiB and facade DFA-cache2MiB. Bounded adapter pattern/text limits default1MiB each and can be configured; resource errors are separate from false matching. Pattern/text are UTF-8 spans, including empty/NUL where supported by the provider; the editing model keeps its independent input restrictions. Create a session with a hard cache heap-byte budget; it owns the prepared runtime cache and retains compiled ownership. Destroying the compiled handle does not invalidate existing sessions. `cui_regex_matcher(&session)` borrows the public session extent/generation. Destroy/rebind while leased returns BUSY without mutation. Rebind prepares a replacement first; failed preparation leaves the session and generation intact. Success changes generation and makes old descriptors STALE; callers refresh their Input `.matcher`. Destroying a session leaves its caller-owned handle alive for stale-descriptor rejection. Generation allocation never wraps; exhaustion returns CAPACITY. The compiled/session handles must remain valid until operations finish; direct pointer tampering and unsynchronized concurrent access are outside the contract. ```c cui_regex compiled = {0}; cui_regex_session session = {0}; if (cui_regex_compile(cui_string("^[0-9]*$"), (cui_regex_options){0}, &compiled) == CUI_REGEX_OK && cui_regex_session_create(&compiled, 1024 * 1024, &session) == CUI_REGEX_OK) { cui_input_options options = {.matcher = cui_regex_matcher(&session)}; /* Keep session alive while rendering/reducing Input with options. */ (void)options; } /* After the last checked call: */ (void)cui_regex_session_destroy(&session); (void)cui_regex_destroy(&compiled); ``` Build the optional archive with `scripts/build_regex.py` and the pinned private toolchain/cache as described in `backends/regex/README.md`. Its `pin.json` and lock preserve exact source archive/patch/toolchain provenance. No Rust dependency is introduced into default builds. Default-OFF native Linux CMake/package integration, generated declarations and dependency notices are registered separately from the optional compiled archive. Measured provider proof uses its actual exported compile/session/begin/match/end API against source Regex1.13.1 across385 successful config/pattern combinations,63 equivalent compile rejections and58,520 matches. Every match makes zero allocator calls, including first use; all eight session allocation positions are forced to fail and restore tracked heap. Source captured-NFA admission limit rejection is explicitly retained even when reduced runtime could fit. Tests preserve the custom line-terminator LookMatcher configuration required for source semantics. Production code never logs text; test failure assertions use synthetic public fixtures. Native strict C tests cover 1,000 lifecycle loops, leased BUSY, atomic failed rebind, stale/destroyed handles, compiled-owner destruction, malformed UTF-8/options/span/aliases and output preservation. Actual composed styled Input covers typing/paste/cut/delete, Undo/Redo, empty/invalid-old healing, Unicode, readonly, secure masking, IME update/rejection/commit and stale-provider hard failure before custom acceptance. The standalone prebuilt consumer CMake harness passes3/3 CTests. C-side Core/engine/provider/control ASan/UBSan+leak checks pass; Rust itself is not sanitizer-instrumented (allocator-spy/leak accounting covers its tested fallible allocation boundary). `tests/web/build_regex_fixture.py` builds a real Core/Base/Components Input plus the optional Rust archive into a Zig0.16 WASI **reactor**; global gallery files are untouched. `test_regex_wasi.py` executes the composed C test entrypoint in Wasmtime49 after `_initialize`, with no `_start`. The same module runs in actual Chromium1208 (Playwright1.58). Its existing reusable secure proxy reads finalized Core owner/type/purpose/generation, and CDP `Input.imeSetComposition`/`Input.insertText` exercise real DOM composition through Core events to the CUI Input and provider. Browser assertions cover rejected candidate/provisional view preservation, commit exactly once, rejected host-end cancellation and following typing, Undo/Redo, masking, readonly proxy removal, and Greek Unicode matching. JavaScript performs no regex acceptance. Reproduce browser proof with `python3 tests/web/build_regex_fixture.py --library WASI_ARCHIVE --output FIXTURE`, then `uv run --offline tests/web/test_input_regex.py --fixture FIXTURE` and `uv run --offline tests/integration/test_regex_wasi.py FIXTURE/regex.wasm`. Provider oracle: use task-local cargo `test --offline --locked --release --manifest-path CACHE/source/Cargo.toml -- --nocapture --test-threads=1` after the build script. Native harness: configure `backends/regex` with `CUI_REGEX_LIBRARY` and `CUI_REGEX_CORE_LIBRARY`, build, run CTest. Optional provider/native/package/browser tests and both public headers are registered; the isolated browser fixture is separate from the production gallery story. PikeVM's prepared memory is bounded; execution is not deadline-bounded and may be slower than the source facade's adaptive engines for large/dense patterns. Pattern/NFA/cache/text limits control memory and accepted input size, not a guaranteed UI latency. The oracle/fault tests establish this boolean/resource slice; remaining Input contracts and other native platforms are separate work. ## Build and link the optional native provider Ordinary CUI builds require no Rust toolchain. The portable caller-provided matcher is available in the default C11 library. Enable the regex backend only when you need its Unicode regular-expression implementation. For the currently verified native Linux target, use an official Rust 1.85.1 prefix and build the separately pinned archive into a private cache: ```sh python scripts/prepare_regex_toolchain.py --cache build/regex-toolchain python scripts/build_regex.py --cache build/regex-cache --toolchain build/regex-toolchain/rust-1.85.1 cmake -S . -B build -G Ninja -DCUI_BUILD_REGEX=ON \ -DCUI_REGEX_LIBRARY="$PWD/build/regex-cache/target/release/libcui_regex.a" cmake --build build ctest --test-dir build --output-on-failure cmake --install build --prefix "$PWD/install" ``` The private preparation script verifies the pinned official manifest and both toolchain archives before extraction and installs into the specified cache with ldconfig disabled. The archive build script checks the compiler version and commit, archive checksums, lock and private cache patch before building offline. It does not install Rust or change global Cargo/rustup configuration. Obtain and verify the official toolchain against `backends/regex/pin.json`; the supplied installed prefix is caller-owned tooling. Compiler/target std must match. Native Windows/macOS package acceptance remains unfinished. Within this source build, link a CMake target against `cui::regex`. Installed consumers use `find_package(CUIRegex CONFIG REQUIRED)` and `target_link_libraries(app PRIVATE CUI::cui_regex)`, with `CMAKE_PREFIX_PATH` pointing to the installed prefix. The package carries the Core dependency and the Linux archive's system link dependencies. For a direct compiler invocation: ```sh PKG_CONFIG_PATH="$PWD/install/lib/pkgconfig" \ cc -std=c11 -Wall -Wextra -Wpedantic app.c -o app \ $(PKG_CONFIG_PATH="$PWD/install/lib/pkgconfig" pkg-config --static --cflags --libs cui-regex) ``` Include `cui/cui_regex.h`. Generated distribution headers also contain the matcher and regex declarations, but the optional compiled Rust archive remains a separate link dependency. Defining a distribution implementation macro does not generate the regex engine. The optional-regex CI job shares Pages' exact OS/architecture/checksum-pin cache key for only `channel.toml`, `host.tar.xz` and `wasi.tar.xz` under `build/regex-toolchain`. Every run still verifies all three inputs, extracts and installs the private toolchain, builds the provider offline, and runs all source and CUI checks. Installed tooling, extracted sources and compiled outputs are not cached. `tests/test_native_ci_cache.py` checks this policy offline. A completed baseline, [CUI run 39773195384](https://github.com/mattmezza/cui/actions/runs/39773195384) (22 October 2026), spent 44 seconds preparing this toolchain, 215 seconds building CUI in optional-regex and 154 seconds testing it. Native Linux GCC build/test steps took 293/218 seconds; Clang took 122/176 seconds. macOS native dependency builds took 110 seconds, followed by 196 seconds building CUI and 148 seconds testing. [Native binding run 39774911345](https://github.com/mattmezza/cui/actions/runs/39774911345) spent 104 seconds on native dependency download/configure/build/install and 178 seconds validating callbacks. These combined steps do not establish their download-only cost. No compiled dependency cache or skipped checks were added. Warm-cache savings have not been measured: checksum verification and installation still cost time, misses download normally, and cache transfer overhead can offset savings. Compilation and test costs remain. --- ## Optional Unicode regex Input gallery Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/INPUT_REGEX_GALLERY.md # Optional Unicode regex Input gallery The Input story's mode 9, **Unicode letters · regex**, uses the compiled optional provider and anchored pattern `^[\p{L} ]*$`. It accepts Unicode letters and ASCII spaces, including an empty value, and rejects digits and punctuation through CUI's existing candidate acceptance. JavaScript does not validate text. Default browser builds remain C11/Zig builds without Rust or a regex archive: ```sh python scripts/build_web.py --output build/web ``` `gallery_regex_available()` returns zero and the mode is visibly disabled as unavailable. The C mode setter also refuses mode 9 when no prepared provider exists. The other Input modes keep their existing behavior. To include the real provider, first build the pinned WASI archive using the optional backend instructions in [INPUT_REGEX.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/INPUT_REGEX.md), then pass it explicitly: ```sh python scripts/build_web.py --output build/web-regex \ --regex-library build/regex-wasi/target/wasm32-wasip1/release/libcui_regex.a ``` The archive must target wasm32-wasip1 and use the pinned backend/toolchain. `build_web.py` does not invoke Rust or silently download/build a provider. A missing archive or incompatible link fails the build. This path defines only the gallery's optional provider seam and exports availability in both builds. The story prepares its compiled expression and session outside UI frames after successful gallery setup. Pattern admission is bounded to 64 bytes, candidate text to 1024 bytes and session cache heap bytes to 1MiB. Failure destroys any partial session and compiled handle, leaving the option unavailable. Successful handles occupy stable global storage for the WASM instance lifetime; the matcher borrows that persistent session, not a stack handle. Candidate acceptance, IME, Undo and input error behavior are the existing Input/provider contracts. Selecting this mode produces a complete copyable C11 translation unit, including zero-initialized caller-owned handles, preparation, persistent-session drawing, failure cleanup and shutdown cleanup outside a matcher lease. The application must initialize successfully before drawing and retain its edit/state and session across frames. The copied unit is a portable API example; link the optional archive to execute it. Proofs: - `tests/test_selected_usage.py`: 270 complete strict C11 units across joined Button and Input modes, all 15 design choices and both disabled states. - `tests/web/test_selected_usage_gallery.py`: actual desktop/mobile clipboard equality and strict compilation, including mode 9 when the provider is linked; a default build asserts unavailable mode and exercises the other examples. - `tests/web/test_input_regex_gallery.py`: Wasmtime49 actual gallery initialization, typing and rejection with/without the provider (deterministic native-fallback metrics), followed by actual linked and default Chromium galleries, Unicode typing, rejected punctuation/digits preserving the committed value, accepted/rejected provisional IME text, one-step commit Undo/Redo and disabled no-archive mode at desktop/mobile widths. It uses finalized CUI text semantics and Chromium CDP events rather than a JavaScript acceptance substitute. Run the browser fixtures with their pinned Playwright environment, passing `--directory build/web-regex`, `--default-directory build/web`, and an optional `--chromium` path to the regex interaction fixture. The clipboard fixture takes `--directory` and `--chromium`. This demonstrates one real optional provider in the gallery. It does not complete Input or native provider/platform parity; backend packaging and general matcher contracts remain documented in the separate regex guide. --- ## Installed native text validation Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/INSTALLED_TEXT_VALIDATION.md # Installed native text validation Run on Linux with native FreeType, HarfBuzz and SDL3 development/runtime dependencies available: ```sh python tests/packaging/test_installed_text.py \ --artifacts /path/to/native-artifacts \ --font /usr/share/fonts/noto/NotoSans-Regular.ttf \ --rtl-font /usr/share/fonts/noto/NotoSansHebrew-Regular.ttf \ --build-dir /tmp/cui-installed-text ``` The artifact directory must contain exactly one Python wheel and one prebuilt npm `.tgz`. This test never installs packages, downloads dependencies or starts a window. It removes display variables, selects SDL's dummy driver, extracts only ordinary archive files/directories into a temporary directory and compiles the existing `sdk_text_fixture.c` against each package's headers and bundled `libcui_bridge.so`. No package source is rebuilt or substituted for those libraries. The canonical reference is built from this checkout with native text and bidi support. `--reference-build DIR` can reuse a matching canonical build containing `libcui_text.a`, `libcui.a` and `libcui_bidi.a`; the caller must ensure that build matches the source being validated. The shared fixture asserts contextual bidi geometry, invalid byte-range rejection, RTL runs, fallback faces, nonzero glyph IDs, selection/caret behavior and colored raster coverage. UNAVAILABLE results and missing RTL/fallback/color coverage fail its assertions. Choose a primary font without Hebrew coverage so the fallback assertion is meaningful. All printed fixture values must match canonical output using exactly the same fonts on the same host. Font, artifact and library SHA256 values are printed. Library hashes are checked against wheel RECORD and any provided build-info library SHA256 metadata; explicitly non-native metadata fails. This proves packaged C text behavior. It does not prove Python/Node wrapper text API coverage, package installation behavior, SDL rendering, GPU behavior or cross-host raster reproducibility. Run `scripts/test_binding_packages.py --native --require-prebuilt` separately for actual installed binding UI consumers under its dedicated invisible Xvfb display. --- ## Keyboard shortcut hints Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/KBD.md # Keyboard shortcut hints `cui/cui_kbd.h` adds `cui_kbd_ex` for a typed **single chord**, preserving the existing literal `cui_kbd` and byte-preserving `cui_kbd_format` APIs unchanged. It displays hints only: no shortcut registration, action lookup, sequence recognition, activation or global event dispatch occurs. The frozen source stores one Keystroke. Binding lookup takes the first stroke; several hints in its story are ordinary sibling components. The earlier “grouped shortcut rendering” manifest phrase does not identify a missing multi-shortcut source API. See the pinned [audit](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/KBD_SOURCE_AUDIT.md). Compose hints normally, as in this complete C11 draw function: ```c #include "cui/cui_kbd.h" bool draw_shortcut_hints(cui_context *ui, const cui_theme *theme, bool mac_symbols) { cui_begin_box(ui, 100, (cui_box){.row = true, .gap = 8}); bool palette = cui_kbd_ex(ui, 101, theme, (cui_kbd_stroke){.modifiers = CUI_MOD_META | CUI_MOD_SHIFT, .key = CUI_STR("p")}, (cui_kbd_options){.mac_symbols = mac_symbols}); bool escape = cui_kbd_ex(ui, 102, theme, (cui_kbd_stroke){.key = CUI_STR("escape")}, (cui_kbd_options){.outline = true, .mac_symbols = mac_symbols, .accessible_name = CUI_STR("Escape key")}); cui_end_box(ui); return palette && escape; } ``` Call inside an active frame. The host selects platform convention explicitly: CTRL/ALT/SHIFT/META display in that order, as text with `+` or macOS symbols without separators. `META` is Win or Command. Host parser aliases such as `secondary` must be resolved by the host; the component does not guess a keymap. ASCII first letters become uppercase; known lower-case key names map to source labels, including Esc, Enter/⏎, Backspace/⌫, Delete/⌫, arrow names/symbols and Page Up/Page Down. Function keys and literal `+`/`-` work without a parser. `cui_kbd_format_stroke` returns required bytes **excluding NUL**. It accepts NULL output for size queries and capacity0 without writing; positive capacity always NUL-terminates valid output within that capacity, truncating only complete UTF-8 scalars. Invalid input returns SIZE_MAX and leaves the output unchanged. Input key must be nonempty strict single-line UTF-8, at most128 bytes, with no embedded NUL or ASCII control characters. Unknown modifier bits are invalid. The four existing portable flags are the only accepted mask. The longest result is147 bytes, so internal required-count arithmetic cannot overflow. The output buffer may overlap the input key. Non-ASCII casing is preserved: full Unicode uppercase conversion from the Rust source is not implemented. Zero options draw the source-shaped muted pill: muted foreground/background, 12-unit text at16-unit rem, horizontal padding4, vertical padding2, minimum width20 and half theme radius. Outline adds a1-unit border and uses the theme background. `plain=true` wins over outline and renders text at the theme font and color without pill padding/border/minimum. CUI maps rem to `theme.font_size/16`; the font must be finite(0,512], radius finite/nonnegative. It does not provide arbitrary upstream Styled modifiers or a general inherited parent text-style stack. CUI solid theme tokens are the supported palette; this is not proof of every upstream theme/background representation. Hints are noninteractive LABEL semantics, excluded from tab traversal. The accessible name defaults to formatted text; an explicit name overrides it. Names must be strict single-line UTF-8 up to1024 bytes, without embedded NUL or ASCII controls. Invalid arguments fail before layout or semantics. Input strings and local formatted output are copied into Core frame storage at submission and survive through that frame's renderer consumption. No retained component state, allocator or cleanup is required. Ordinary row composition fits its contents; it does not automatically turn a shortcut list into a responsive wrapping grid. For narrow help panels, let the owner split rows using the host's available-width/layout policy. Joining multiple strokes into one sequence or looking up host Action/context/focus/global bindings remains outside this API. Do not promote full Kbd parity from these formatting and presentation additions. The standalone worker fixture compiles the exact example and tests named-key formatting, all output capacities, UTF-8/control rejection and overlap, normal/ outline/plain geometry, theme scaling, actual software fill pixels, text draw colors, semantics and ordinary sibling composition. It checks legacy helpers remain unchanged. Text rasterization is not claimed by portable pixel tests. New sources require root-owned canonical source/test registration and matching SDK/consumer-resource regeneration before distribution. Worker validation used strict C11 Release (`-Wall -Wextra -Wpedantic -Werror`): `kbd_source` and the existing `content` regression passed through the private headless wrapper. The exact guide example compiled against the real header, and strict C++11 header syntax passed. No native windows or browser were opened. ```sh cmake -S tests/fixtures/kbd -B /path/to/private-build -G Ninja \ -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_FLAGS='-Wall -Wextra -Wpedantic -Werror' cmake --build /path/to/private-build --target test_kbd kbd_guide test_content python scripts/test_local.py --build-dir /path/to/private-build -- -R '^(kbd_source|content)$' ``` --- ## Source label contract Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/LABEL.md # Source label contract The additive `cui_label.h` API complements the legacy `cui_label` plain text wrapper. `cui_label_prepare` produces caller-owned display bytes and sorted nonoverlapping color spans. `cui_label_source` copies those bytes into Core frame storage. Initialize options to zero and provide `primary`. `has_secondary` adds exactly one ASCII space even if either string is empty. Secondary text and its preceding space use theme muted foreground. Matches override either foreground with theme info (the semantic blue). `custom_color` changes primary foreground. A supplied `color` is inert unless `custom_color` is true; zero initialization uses theme text. Caller-selected error presentation uses `custom_color = true` and `color = theme.danger`. Secondary text stays muted and matches override either foreground, including matches that cross the primary/secondary separator. Masked bullets use the selected base foreground uniformly and never emit secondary/highlight spans. Font size, weight, italic, monospace and family are forwarded; line height defaults to 20 logical pixels, matching the source's 1.25rem at its 16px root size. The frozen `crates/component/src/label.rs:53-59,61-91,192-215` has no disabled or error state flags; it accepts inherited Styled text color. Its website error example (`website/component/label.md:231-233`) selects `theme.destructive` through `.text_color(...)`. C's caller color option covers that presentation rather than adding an invented validation/disabled API. Required/optional markers likewise remain ordinary secondary text. `test_label_source` checks prepared spans and real Core draw commands for default and caller error foregrounds, muted secondary text, a Unicode highlight crossing the separator, alpha preservation, default theme font and 20px line metrics, and masked display/semantic privacy with a custom color. Matching uses Unicode 17.0.0 default, locale-independent lowercase, including one-to-many mappings and contextual Greek final sigma. Full matching finds all overlapping occurrences; prefix matching considers only the start. Empty matches are inert. Matching performs no normalization or full case folding: sharp-s and SS are distinct. Lowercase positions map back to original UTF-8 scalar boundaries, so expanding mappings and byte-width changes cannot split a scalar or shift later matches. This deliberately repairs the source implementation's reuse of lowercase byte offsets and original search length, which can miscolor or split Unicode text. A match covering part of an expanded lowercase scalar colors that whole scalar. Masking emits one U+2022 bullet per Unicode scalar of the combined text, including the separator. It emits no highlight spans, and neither draw paragraph nor optional semantic name contains original bytes. Inputs remain owned by the caller; this API is not a secret-storage or memory-erasure facility. Optional `semantic_id` creates a label node; `control` sets Core controls and focus_target relations. Masked nodes are marked secret. Applications set the controlled widget's `labelled_by` relation when they need that reverse accessibility relation. All input strings require strict UTF-8. Prepare rejects invalid arguments, overflow, allocation failure and insufficient capacity without changing text, spans or the result structure. Output buffers must not overlap each other or input strings. The text output is length-delimited with no NUL terminator. Span capacity is bounded by Core's 4096 span maximum. Renderer failures are returned; an allocation failure inside Core after beginning an optional semantic box can leave an empty box. Rendering now submits a complete colored text paragraph through Core, wraps at its current-frame parent width, and stacks hard paragraphs and empty lines. CRLF is one break; LF, CR, NEL, paragraph separator and the Core information separators also start new paragraphs. U+2028 starts a visual line while preserving the full original bidi paragraph for shaping. Spans crossing either explicit or automatic line boundaries are clipped and rebased to each draw command's original UTF-8 paragraph. Blank and trailing lines contribute their configured line height. `no_wrap` disables automatic wrapping while retaining explicit line breaks. Masking occurs before line layout, so original paragraph separators become bullets and reveal neither source text nor original newline structure. The frozen Label source uses StyledText from its pinned upstream-pre 0.3.8 dependency. That measured layout chooses the definite current parent width when normal white space is enabled. The additive Core paragraph API supplies that available-width behavior without relying on previous-frame label bounds. The prior single-line and hard-separator rejection restrictions are removed. Core now uses the pinned measured wrapping candidates, including punctuation, Unicode word ranges and fallback inside long tokens. Trailing spaces remain in the preceding visual row. Unicode 17 graphemes and provider shaping clusters are kept intact during fallback; this deliberately strengthens the source's individual-glyph fallback. See [the wrapping contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/UNICODE_WRAP.md) for the exact policy, resource limits and measurement-only host limitations. `alignment` supports physical left (default), center and right per visual row, using current-frame available width. See [the alignment contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TEXT_ALIGNMENT.md). Arbitrary upstream style refinement remains incomplete. Root-relative rem scaling must be supplied through line_height when the application's root size differs from 16. The legacy wrapper remains unchanged. The general `cui_text_paragraph_colored` Core API validates all UTF-8 and full-text color spans before publication. Invalid input and conservative storage/element preflight failures publish no layout. Per-draw clipped spans require bounded frame storage during final layout; exhaustion empties the draw list under Core's usual capacity-error contract. The pre-existing unwrapped contextual APIs retain their validation rules. `test_contextual_wrap_source` covers paragraph-relative spans, Unicode separators, empty lines, current-frame reflow, measurement identity and preflight failures. With `CUI_TEST_WRAP_RENDERER` it additionally renders colored wrapped text through the real software font renderer and verifies a copied draw snapshot after frame invalidation. ## Pinned Unicode provenance Generated tables in `src/components/cui_label.c` derive from official Unicode 17: - https://www.unicode.org/Public/17.0.0/ucd/UnicodeData.txt SHA256 `2e1efc1dcb59c575eedf5ccae60f95229f706ee6d031835247d843c11d96470c` - https://www.unicode.org/Public/17.0.0/ucd/SpecialCasing.txt SHA256 `efc25faf19de21b92c1194c111c932e03d2a5eaf18194e33f1156e96de4c9588` - Vendored `third_party/unicode/17.0.0/DerivedCoreProperties.txt`, pinned by its adjacent manifest, supplies Cased and Case_Ignorable properties. Generation reads field 13 (simple lowercase mapping) from UnicodeData, overrides with unconditional SpecialCasing lowercase mappings, and extracts the two sorted property range sets. Final_Sigma is implemented contextually; language-dependent Turkish, Azeri and Lithuanian conditions are excluded by default lowercasing. The following notice applies to these generated Unicode data tables: UNICODE LICENSE V3 COPYRIGHT AND PERMISSION NOTICE Copyright © 1991-2026 Unicode, Inc. NOTICE TO USER: Carefully read the following legal agreement. BY DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE. Permission is hereby granted, free of charge, to any person obtaining a copy of data files and any associated documentation (the "Data Files") or software and any associated documentation (the "Software") to deal in the Data Files or Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, and/or sell copies of the Data Files or Software, and to permit persons to whom the Data Files or Software are furnished to do so, provided that either (a) this copyright and permission notice appear with all copies of the Data Files or Software, or (b) this copyright and permission notice appear in associated Documentation. THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA FILES OR SOFTWARE. Except as contained in this notice, the name of a copyright holder shall not be used in advertising or otherwise to promote the sale, use or other dealings in these Data Files or Software without prior written authorization of the copyright holder. --- ## Native macOS applications Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MACOS.md # Native macOS applications CUI's portable library has macOS CI evidence. The native workflow below adds the SDL3/text adapters and a `.app` starter. A configured CI job or a successful Linux build is not evidence that the app runs correctly on macOS. Record the revision, Mac architecture, macOS version, dependency receipt and results when validating. ## Build on your Apple Silicon Mac Install Xcode Command Line Tools, CMake 3.20+, Python 3, Git, pkg-config and a build tool. Use an arm64 terminal (`uname -m` should print `arm64`), rather than a Rosetta x86_64 shell. The commands below use Makefiles, so Ninja is optional. Run from the repo. Dependency sources are pinned in `tools/native-deps/CMakeLists.txt`; this avoids relying on changing Homebrew library versions. The initial build needs network access. SDK and compiler remain your local Xcode tools. ```sh cmake -S tools/native-deps -B build/macos-deps \ -DCMAKE_BUILD_TYPE=Release \ -DCUI_DEPS_PREFIX="$PWD/build/macos-prefix" cmake --build build/macos-deps --parallel 4 python3 tests/test_native_deps.py --prefix "$PWD/build/macos-prefix" PKG_CONFIG_PATH="$PWD/build/macos-prefix/lib/pkgconfig" \ cmake -S . -B build/macos \ -DCMAKE_BUILD_TYPE=Release \ -DCUI_REQUIRE_NATIVE=ON -DCUI_BUILD_NATIVE_STARTER=ON \ -DCUI_HEADLESS_NATIVE_TESTS=ON -DCUI_BUILD_CPP_EXAMPLE=OFF \ -DCUI_TEST_FONT="$PWD/third_party/inter/Inter-Regular.otf" \ -DCUI_MACOS_DEPENDENCY_LICENSE_DIR="$PWD/build/macos-prefix/share/licenses" cmake --build build/macos --parallel 4 python3 scripts/test_local.py --build-dir build/macos cmake --install build/macos --prefix "$PWD/build/macos-installed" ``` The installed starter is `build/macos-installed/cui_native_starter.app`. Installation deploys non-system dynamic dependencies into the bundle on a native Mac, then applies and verifies ad-hoc development signatures without a signing identity or keychain. Inspect installation output and test the installed app away from the build prefix before distributing it. The build-tree bundle still references build libraries. `CUI_REQUIRE_NATIVE=ON` makes missing native dependencies a configure error instead of silently building only portable targets. The bundle includes pinned Inter regular/bold fonts and their license. The starter locates its default regular font relative to its executable, independent of the launch directory; `--font PATH` overrides it. The larger starter currently uses the regular face; bundling the bold face does not automatically register a bold style. An application icon and your own bundle identifier/branding are application work. See `examples/native_starter/README.md` for copied projects. ## Automated checks without desktop windows `CUI_HEADLESS_NATIVE_TESTS=ON` forces the dummy SDL video driver and software renderer for registered CTest tests. GPU checks cannot be enabled in this mode. Use `scripts/test_local.py`, which recognizes this configuration on macOS and preserves CTest's exit code. This exercises native adapter services without validating Cocoa windows or Metal. Some shaping tests need additional distinct family/Hebrew/Arabic font fixtures and can report skips; inspect the test output. Do not treat skipped coverage as a pass. A bounded headless starter capture can additionally verify packaged resources: ```sh SDL_VIDEODRIVER=dummy SDL_RENDER_DRIVER=software \ build/macos-installed/cui_native_starter.app/Contents/MacOS/cui_native_starter \ --frames 3 --capture "$PWD/build/macos-starter.bmp" ``` ## Manual Mac acceptance These are intentional interactive launches, outside automated tests: ```sh open build/macos-installed/cui_native_starter.app ``` Check the installed app from Finder and a different working directory. Verify: - Navigation, editable settings, keyboard focus, shortcuts and clipboard. - Window close/minimize/maximize/fullscreen behavior and native traffic lights. - Rendering and text at Retina scale, resizing, and moving between displays. - Input-method marked text, candidate placement and committed text. - System appearance changes, sleep/resume and relaunch. - Launch with the dependency prefix unavailable, proving deployed libraries and resources are sufficient. Use a copied bundle on another Mac for best evidence. Record failures rather than assuming SDL's platform support proves CUI behavior. The dedicated SDL_GPU adapter still lacks Metal shaders. Native macOS AX/VoiceOver integration remains unfinished and requires separate implementation and acceptance; this starter workflow does not establish accessible production-app support. ## Distribution and cross compilation The installed app is a development artifact. Choose a deployment target and architecture policy, add branding, and establish Developer ID signing, entitlements as needed, notarization and release testing before public release. Dependency fixup changes Mach-O files; sign after deployment, including nested libraries. No signing identity or notarization credentials are requested by these build scripts. Ad-hoc signatures are for local development; [Apple’s distribution signing guidance](https://developer.apple.com/documentation/xcode/creating-distribution-signed-code-for-the-mac/) describes the separate release identities. Universal apps require every dependency and executable to include the same architecture slices; this workflow starts with one architecture. See [Linux to macOS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MACOS_CROSS.md) for the cross-toolchain workflow. Cross-built artifacts still require validation on a Mac; local Linux tests cannot execute Mach-O binaries or establish Cocoa/Metal behavior. --- ## Linux to macOS native starter Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MACOS_CROSS.md # Linux to macOS native starter This is a caller-provisioned cross-build path, not an SDK downloader or a self-contained macOS release pipeline. No Apple SDK or OSXCross installation is bundled. Without those inputs only the host-side guard tests can be validated. The Linux build does not establish macOS runtime, graphics or accessibility parity. ## Provision the inputs 1. Build [OSXCross](https://github.com/tpoechtrager/osxcross) on Linux using an explicitly selected full Git commit and record that commit, compiler/linker versions and build options in your build provenance. Obtain an Apple SDK under its applicable license, following the upstream [SDK instructions](https://github.com/tpoechtrager/osxcross/blob/master/README.SDK.md). Record the SDK version and archive SHA-256. This repository deliberately does not select or download someone else's SDK or a floating toolchain revision. 2. Choose one architecture (`arm64` or `x86_64`) and deployment version. ARM64 requires macOS 11.0 or newer; the deployment version must not exceed the SDK version. Use a separate build directory and dependency prefix per architecture. 3. Cross-build and install **macOS** SDL3 (>= 3.2), FreeType and HarfBuzz into an absolute prefix such as `/opt/cui-deps/arm64`. Pin and record source revisions or archive hashes for every dependency and its transitive dependencies. Use the same compiler, SDK, architecture and minimum macOS version for all. Disable dependency examples/tests and optional platform backends you do not need; never run configure-time target executables on Linux. The repository's Linux packages and Linux AccessKit archive cannot be reused. The pinned dependency builder in this repository installs shared SDL3, FreeType and HarfBuzz and their license files into a dedicated target prefix: ```sh cmake -S tools/native-deps -B build/macos-deps -G Ninja \ -DCMAKE_TOOLCHAIN_FILE="$PWD/cmake/toolchains/macos-osxcross.cmake" \ -DCUI_DEPS_PREFIX="$PWD/build/macos-prefix" \ -DCUI_MACOS_CC=/opt/osxcross/target/bin/arm64-apple-darwin24-clang \ -DCUI_MACOS_SDK=/opt/osxcross/target/SDK/MacOSX15.sdk \ -DCUI_MACOS_PREFIX="$PWD/build/macos-prefix" \ -DCUI_MACOS_ARCH=arm64 -DCUI_MACOS_DEPLOYMENT_TARGET=11.0 cmake --build build/macos-deps --parallel 4 ``` Use `--prefix "$PWD/build/macos-prefix"` in the starter helper below when using this builder. It forwards the toolchain and target settings into each dependency. For CMake-based dependency builds, reuse `cmake/toolchains/macos-osxcross.cmake` with the five `CUI_MACOS_*` values shown below and an absolute `CMAKE_INSTALL_PREFIX`. HarfBuzz/FreeType bootstrap and feature choices depend on your selected pinned releases; provision their complete transitive closure. Supply `sdl3.pc`, `freetype2.pc`, `harfbuzz.pc` and transitively required `.pc` files under `/lib/pkgconfig` or `/share/pkgconfig`. Their absolute include/library paths must point to your macOS prefix, never Linux `/usr`. Use shared dependencies for this helper; fully static builds may need additional private link flags and are not automatically supported. Stage dylibs separately and adjust install names/rpaths for redistribution on macOS. ## Configure and compile ```sh python scripts/macos_cross.py \ --cc /opt/osxcross/target/bin/arm64-apple-darwin24-clang \ --sdk /opt/osxcross/target/SDK/MacOSX15.sdk \ --prefix /opt/cui-deps/arm64 \ --arch arm64 --deployment-target 11.0 \ --build-dir build-macos-arm64 ``` Replace the illustrative compiler/SDK paths with your actual installation. The helper requires host CMake, Ninja, Python and pkg-config. It verifies SDK layout and target dependency metadata, clears common host compiler/pkg-config overrides, configures with native adapters required, disables SDL fetching and the C++ example, and builds only `cui_native_starter`. `--configure-only` stops after configuration. Use a fresh directory when changing compiler, SDK or architecture. The equivalent toolchain parameters for dependency builds are: ```text -DCMAKE_TOOLCHAIN_FILE=/absolute/path/to/cui/cmake/toolchains/macos-osxcross.cmake -DCUI_MACOS_CC=/opt/osxcross/target/bin/arm64-apple-darwin24-clang -DCUI_MACOS_SDK=/opt/osxcross/target/SDK/MacOSX15.sdk -DCUI_MACOS_PREFIX=/opt/cui-deps/arm64 -DCUI_MACOS_ARCH=arm64 -DCUI_MACOS_DEPLOYMENT_TARGET=11.0 ``` CMake searches target roots for headers, libraries and packages; host programs remain discoverable. pkg-config searches only the supplied target prefix, with no Linux fallback. This cannot repair malformed `.pc` files pointing outside the prefix: audit dependency metadata and actual link commands. The Apple linker is the final check that supplied libraries are compatible Mach-O artifacts. Do **not** run CTest in the macOS cross-build directory on Linux: it contains macOS executables. Host-only tooling checks are `python tests/test_macos_cross.py`. Transfer the resulting executable and required dylibs to an actual compatible Mac for launch, font, input, rendering and deployment validation. Developer ID signing, notarization, universal binaries and public distribution remain separate release work; a successful cross compile alone validates none of these. ## Deploy on your Mac The build produces `build-macos-arm64/cui_native_starter.app`. Transfer this bundle and the complete **target** dependency prefix to your Mac, preserving symlinks (for example, with a tar archive). On the Mac, with this checkout: ```sh cmake -DAPP=/absolute/path/cui_native_starter.app \ -DDEPENDENCY_PREFIX=/absolute/path/macos-prefix \ -P scripts/deploy_macos_bundle.cmake python3 tests/packaging/verify_macos_app.py /absolute/path/cui_native_starter.app ``` Deployment copies target dylibs, adjusts their install names using macOS tools, and applies ad-hoc development signatures. Developer ID signing is a separate release step. Validate away from the dependency prefix, then follow [Mac desktop acceptance](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MACOS.md#manual-mac-acceptance). A development bundle is produced; public release signing/notarization remain application work. --- ## Image and Attachment Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MEDIA.md # Image and Attachment The comparison is frozen to upstream-component 0.7.1 and its local source/docs snapshot. Image is a re-export of upstream's image element, rather than a kit-defined widget. Attachment is a composed, application-controlled presentation of file lifecycle. Image source descriptors distinguish embedded asset keys, file paths, URIs, encoded bytes and custom loaders. CUI supplies the portable host-loader boundary, not a decoder, filesystem reader or HTTP client. Assign a stable source identity; change it when the source or retry attempt changes. The host callback must reuse its request/cache. Resource success and failure are retained until identity changes or state is explicitly reset. Custom loaders are polled each frame and may supply a new frame collection. Source descriptor memory is borrowed for the callback. Ready frame arrays and pixels must remain alive while retained by state, and through completion of every renderer consuming their draw commands. A load returns Pending, Ready or Failed. Ready validates up to 4096 borrowed RGBA8 frames with positive dimensions, stride of at least four bytes per pixel, finite nonnegative durations and no addressable stride overflow. Pixels are straight alpha; changing them requires changing the revision. CUI keeps loading and failure replacement callbacks within the reserved image box. Identified pending images show the loading replacement after 200ms; unidentified images do not show it. A fast success skips that replacement. Failure callbacks do not initiate retries. Returned `next_wake_seconds` lets the host schedule delayed loading or animation. Call the update/render function when host loading completes. Image geometry supports centered Contain (default), Cover, Fill, ScaleDown and None. Cover and overflowing None crop the source, preserving real bitmap pixels. A zero dimension means automatic sizing: an explicit opposite dimension and ratio resolve it, otherwise decoded intrinsic dimensions resolve it. An explicit aspect ratio reserves height before decoding. Without reserved dimensions, decoding can change layout. Grayscale, opacity and independent corner radii are passed to the bitmap renderer. Informative descriptions create a passive semantic label; interactive image commands belong inside a real application Button or Link. Animation advances decoded frames only when identified, active and not reduced motion. Inactive/reduced-motion periods do not accumulate catch-up time. A zero frame duration uses a 10ms minimum to prevent an unbounded advancement loop. Frame selection is bounded by the supplied frame count even after long elapsed times. Attachment defaults to Complete, Medium and Horizontal. The application controls Pending, Uploading, Processing, Failed and Complete; CUI never starts an upload or mutates lifecycle state. Named sizes follow the reference rem geometry (at root16: 40/48/56/64px chip heights, 176/200/232/272px content widths and 28/32/38/44px media). Custom density scales Medium geometry from an explicit pixel base. Vertical cards without metadata are flush square media tiles; vertical metadata cards use a 120px default width and independently configurable media aspect ratio. Typed metadata retains ordering, inherits lifecycle unless explicitly overridden, and supports custom child callbacks. Typed children may override color/font size and supply Marker shimmer duration/spread/highlight/direction options. Uploading/Processing titles use Marker shimmer; Failed descriptions use destructive color. Known Uploading progress is clamped to 0–100, appears as a determinate media ring and horizontal bottom bar, and appends a rounded percentage to typed descriptions. Processing ignores known progress and remains indeterminate. Media uses real image rendering when a host loader/state is supplied. Custom media children and centered overlays compose existing controls. Image status scrims are 35% while in progress and 55% on failure. Stable identified cards may expose a pointer-only whole-card action, leaving focus and keyboard activation to real child controls. The actions cluster captures its gaps so pressing them does not arm the card. Remove is a 20px control with 6px upper/trailing overhang, visible on desktop hover and always on explicit touch mode. Failed retry appears over media and after the first typed description. Callbacks report actions; ownership, removing records and retry requests remain with the application. Keep states and borrowed child arrays alive through frame completion. Tooltip composition reuses the existing Tooltip and requires the caller to provide viewport and timing options. AttachmentGroup retains a horizontal scroll offset, or uses an explicit external scroll state. Its default gap is 12 and vertical padding is 4. Dominant horizontal wheel input updates it, while ties remain vertical for the parent chain. Optional 24px edge fades appear only while content is hidden, with independent 200ms cubic transitions and reduced-motion settling. Each fade uses 24 bounded strips and claims no pointer target. Retained bounds measure overflow on a follow-up frame. Current integration limits: no built-in raster/SVG decoding, remote transport, HTTP cache, shared/scoped decoded asset cache or encoded animation parser. Host adapters supply those; decoded-frame playback is implemented here. True font weight and automatic ellipsis are absent in the existing text primitive; metadata is clipped to a single line. The progress ring uses 36 bounded samples; the bottom bar samples rounded clipping with six strips. Remove/retry shadows and automatic content ellipsis are not implemented. Pending dashed borders are bounded samples rather than a general dashed-path primitive. Arbitrary source style builders are exposed as composition callbacks and explicit geometry, not a full upstream style language. These limits preclude a full-parity claim. Integration: compile `src/base/cui_media.c` and `src/components/cui_media.c` into the styled library. The independent base test needs only its test source, media base source and math, with `CUI_MEDIA_BASE_ONLY`; no core/theme implementation is linked. Styled code needs core bitmap commands, pointer-only semantic activation, focus-scope hover ancestry, Theme, content helpers/Tooltip, Marker, and scroll base. Each Attachment state is bounded by 128 metadata entries; Marker state is retained per entry so its tracked text bounds remain valid through frame completion. State may be heap allocated by the application to avoid large automatic objects. --- ## Message and MessageScroller Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MESSAGE.md # Message and MessageScroller Contracts were audited against the frozen upstream-component 0.7.1 Message and MessageScroller sources and website documentation in the local reference checkout. These components leave application message data, formatting and actions with the caller. `cui_message_options_default()` uses start alignment, width 480, avatar-row gap 8, vertical gaps 10 and metadata gap 4. Avatar content reserves at least 32 pixels of width and aligns to the bottom of the header/body stack. End alignment reverses that row. Footer content is outside that row and indents 40 pixels on the avatar side. Header/footer use muted 12-pixel text at the default theme font size and 12-pixel horizontal insets. A typed ghost Bubble anywhere in the body suppresses both default metadata insets; explicit ON/OFF wins. Arbitrary callbacks do not participate in typed Bubble inference. A message is passive by default; opt into `CUI_ROLE_LISTITEM` with an application name and stable ID when appropriate. Slots accept borrowed text or a rendering callback with available width, color, font size and alignment. Body slots may wrap an existing typed Bubble or render arbitrary children. Callbacks may create real interactive controls. Borrowed text, body arrays and callback users must remain valid through `cui_end_frame`. `cui_begin_message_group` opens a vertical container; pass gap 8 for the reference default. Caller supplies width and closes it with `cui_end_message_group`. Create a scroller with an explicit capacity, item count and estimated raw row height. Allocation is bounded at creation; capacity is 1–1,000,000 items and no operation grows it. Heights and spacing are finite and at most 1,000,000 pixels; estimates must be positive. `memory_bytes` reports retained allocation. State retains layout keys and heights, never message records. Destroy it explicitly. The application updates its collection and performs matching reset/splice/append/ prepend operations between frames. Splice ranges are half-open. Invalid ranges, capacity overflow and invalid geometry leave the model unchanged. Initial/reset position follows the tail. Appends follow only while that mode is active. Prepending and splicing preserve the surviving item anchor, including remeasurement of the previous last row's missing trailing gap. Scrolling to an item disables following even when the content fits. Scrolling to the end resumes following. Global remeasurement restores proportional position; selective remeasurement keeps the item anchor and cached height until its replacement is measured. Styled width changes request global remeasurement. Retained row bounds supply measurements on the next frame; explicitly invalidate selective ranges when application content changes. Scroller defaults are 480×320, horizontal insets 12, top/bottom padding 8, row gap 32 except after the final row, and 400 pixels of overdraw on each side. Rendering calls only this bounded visible range. Row callbacks receive the inner width and stable internal row ID. Do not mutate collection/state until frame completion. The owner has a focusable LOG role. Vertical dominant wheel events (vertical on ties), arrows, PageUp/PageDown, Home/End and the optional scrollbar update position. At scroll edges the normal core parent chain applies. Hiding the scrollbar does not disable these interactions. The jump button is enabled by default, named “Jump to latest”, and retains its built-in action when custom content/size is supplied. It fades with 200ms cubic ease-out by default, disables during exit, and exposes `next_wake_seconds` for host scheduling. Reduced motion and zero jump duration settle immediately. An optional 48-pixel bottom fade has its own 200ms transition. The renderer samples that fade with 32 bounded strips. Overlays need one initial bounds-tracking frame. The base composition/model and drawing-free scroller do not link theme implementation. The base UI needs core, virtual-list base, scroll base and math. Styled code additionally needs theme, content/Bubble and styled scrollbar code. Core must include LISTITEM/LOG roles, dominant-axis scroll routing, retained bounds and opt-in semantic container focus. Known differences remain: built-in Image, TextView and Attachment dependencies are absent and require application callbacks; font weight and true rounded image clipping are unavailable in the current primitives; avatar background uses the available surface token. Existing Bubble spacing is reused. Arbitrary source style refinements are represented by slots and geometry rather than a complete upstream style builder. Jump tooltips and a configurable button variant are not yet provided. The accessible jump name deliberately improves on the source's empty icon-only default. No full rendering or native dependency parity is claimed. --- ## Explicit Checkbox and Radio indicator IDs Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NAMED_SELECTION_INDICATORS.md # Explicit Checkbox and Radio indicator IDs The optional `_with_parts` functions name an existing indicator paint box without adding an input target. Existing Checkbox/Radio APIs keep their anonymous indicators and row IDs. Their public options/state structures are unchanged. ```c cui_selection_indicator_parts parts = {.indicator = indicator_id}; (void)cui_checkbox_ex_with_parts(ui, row_id, theme, cui_string("Receive updates"), &check_state, (cui_checkbox_options){0}, parts); /* After successful composition, target the square instead of the label row. */ bool styled = cui_element_set_shadow_preset(ui, parts.indicator, CUI_SHADOW_SM, (cui_corner_radii){3, 3, 3, 3}); ``` Keep stable, nonzero and distinct row/indicator IDs. Explicit descriptor0 is invalid; it does not select legacy anonymous rendering. Descriptors are values captured before callbacks. The indicator retains the existing projected size, style, glyph/custom-content callback, clipping and motion behavior. It owns no new semantic record, focus stop or pointer target. Disabled/checked/mixed state and source pointer-focus policy remain the chosen facade's existing contract. Checkbox offers named variants of ex, source, bool convenience and immutable events. Radio offers named ex and convenience variants; Checkbox-only fields in its aliased options remain ignored. Each reaches its original reducer once. The event result keeps its original request/activation counts and callback timing; calling both an old and a new facade for the same owner would submit it twice. RadioGroup has separate `_with_parts` and `_events_with_parts` entry points. Supply one descriptor per item, count equal to item count and at most64. Use stable IDs associated with item identity when reordering. Group/item/indicator full IDs must all be distinct. A zero-count group accepts NULL parts/count0 under its existing empty-group rules. The group copies all part IDs before its owner request and observer callbacks. Existing item-array borrowing and callback mutation restrictions still apply; the copied parts do not make item strings or other borrowed model storage owned. Group painting still uses one group reducer, not individual Radio reducers for every indicator. Local invalid descriptors/cardinality/full-ID duplicates reject before reduction, callbacks, semantics or layout, report INVALID_ACTION and leave model values unchanged. Bool returns retain their existing **changed** meaning; they are not validity or completed-rendering results. Event/group result.valid describes argument validation, not renderer capacity or final layout. There is deliberately no global identity reservation. A collision with another already submitted box, an internal conditional part, or a different full ID with the same folded Core identity is diagnosed during normal box submission. Base reduction and application callbacks may already have occurred. Such frame failure **does not roll back input or owner state**. Capacity/layout failures keep that same ordinary composition boundary. Check frame diagnostics, allocate unique IDs and do not infer collision safety from previous bounds or semantic lookup. Style callbacks remain confined to refinement. Indicator/content callbacks may compose balanced children under their existing contract; do not reuse owner/part IDs, recursively submit the same owner, free active model/context/resources or mutate borrowed item/theme/string storage. Changing external descriptor storage inside an owner callback cannot redirect the captured indicator ID for this call. Shadow lists use the existing copied eight-layer API after submission. Supply matching indicator radii yourself: Checkbox styles can change corners; Radio uses its circular size/2 caster. This is rectangular-box shadow styling with rounded corners, not an alpha-mask shadow around arbitrary glyphs. Ancestor masks/opacity, DROP/INSET phase ordering and renderer budgets remain in [ELEMENT_SHADOWS.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/ELEMENT_SHADOWS.md). Named composition uses existing nodes but registers additional explicit IDs and changes descendant auto-ID derivation in the opted-in branch. Legacy routes keep their original anonymous identity/capacity behavior. Re-submit named parts each frame; omission creates no retained paint target. No pure getter invents a named indicator for an old anonymous facade. These named entry points remain C composition APIs. The bounded [typed semantic target mapping](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_PART_SHADOWS.md) now uses the bridge's existing bool convenience routes for Checkbox/individual Radio and its separate RadioGroup owner route. That is not exposure of every C source/ex/events facade. Broader78-family part coverage, portals and browser/GPU proof remain pending; packaged C headers alone do not establish additional language support. --- ## Native text integration audit Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NATIVE_TEXT_INTEGRATION_AUDIT.md # Native text integration audit At integration/next18 `b291765`, native font shaping and explicit line geometry worked, but ordinary wrapping and editor geometry did not preserve that result. `tests/integration/test_native_text_geometry.c` reproduces four observable mismatches using supported Hebrew glyphs and an explicitly registered fallback face. The follow-up implements the unwrapped Input host geometry seam described in [INPUT_VISUAL_GEOMETRY.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/INPUT_VISUAL_GEOMETRY.md). The default executable now verifies fixed Input behavior and returns 0; `--audit` preserves the remaining Textarea and automatic wrapped-paragraph observations and returns 1. It returns 77 when optional native bidi or actual supported font fixtures are unavailable. ## Runtime evidence With Noto Sans as the primary and Noto Sans Hebrew as an explicit fallback: | Operation on `אבג` at size 14 | Original editor result | Native shaped result | | --- | --- | --- | | Caret at original UTF-8 byte 0 | x=0 | x=22.094, the visual right edge | | Hit at visual left edge | Input byte 0, Textarea byte 0 | byte 6, the logical end | | Select first Hebrew character, bytes 0..2 | Highlight x=0 | Highlight x=13.250, over the actual rightmost character | The current Input path matches all of these results when its geometry hook is configured. Textarea still produces the prefix-based results in `--audit`. These are shaped cluster edges, so no interior ligature/GDEF caret policy is needed to reproduce the mismatch. The Textarea IME input rectangle follows its incorrect prefix caret position as well. The test compares the actual painted selection rectangle, not just the underlying owner's selection state. The second fixture submits ordinary `cui_text("אבג 123 !")` in a narrow box. Core emits a wrapped `CUI_DRAW_TEXT` command containing `123 !`. Drawing that command through the renderer's actual native font entry point yields a raster identical to independently analyzing `123 !` as a new LTR paragraph. It differs from `cui_font_layout_line` on the original paragraph with scalar range 4..9: that wrapped line retains RTL paragraph context and moves punctuation to the other side of the number run. The command's independently analyzed paragraph level is 0; the original paragraph's level is 1. Before reporting gaps, the test independently shapes the Hebrew fixture using HarfBuzz with explicit RTL/script/language/cluster flags. It compares nonzero source glyph IDs, original byte clusters, glyph positions, and advance width. Ordinary native font drawing matches explicit layout rasterization and emits 110 nonzero pixel samples for this fixture. Thus this audit does not mistake missing-glyph tofu, an unshaped native measure callback, or a missing font for an integration defect. Exact coordinate/pixel values depend on the selected fixture; the comparisons derive expected values at runtime. ## Actual path through the code - `src/core/cui.c` installs `cui_core_measure`, which forwards to the host's styled measurement callback. The native examples register `cui_font_measure[_styled]`. Those native callbacks already shape bidi text; this is not a claim that they use unshaped metrics. - `cui_text` selects Clay word wrapping. The pinned Clay measurement cache measures word slices and spaces separately (`third_party/clay/clay.h:1717`). Core's text command conversion (`src/core/cui.c:1773`) copies the emitted line substring, size/style and bounds, but no original paragraph or line range. Merely switching the scalar font measurement implementation cannot restore context once that information is gone. - SDL3 (`backends/sdl3/cui_sdl3.c:517`), SDL GPU (`backends/sdl_gpu/cui_sdl_gpu.c:433`), Sokol (`backends/sokol/cui_sokol.c:594`) and software rendering (`backends/software/cui_software.c:272`) call `cui_font_draw_styled` per text command. The audit invokes this common entry point headlessly; it does not claim to open a GPU window or test GPU pixels. - The native font path correctly separates actual hard paragraphs and preserves U+2028 line context inside its own whole-string input (`src/text/cui_text.c`, `text_lines_create`/`text_paragraph_append`). It cannot reconstruct context already removed by Core or Textarea automatic wrapping. - The original Input hit testing (`src/base/cui_base.c:399`) binary-searched logical prefix widths and immediately returned byte 0 at the left edge. Its legacy fallback still does; configured unwrapped Input now consumes host geometry. Original Input paint and IME rectangles also used prefix measurements (`src/components/cui_components.c`, `cui_input_paint`). Textarea's public row-x/row-offset and pointer hit functions use the same monotone-prefix assumption (`src/base/cui_textarea.c:408`). - Textarea measures and paints each selected wrapped byte slice separately and draws one prefix-based selection span (`src/components/cui_textarea.c:150`). Caret painting, reveal, vertical preferred-x navigation and IME rectangles follow those prefix coordinates. It does not call the native cluster geometry APIs. The runtime test verifies row geometry, IME rectangle and actual selection paint on an unwrapped RTL line; the wrapped Textarea context loss follows the inspected slice submission, rather than a separate GPU test. The edit model continues to own valid UTF-8/grapheme selection and logical movement. This audit does not equate native shaped clusters with every editor grapheme or claim visual keyboard navigation already exists. ## Narrow next implementation ownership The reproductions justified two independent changes. The first is now implemented for unwrapped Input, with the explicit cluster-interior fallback limits documented in INPUT_VISUAL_GEOMETRY.md. The second remains pending. 1. Implemented: **unwrapped Input visual geometry** through a portable host callback seam rather than making Core depend on native text/font types. The implementation covers the geometry callback public/config seam in `include/cui/cui.h` and `src/core/cui.c`, its native implementation in `include/cui/cui_text.h`/`src/text/cui_text.c`, Input geometry plumbing in `include/cui/cui_base.h`/`src/base/cui_base.c` and Input painting in `src/components/cui_components.c`, with focused headless/native integration tests. Caret, pointer hit, selection rectangles, horizontal reveal and IME rect now use a retained session while measurement-only hosts keep their existing path. Exact shaped-interior offsets deliberately use the documented legacy fallback without changing logical selection. Textarea remains a separate follow-up. 2. Separately preserve **original paragraph plus chosen line range** through wrapping and renderer submission. Initial ownership requires Core text command metadata/layout, native text, and the SDL/GPU/Sokol/software text adapters plus source/raster regressions. The public metadata must remain portable CUI types. The existing `cui_font_layout_line` already accepts full paragraph context and selected scalar ranges; adapters should receive enough original information to use it. Re-shaping each emitted substring cannot satisfy the reproduced UAX9 line-context behavior. Word-breaking policy and capacity/lifetime contracts need explicit tests; font fallback alone does not fix the handoff. Full grapheme editing parity, interior ligature carets using optional GDEF, visual arrow navigation, multi-line affinity policy, OS font discovery and Unicode line-break parity remain beyond those narrow changes. The confirmed fixtures need none of those claims. The relevant existing primary models are [UAX9 line reordering](https://www.unicode.org/reports/tr9/tr9-51.html#Reordering_Resolved_Levels) and [HarfBuzz cluster semantics](https://harfbuzz.github.io/working-with-harfbuzz-clusters.html). ## Reproduction and validation ```sh cmake -S . -B build -G Ninja cmake --build build cc -std=c11 -Wall -Wextra -Wpedantic -Werror -Iinclude \ $(pkg-config --cflags freetype2 harfbuzz) \ tests/integration/test_native_text_geometry.c \ build/libcui_text.a build/libcui_bidi.a build/libcui.a \ $(pkg-config --libs freetype2 harfbuzz) -lm -o /tmp/cui-native-text-audit /tmp/cui-native-text-audit /tmp/cui-native-text-audit --audit # preserves remaining known gaps ctest --test-dir build --output-on-failure ``` Use `CUI_TEST_FONT` and `CUI_TEST_HEBREW_FONT` to select explicit supported fixtures; known Noto and DejaVu paths are tried when unset. The executable is not registered by this worker because CMake belongs to the integrator. Its default verifies fixed Input behavior; `--audit` still preserves four remaining Textarea/wrapping observations rather than declaring full native integration. Validation at this snapshot: portable warnings-as-errors native build and the new manual integration compile pass; existing CTest passes 92/93. The sole failure is the expected distribution regeneration check for changed Core/Base/ Components headers, which is integrator-owned. The enabled default passes using actual Noto fallback fixtures; `--audit` retains the four remaining Textarea/wrapping observations. ASan/UBSan report no runtime errors. The BIDI-off audit compiles/links and returns 77 with an explicit unavailable message. The follow-up changes only its assigned Input/geometry production files; no CMake or distribution output is changed. --- ## Node and TypeScript controlled Single/Range Slider Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NODE_SLIDER_MODEL.md # Node and TypeScript controlled Single/Range Slider Unreleased bridge-owned subset over [C V1](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_SLIDER_MODEL.md). Legacy `slider()` keeps scalar float autoacceptance and original CHANGE timing. This route does not export direct C Base/Styled state, arbitrary owned styles or motion structs. The [Rust subset](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/RUST_SLIDER_MODEL.md) has separate dynamic and matching bundled-static Linux1.99.1 proof; MSRV1.85.1 remains untested. Native numeric AT, typed SET/touch injection, V2 gradient adapters and vertical registered-scroll admission remain pending. Full Slider and all-language closure remain open. ## Complete authored applications [JavaScript](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/node/examples/slider-model.cjs) and [TypeScript](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/typescript/examples/slider_model.ts) define real labels, nested Row/Column controls, external owner storage, accept/reject policy, callback and composition. Their default programs construct windowless UIs, focus actual thumb geometry, submit keys and verify explicit full-pair owner acceptance and rejection. The JS example accepts `--single`, `--vertical`, `--reject`; `--native` uses SDL with `CUI_FONT_PATH` supplied manually. Automated native tests always use private Xvfb through `scripts/test_local.py`; browser tests remain headless. With [C11/CMake/Ninja prerequisites](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DEPENDENCIES.md), Python3, Node18+ and its N-API headers, build without native windows from the repository root: ```sh cmake -S bindings/node -B build-node -G Ninja -DCUI_BUILD_NATIVE=OFF cmake --build build-node --target cui_node_bindings export CUI_NODE_ADDON="$PWD/build-node/cui.node" node bindings/node/examples/slider-model.cjs node bindings/node/examples/slider-model.cjs --reject --vertical node bindings/node/examples/slider-model.cjs --single ``` No npm dependencies are needed for JS. For TS use an existing TypeScript compiler (verified locally with 5.8.3), without installing from these commands: ```sh python bindings/node/test/run-slider-model-types.py \ --tsc /absolute/path/to/typescript/bin/tsc --node /absolute/path/to/node \ --output "$PWD/build-node/slider-model-types" ``` This compiles readonly/discriminant/BigInt negative cases and executes the complete TS application. CMake registers it when `CUI_NODE_TSC_EXECUTABLE` finds an existing `tsc`; override that cache path if needed. Local proof is Linux, not a claim of verified packages/platform distribution or physical native AT. ## Owned authoring and receipts `slider_single(end)` and `slider_range(start,end)` return frozen discriminated values. `slider_config({...})` owns its domain, orientation (`horizontal` or `vertical`), layout (`fixed` or `parent`), rem/length, sourceGeneration BigInt, requests/readonly/reverseFill/reducedMotion/hideFocus flags. `slider_model(key, config,confirmed,text?)` authors kind81. Mount requires only Row/Column ancestry; the entire tree is preflighted before native node creation. Unsupported optional symbols fail explicitly rather than producing an old scalar substitute. Numbers retain double precision; geometry is checked float32. Every uint64 field uses BigInt, including epoch/source/config/frame/sequence, event targets/indices and pointer/device/accessibility IDs. Handles are checked uint32 number pairs. Invalid/nonfinite active values, invalid domains and lossy identity conversions reject. Parent layout ignores authored length and canonicalizes it to0; malformed native output with a nonzero inactive length rejects instead of normalizing. `.configure(config,pair)` replaces complete records atomically, retaining the C reducer for captured cancellation. `.set_value(pair)` replaces the same kind; `.get_value()`/`.get_config()` copy actual mounted values. `.disabled()` and `.label()` use existing policy/name calls. `.part_bounds(0..4)` reads ROOT/TRACK/ FILL/START_THUMB/END_THUMB actual completed geometry, or undefined for absence; thumb geometry is the outer rem box. Disabled track/fill remain, thumbs omit. `.presentation()` copies render status and absolute Core-clock/wake values, or undefined before observation. It certifies no renderer/AT success or V2 support. `app.enable_slider_requests(capacity=4096)` enables the independent bounded FIFO; typed trees enable lazily. Reenable is same-capacity only. `supports_slider_model()` requires the complete 16-symbol group, V1 support and all five exact record sizes. Old-only applications neither require nor enable this feature. `poll_slider_request()` returns one immutable owned request or undefined. Nested receipt/value/domain/input records are copied before leaving N-API and frozen; no C pointer or view survives into a user callback. Copied input records require zero numeric evidence when HAS_NUMERIC_VALUE is absent, including keyboard events and accessibility INCREMENT/DECREMENT. Explicit numeric SET evidence remains supported. Malformed records are rejected before a request or receipt authority is published; previously copied records stay valid. Copies stay readable after frames, removal, close or disposal. Keep the original returned receipt object: reconstructed/cloned numeric fields do not confer acceptance authority. Authority belongs to one matching App and loaded bridge image, not a process-global security namespace. Returned records do not retain the App/native handle. ## Timing and decisions `step_only()` steps without callbacks. Existing `step()` steps then dispatches; `run()` uses the existing native post-frame trampoline. Legacy callbacks always run first, then the typed independent FIFO. No global queue ordering is invented. `dispatch_slider_requests()` explicitly drains that FIFO; its count is popped records, including records with no registered handler. Existing legacy callback counts/timing stay unchanged. Do not duplicate side effects through both manual polling and callbacks. `.on_request(callback)` or null sets/releases a handler. Call `app.accept_slider_request(request.receipt, wholePair)` explicitly; another valid full pair may be accepted. Doing nothing rejects. Immutable current stays the submission-entry snapshot; requested intent evolves for repeated original-order inputs. Acceptance never emits legacy CHANGE or retroactively repaints. Already accepted effects are not rolled back if a later callback/frame fails. Callbacks may mutate external owner state, enqueue future work/input, accept, configure, remove or tear down. Nested step/step_only/run/dispatch reject during typed dispatch. Exceptions propagate outside C, reset the guard and leave later entries queued; the popped entry is not replayed or autoaccepted. Config changes can expire later copied receipts without changing their original metadata. Node preserves its existing teardown distinction: `close()` requests shutdown; `dispose()` destroys resources. Both stop typed dispatch before another native poll and release typed handlers. Removal prunes native queue entries and releases the new handler. Owner OS thread must remain alive through destruction; do not transfer handles/receipts between Workers, libraries or App instances. There is no temporary hide/reinsert contract. ## Proof limits Focused tests exercise actual Single/Range UIs in both axes, explicit acceptance and rejection, copied lifetime/teardown and protocol errors. Synthetic conversion fixtures are not UI evidence. Linux optional-group tests use a separate addon linked to an explicitly supplied actual pre-typed bridge; all 16 missing-symbol variants, support and size failures use tiny test providers over that old module. These historical tests register only with `CUI_NODE_SLIDER_OLD_LIBRARY`; ordinary current-library and synthetic copy tests do not need that artifact. Missing old fixtures are an omission, not a claimed compatibility pass. --- ## JavaScript/TypeScript localized TimeField Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NODE_TIME_FIELD_LOCALIZED.md # JavaScript/TypeScript localized TimeField Unreleased authoring over the integrated localized C bridge. Strict root C11 build and all 81 configured Node checks pass, including 20 localized checks, actual old/missing providers, real English/Arabic UI and TypeScript 5.8.3. See the [root receipt](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/validation/localized-facades-root.json) and retained [worker history](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/validation/node-localized-time-field-worker.json). The existing `time_field()` remains legacy kind 55. `localized_time_field()` is a distinct subclass using that same kind and the bridge-owned localized editor. Python and dynamic Go/Rust also have focused root acceptance. Static/package, native interactive and broader platform acceptance remain separate; these results establish no full 78-family parity. Complete authored UI sources are [JavaScript](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/node/examples/time-field-localized.cjs) and [TypeScript](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/typescript/examples/time_field_localized.ts). They nest English 24-hour and Arabic 12-hour widgets in Row/Column UI with real clear, read-only, disabled and bounds controls. Locale tokens are explicit values, not OS locale lookup. No foreign callback runs inside Core and no JS reducer exists. Call `app.supports_localized_time_field()` before opting in. The addon resolves all ten symbols as one optional group, checks version bit 0 and exact 616/80/64 native record sizes. Missing/partial/old providers leave legacy scalar authoring usable. `enable_localized_time_fields(capacity)` enables an immutable independent FIFO; 0 selects 4096. Mount preflight enables default capacity if needed and rejects unsupported or non-Row/Column ancestry before making any nodes. `localized_time_config()` returns a deeply frozen copy with explicit locale, cycle h23/h12, precision minute/second, inclusive same-day bounds, four segment names and nonzero uint64 `editGeneration` BigInt. Tokens are strict UTF8, no NUL, prefix-free and 1–16 bytes. Names are 0–64 bytes; empty chooses the C default. Minute bounds require seconds 0. `configure()` replaces the whole configuration; it commits the JS owner copy only after synchronous C success. Increase generation for locale/name/domain replacement that should reset unfinished editing. Identical owner echoes keep generation stable. `.time_value()` retains the existing range checks; values outside configured bounds are displayed invalid, never clamped. The binding's internal Buffers are explicit little-endian copies, **not** the C ABI's native-endian records. N-API converts every native uint32/uint64 field and string length individually in both directions, with exhaustive layout assertions. UTF8 byte arrays copy unchanged. No native struct pointer, borrowed Buffer view, mutable model/draft or external callback crosses the C call. Input/output buffers can be discarded or mutated after return without changing future C state. `on_localized_change()` receives immutable **already applied** previous/value, node slot/generation, BigInt frame, validation, rejection count and actual bridge frameStatus. Editor validation is exactly 0/3/4/5; EMPTY is never a completed frame status. Latest results use the seven explicit C status values and require queued-change count no greater than the changed flag; unchanged results are valid. Returning a value does nothing; do not accept/reapply it. Typed records use their own FIFO and do not duplicate generic time CHANGE events. `step()` dispatches after successful submission; `step_only()` leaves dispatch to the caller. After a failed step, explicitly poll/dispatch localized changes too: a later failure may follow an applied edit. A failed frame's latest-result getter stays unavailable until a healthy ordinary widget frame; clearing validation is not recovery or undo. `clear_validation()` preserves time/draft and owner-invalid. Polling consumes before callbacks. A callback exception never replays that record; later records remain queued and the dispatch guard resets in finally. Nested step/run/typed dispatch is rejected for that app. Setters/removal/close/dispose inside poststep callbacks are supported; teardown clears callback references and stops dispatch, and retained copied values remain safe after app destruction. Removal prunes unread C records; slot reuse cannot redirect an old observation. All calls remain serialized on the owning OS thread through destruction. No shared-WASM, native AT, IME or native Tab traversal support is claimed. The focused gates cover protocol poisoning/reserved/UTF8/BigInt boundaries, real English/Arabic queued input, disabled/read-only/bounds/clear, copied C ownership, callback error/return/reentry/lifetimes, an actual later Slider capacity failure, old/partial group fallback and compiled TS-authored runtime. These are focused fixtures backed by the worker receipt. Native automation must use the private-display wrapper, never the desktop. The frozen initial failures and fixture-only warmup/coordinate corrections remain recorded in that receipt. --- ## Opt-in source Notification motion Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NOTIFICATION_MOTION.md # Opt-in source Notification motion After initializing the caller-owned state, select source motion explicitly: ```c cui_notification_state state; /* entries, settings and host are application-owned. */ if (cui_notification_init(&state, entries, capacity, settings, host)) { state.motion_policy = CUI_NOTIFICATION_MOTION_SOURCE; } ``` Zero-initialized state and initialization retain `CUI_NOTIFICATION_MOTION_LEGACY`. Reinitialization resets this opt-in. Motion and `settings.shadow_policy` are independent: use SOURCE shadows as well when both source behaviors are wanted. No Theme, Core, Base lifecycle or renderer API is changed by this policy. SOURCE follows the pinned upstream-component 0.7.1 implementation at `87d10ae5e1299d1be18670a37570c5402f952e34`: | Transition | Duration | Translation | Opacity | | --- | --- | --- | --- | | Enter | 400ms | 96px outside the edge → 0 | 0 → 1 | | Exit | 200ms | 0 → 96px outside the edge | 1 → 0 | Top-left/center/right move upward outside the stack, bottom-left/center/right move downward, and left/right-center have zero translation. Elapsed time is mapped through CSS cubic-bezier `(0.25, 0.1, 0.25, 1)`, solving its x coordinate before sampling y. SOURCE uses the source's bounded eight-step Newton and 32-step bisection solver; LEGACY retains its existing six-step solver and 16px distance. Measured animated card bounds, custom content, interactions and copied shadow casters all follow the same translated card. The source locations are `crates/component/src/notification.rs:30–32,485–529` and `crates/base/src/animation.rs:14–64`. SHA-256 respectively: - `09010c94024ee6e2580ecf557d97dcf276512a52be8cf298e0936088df0afeca` - `b17a0e92d239c4f947373f6ebf699e3fde7c83f13e2f96e979ada8b823eef44d` Reduced motion samples the oneshot end state, matching upstream's `AnimationExt` contract and implementation at `upstream-pre-0.3.8/src/elements/animation.rs:78–80,407–413` (SHA-256 `117a4b1a580382b21accce30308f0480853c1e9372220566748dcb5f74d5793e`). Thus enter is immediately at rest and fully opaque; exit is immediately at its translated, transparent end state. Stack springs already snap under the existing reduced-motion setting. SOURCE requests the remaining lifecycle deadline instead of 16ms animation wakes. It does not invent immediate removal: the source ToastManager retains its 400ms/200ms transitions independently (`crates/base/src/toast.rs:234–266`). Presented results and close callbacks retain those deadlines. Autohide deadlines and hover/focus pause behavior are preserved. Render once per active UI frame through `cui_notifications_checked`, passing a stable overlay ID and monotonic finite owner clock. Unknown motion enum values fail before reductions, callbacks, output publication or UI emission. SOURCE also checks the initialized owner's fade phase and finite timing/visibility state. Existing shadow-policy validation and checked-render transaction limits remain as documented in [NOTIFICATION_SHADOWS.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NOTIFICATION_SHADOWS.md): later UI/frame/renderer errors cannot undo previously accepted host callbacks. No new borrowed buffers, sampler callbacks or resource lifetime are introduced. The effective SOURCE shadow opacity remains transition opacity to the fourth power, multiplied by independent stack visibility, then inherited Core opacity once. Motion does not change the two copied source layers or their quantization. Evidence: - `test_notification_source_motion.c`: all eight placements at five actual enter times, an intermediate exit, exact completion/removal boundaries, legacy compatibility, reduced deadlines/no animation redraw, close callback timing, independent shadow policies, invalid policy/NaN rejection and Software pixels distinguishing 96px source movement from the old 16px card location. The exact pre-change component source fails its new source-distance assertion; the external reproduction keeps the appended header solely to select that policy. - `test_notification_source_motion_sdl.c`: actual SDL Renderer OpenGL and software drivers, 32 controlled placement/enter/exit/scale frames per driver. Pixel capture happens before real Present; assertions abort rather than show modal ignore workarounds. A GNU/Clang native fixture needs `--wrap=SDL_RenderPresent`. - `test_notification_source_motion.py`: actual WASM component commands and Canvas pixels for 64 controlled enter/exit/placement/reduced cases at DPR1/2, including legacy/source position distinction. Independent double-precision Bezier inversion checks geometry; the shared raster independently checks composition. No wall-clock sleeps drive these transitions. Strict C11, scoped GCC ASan/UBSan and portable Wasmtime checks exercise the new headless fixture. The worker does not register global tests or regenerate headers; integrator regeneration is required for the appended state member. The browser fixture takes `--output` and optional `--chromium` arguments. This is a bounded motion slice, not Notification-family completion. Arbitrary source style refinement and renderer-native upstream AA/color/shader identity remain separate boundaries. Native GPU/Sokol source-shadow coverage is from the prior shadow slice; this motion fixture adds actual SDL Renderer and Canvas proof. --- ## Notification source shadows Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NOTIFICATION_SHADOWS.md # Notification source shadows Set `settings.shadow_policy = CUI_NOTIFICATION_SHADOW_SOURCE` before initializing the notification state. Zero-initialized settings and `cui_notification_settings_default()` retain `CUI_NOTIFICATION_SHADOW_LEGACY`. SOURCE replaces the sixteen decorative rectangles with two copied drop-shadow layers on each visible card's final, animated bounds: | Order | Offset | Sigma | Spread | Color at rest | | --- | --- | --- | --- | --- | | 1 | (0, 10) | 7.5 | -3 | black, alpha 26/255 | | 2 | (0, 4) | 3 | -4 | black, alpha 26/255 | The caster uses `theme.radius_lg`. Core paints both shadows before the card surface; content clipping and the ordinary border retain their existing order. Source-invisible collapsed cards and system-only notifications emit no shadows. The popover surface palette, custom content, stacking, dismissal controls, deadlines and existing slide distance remain the Notification renderer's current behavior. The pinned source is upstream-component 0.7.1, commit `87d10ae5e1299d1be18670a37570c5402f952e34`, `crates/component/src/styled.rs:85–95` (ordered layers), `crates/component/src/notification.rs:494–495,518–528` (transition ink), and `crates/base/src/toast.rs:514–534` (independent stack visibility). Source shadow ink uses transition alpha cubed, then element opacity adds another transition-alpha factor. CUI projects the resulting ink as `round(255 * 0.1 * transition_alpha^4 * stack_visibility)`. Stack visibility is an independent ancestor factor, not raised to the fourth power. External Core ancestor opacity applies once after this projection. The source floating alpha 0.1 becomes 26/255 at rest; this is an explicit 8-bit projection rather than floating Hsla identity. ```c cui_notification_settings settings = cui_notification_settings_default(); settings.shadow_policy = CUI_NOTIFICATION_SHADOW_SOURCE; /* Initialize caller-owned entries/state using these settings. */ cui_notification_advance next; bool accepted = cui_notifications_checked(ui, overlay_id, theme, &state, viewport, now_seconds, &next); /* End the active frame and check Core/renderer errors separately. */ ``` `cui_notification_settings_valid` rejects unknown policies. Reducer operations also reject invalid settings before changing state or invoking callbacks. The checked render entry requires an active UI frame, valid initialized state, independent output storage, finite viewport/time and, in SOURCE mode, valid shadow radius and finite owner fade state. Rejected inputs leave its output, owner reductions, callbacks and UI emission untouched. SOURCE setter failure returns false without publishing the output. Already accepted reductions or host/custom-content callbacks cannot be rolled back by later UI capacity, `cui_end_frame`, or renderer-preflight failure. The compatibility wrapper returns a zero advance on checked failure. This API does not certify frame submission. The two local layer values are copied by Core; neither the stack array nor the temporary theme is retained by a deferred renderer. Existing caller ownership of notification strings, content callbacks, state entries and host userdata is unchanged. Custom content must continue honoring the supplied opacity and its existing borrowed-lifetime contract. Renderer budgets, supported shadow domain, pre-clear rejection and copied cache keys use the shared drop-shadow capability. Evidence includes meaningful headless geometry/order, invalid-policy/radius/fade rejection, controlled exit, independent stack opacity, translucent surface and ancestor composition, hidden/system delivery and custom disabled/loading children. Software and actual SDL Renderer (OpenGL and software drivers), SDL GPU (Vulkan), Sokol (Mesa GL), and Canvas exercise actual component commands in light/dark themes at scales 1 and 2. Failed shadow preparation preserves previous pixels; native SDL captures occur before Present because accelerated backbuffers need not retain pixels after presentation. This slice does not complete Notification parity: the source's 96px slide, arbitrary source style refinement and exact upstream native shader/AA/color identity remain separate work. Source behavior is not inferred from the private shadow helper's name. The unchanged LEGACY approximation remains available explicitly. The native/unit/WASI/browser fixtures are registered by the integrator; generated headers include the optional policy and checked entrypoint. The four GNU SDL wrap flags capture actual completed drawing before presentation. Reproduce Canvas with `uv run tests/web/test_notification_shadows.py --output build/notification-shadow-probe`. --- ## Numeric and sequence controls Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NUMERIC.md # Numeric and sequence controls `cui_numeric.h` provides NumberInput, Pagination, Rating and Stepper. Values and changes belong to the application; a true result signals a controlled value/index change. Theme values define typography, surfaces and spacing. Each styled function calls its corresponding `cui_base_*` reducer exactly once, then paints without adding semantics or mutating state. Base reducers are independently usable with custom layouts and emit no draw commands. `cui_numeric_part_id` exposes stable child IDs for these layouts. Button/page/star/step activations are processed in input order, including multiple activations in one frame. The implementation is portable C11 and uses semantic snapshots and common draw commands, without platform or Clay types. ## NumberInput Create a single-line `cui_edit` attached to an application-owned NUL-terminated buffer, then zero-initialize `cui_number_state` with its borrowed editor. The editor must outlive the state. Drafts are bounded to 127 bytes; a 128-byte buffer accommodates every supported draft. Editor history/scratch allocation remains explicit in its configuration. `cui_number_input` accepts a finite `double *value`. Initialization and subsequent external value replacements synchronize the draft. Valid typing updates the value immediately; incomplete drafts such as `-` or `.` stay visible without replacing the last accepted value. Default typing admits an optional leading sign, digits and a decimal point; optional exponent typing admits incomplete exponent drafts until they become valid. Full-width digits, signs, decimal point and ideographic full stop normalize to ASCII. Other characters, malformed UTF-8, invalid prospective syntax and oversized insertions are rejected atomically. Existing editor selection, left/right/home/end, shift-selection, backspace/delete and select-all are supported. Enter submits, and Enter or blur clamps valid drafts to optional finite min/max bounds. Up/Down and plus/minus buttons use fixed positive `step` or an application callback receiving value/direction. Invalid/nonpositive steps do not mutate the value; `step_direction` still reports an attempted step for application-owned handling. Stepping below the minimum downwards or above the maximum upwards does nothing. Crossing a bound clamps in the requested direction; finite overflow without a bound is rejected. Draft formatting failures do not commit a button step. Disabled suppresses editing and focus; readonly keeps readable/focusable text while suppressing editing and stepping. Prefix, suffix and field width are configurable. Standalone `cui_number_parse` recognizes strict ASCII decimal/exponent grammar without whitespace, hexadecimal, comma, NaN or infinity. It validates before adapting the single decimal point to the current C locale's radix for one correctly rounded `strtod` conversion. `cui_number_format` reverses locale radix adaptation and emits 17 significant digits, preserving finite double round trips, including signed zero and nonzero subnormals. Underflow to zero is rejected. These functions never mutate global locale; concurrent changes of the process locale remain unsupported. Semantic float values/ranges saturate at `FLT_MAX` when the accepted double exceeds semantic storage precision. NumberInput renders the decrement button, centered editable value and increment button inside a single themed frame. Its `name` is an accessible label rather than a painted legend. Source Minus/Plus SVGs use the theme asset provider; no textual +/- stand-ins are painted. Step buttons remain pointer-only and route pointer focus to the editor, with accessible Increment/Decrement names. They stay enabled at configured bounds; an attempted step reports its direction while the clamped value stays unchanged. Arrow-key stepping still belongs to the focused editor. Step buttons have only the outer corners rounded, one pixel inside the frame radius, and fill the frame's inner height. Normal is transparent, hover uses input at40% alpha and held uses60%; glyphs use secondary foreground. Disabled dims the whole frame to50%, with the source disabled input/border tokens inside. `no_appearance` suppresses the frame surface/border. The renderer shares Input's selection and caret painting, with retained horizontal scrolling. `cui_number_options.size` defaults to `CUI_NUMBER_MEDIUM` (zero); SMALL, LARGE, XSMALL and CUSTOM are available. `cui_number_measure` exposes the complete metrics. Preset metrics scale by positive `density` or `theme.font_size / 16`: XS/S/M/L heights20/24/32/44, fonts12/14/14/16 and line box20. Step widths24/24/32/32 and SVG sizes12/14/16/24 follow the frozen source. Custom size is the frame height, step width and icon size, with font87.5% of that size. The frame width defaults200; negative width grows. Fixed-width values center correctly on the first frame. The inner field uses Source Input padding without another border or surface. Remaining upstream options include thousands-separator masks, custom pattern validation and fully composed prefix/suffix elements. NumberInput still has pointer text positioning, undo shortcuts, native clipboard and IME gaps in its base reducer. Its semantic field is currently Textbox rather than a native SpinButton role; there is no outer focus shadow or caret blinking. For editing automatically formatted scientific values, enable `allow_exponent`. ## Pagination Pages are one-based, with zero representing an empty result. Current page clamps to `[1,total]` or zero when no pages exist. Buttons support First, Previous, Next and Last, and visible numbered pages. A compact mode shows the current/total count. Boundaries and the current page disable redundant activation. The allocation-free item model emits endpoints and a radius-bounded neighborhood, fills single omitted pages, and inserts ellipses for larger gaps. Radius is capped at three, with at most eleven items. Arithmetic remains bounded for `SIZE_MAX` totals. The styled control uses radius two. All page buttons use the ordinary pointer/keyboard button routing; selected semantic details reflect the controlled page. Layout wrapping, configurable label slots, exact upstream compact typography and arbitrary visible-page budgets remain pending. ## Rating Rating accepts a controlled floating value, clamps to the configured maximum and quantizes to integer or half steps. The default maximum is five; the bounded renderer caps it at one hundred. Pointer activation selects a star; left/right halves select half/integer values when enabled. Keyboard arrows change by one step and Home/End select zero/maximum. Optional Clear supports both a pointer button and Delete/Backspace. Individual stars use pointer focus with no extra Tab stops; choosing a star returns keyboard focus to the rating group. Disabled and readonly suppress activation; readonly remains identified by semantic details. Full, half and empty indicators use antialiased SVG star masks, tinted by the theme. Half values crop the filled star mask. Custom icon/color slots and hover previews remain pending. ## Stepper Stepper uses a controlled zero-based selected index, bounded to existing items. Each item has title, optional description, explicit pending/active/complete/error status and disabled state. Pointer or Enter/Space activation updates the index. Whole-group disabling suppresses all items. Horizontal and vertical layouts use the same model. Selected semantic details and the visible Current label update in the activation frame. The selected button uses the primary variant; other buttons use the outline variant. Explicit complete/error statuses remain visible on other steps; an inactive active status displays Pending. Status text includes non-color meaning. Empty arrays are supported, and this convenience renderer bounds arrays to one hundred items. Custom icons, connector lines and exact size variants remain pending. Headless tests cover real routed key/pointer events, controlled replacement, draft rejection and CJK normalization, blur/Enter clamping, disabled/readonly behavior, half-star selection and clearing, page navigation, disabled step activation, all four themes, strict finite parsing and extreme double round trips. Exhaustive small pagination windows and `SIZE_MAX` boundaries test overflow/ordering invariants. New sources compile with strict C11 warnings; existing CTest and instrumented ASan/UBSan tests run before submission. Source/test/distribution registration belongs to the integrator. Compile `tests/unit/test_numeric.c` with `-DCUI_NUMERIC_BASE_ONLY` to run the same routed-event assertions against base reducers, bare geometry, and no theme/components link. The worker validates this separate executable as well as the styled path, including a Last-then-Previous activation sequence in one frame. For per-activation requests with application-owned validation, use the additive [controlled Stepper navigation API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/STEPPER_NAVIGATION.md). It preserves the legacy mutating reducers and aggregate change observers; the guide provides a compiling owner-validation example. --- ## OtpInput Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/OTP.md # OtpInput CUI implements the frozen 0.7.1 numeric OTP interaction and grouped presentation with portable application-owned state. `cui_otp_init` borrows a valid NUL-terminated buffer and a target of at most 256 cells. There is no per-frame allocation. The buffer remains valid while state is used; only the OTP API should mutate it. `cui_otp_set_value` validates UTF-8/capacity transactionally and preserves arbitrary or overlength programmatic values, matching the upstream compatibility contract. It does not emit user editing notifications; invalidate your context after programmatic changes. `cui_base_otp` submits a single accessible textbox and reduces actual routed pointer/keyboard input without theme painting. ASCII digit and fullwidth digit text events append one normalized digit. Other text and arrow/delete keys are ignored. Each text event uses its first scalar, matching the reference's per-key editor; bulk clipboard paste is not an OTP feature. Backspace removes the final UTF-8 scalar, including arbitrary programmatic values. Typing stops at the target length; storage exhaustion reports capacity without losing the prior value. Disabled state suppresses editing and focus presentation. The result distinguishes `changed`, `complete`, `focused`, and `blurred`, with counts for accepted editing/completion events within one frame. This follows the frozen source's `OtpEvent::Change` and `OtpEvent::Complete` distinction rather than the website's older completion-only summary. Backspace is an accepted edit even on an empty value, as in the source. Programmatic updates do not set these flags. `cui_otp_value` and `cui_otp_count` expose the current borrowed text/scalar count. `cui_otp_options_default()` requests two visual groups. Explicit zero clamps to one, excessive group counts clamp to the target length, and an empty target uses one empty group. Groups contain ceiling(target/groups) cells, with remaining cells in later groups. Options select extra-small/small (24), medium (32), large (44), or a custom cell size; custom pixel sizes default text to half that size. Default within-group gap is four pixels and between-group gap is twenty. Masking replaces every displayed scalar with `*`; draw commands and semantics do not include the raw masked value. The focused cell is the next empty cell, or the last cell for a full code. Focus-ring suppression is explicit. Pass host monotonic `now_seconds` for cursor blink; the interval defaults to half a second. Retained blink phase resets on focus and accepted editing. The result's `next_wake_seconds` supplies an absolute deadline while an empty focused cell has a visible caret. Schedule a host frame at that deadline. Visibility changes invalidate the context, while unchanged frames stay idle. Filled/disabled inputs do not request a caret wake. Window activation and native scheduling belong to the host; this API does not pretend to provide an OS timer or IME bridge. The styled `cui_otp` renders the same base state with theme colors, rounded square cells, grouped gaps, focus border, and caret. The headless test links core, edit (for shared UTF-8 validation), and OTP base only. Styled linkage adds OTP component and a supplied theme; no separate input reducer is used. Tests cover real pointer focus, ordered text/key events, ASCII/fullwidth digits, rejection and target bounds, UTF-8 Backspace, completion/change/focus/blur counts, programmatic arbitrary values, storage errors, disabled input, host-clock blink, group clamping, all four themes/densities, exact cell/group geometry, and masking without raw-value draw commands. Native accessibility bridge coverage remains that of core, and OS OTP autofill is not implemented. --- ## Overlay behavior and focus scopes Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/OVERLAYS.md # Overlay behavior and focus scopes `cui_overlay.h` provides persistent application-owned open/dismiss state. It uses core focus scopes; it does not implement an independent hit-test or focus traversal system. The panel's layout and appearance remain application-owned. Initialize a stable scope ID with `cui_overlay_init`, then open it with `cui_overlay_open`. Supply an explicit trigger ID, or zero to remember current focus. After each `cui_begin_frame`, call `cui_overlay_update` before submitting controls, processing nested overlays innermost first. If `cui_overlay_begin` returns true, submit the panel and its controls, then call `cui_overlay_end`. After layout, save the panel's resolved bounds with `cui_overlay_set_bounds`. Outside dismissal arms only after bounds are supplied for the current opening, so opening a popup cannot dismiss against stale or absent panel geometry. The existing `cui_popup_place` model can determine an overlay's desired bounds; absolute positioning/portals are not currently supplied by this module. A modal scope confines forward and reverse Tab traversal to enabled descendants. The core establishes initial focus inside a newly submitted modal. Nested modal scopes trap to the innermost scope and restore focus to their remembered trigger when dismissed. Pointer input outside a modal is blocked from underlying controls and routed to the modal scope, allowing outside-click dismissal. Nonmodal popups permit the underlying outside click to activate while dismissing. Escape dismisses the top open scope. Dismissal policies are independently configurable. Focus restoration validates that the trigger was enabled in the previous completed frame; final submission validation also clears focus if the trigger has since become disabled or disappeared. Input is routed against the preceding completed frame and its scope ancestry. Opening affects dispatch from the next frame. Dismissal consumes the routed scope event; later queued events retain the routing established at frame begin. There is no post-Tab focus repair. A scope supplies keyboard and pointer isolation, but currently adds no platform accessibility modal relation, semantic dialog role, scrim, z-order, animation, scroll lock, or native window. These are reusable behavior primitives, not a complete styled Dialog. `test_overlay` verifies nested scopes, initial focus, forward/reverse traversal, disabled descendants, Escape, trigger restoration, disabled/removed triggers, and modal versus nonmodal outside-click activation. --- ## Date and time pickers Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PICKERS.md # Date and time pickers `cui_picker.h` provides Calendar, DatePicker, TimeField and ColorPicker. Core date/time structures and base reducers contain no platform, theme or Clay dependencies. Styled wrappers use common box/text/portal commands and cached SVG icons. Selected dates/times and retained navigation state are application-owned. Calendar renders one to three actual month grids, with configurable first weekday, selected date/range, minimum/maximum endpoints, disabled predicate and whole-widget disabled state. The grid model exposes 42 consecutive cells including neighboring dates and zero cells at Gregorian year boundaries. The legacy styled view leaves neighboring cells blank; opt-in presentation renders distinct selectable occurrences as described below. Canonical date IDs remain stable across navigation/reordering. Each day has a full ISO date semantic name by default, or numeric locale-formatted full date when a locale is supplied, disabled/selected details, and a roving Tab stop. The model supports years 1 through 9999. An invalid initial date defaults deterministically to 2000-01-01; applications provide their own current date. Month/year buttons navigate by one/twelve months. Arrow keys move one day or one week, Home/End move to weekday-aligned row boundaries, and Control/Meta with arrows moves months/years. Disabled candidates are skipped with a bounded 366-attempt search. Navigation changes the displayed month when the cursor leaves the visible months. Enter/Space or a day pointer click selects the cursor/date. Range mode takes two activations, sorts reverse selections, and keeps a pending endpoint between frames; disabled predicates constrain endpoints, not every interior date. Navigation never implicitly changes selection. Styled cell size defaults to 32 logical pixels and is bounded to 20..128 pixels. Seven builtin locale tables and custom borrowed labels/order/separator are available through cui_date_locale. Arbitrary month counts and arbitrary source item styling remain unsupported; frozen Calendar does not implement week-number columns, hover-range previews or a dedicated arrow-key map. The additive `cui_calendar_presentation.h` API enables independent month headers, a host-supplied today marker and selectable neighboring-day occurrences through `cui_calendar_ex`. Zero presentation options preserve legacy behavior. Use matching rebuilt headers/library, keep the canonical day ID for in-month cells and query neighboring occurrence IDs with `cui_calendar_cell_resolve`. DatePicker and typed CHANGE wrappers remain separate from these extensions. See [Calendar presentation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CALENDAR_PRESENTATION.md) for input ordering, policy checks, focus, borrowed lifetimes and explicit CUI range/recentering differences from frozen source. New presentation behavior is headless-tested; no browser or language-builder coverage is implied. The base Calendar offers reduction and semantic submission separately, plus a combined convenience function. DatePicker uses this separation to close a selected popup before submitting its modal scope. Closing on selection, Escape, outside click or disabling restores a valid trigger focus; this avoids leaving a closed modal scope in the activation frame. It uses the same `cui_overlay` focus/dismissal state and `cui_popup_place` collision model as choice popups. Its actual calendar renders as a viewport portal beyond ancestor clips, flips/clamps to the supplied viewport, and confines Tab focus while open. Range pickers close only after the second endpoint. Trigger semantics report expanded/controls. Calendar day and weekday labels are centered in their cells; month/year navigation uses SVG chevrons and retains accessible navigation names. DatePicker shares this renderer and uses a centered trigger with a calendar SVG. The current appearance uses ISO labels, a selectable calendar, and placeholder text; editable date masks, clear controls, custom locale/date formats and preset ranges remain pending. Small viewports clip a calendar rather than resize or scroll it. TimeField stores a valid 24-hour `cui_time` and displays segmented hours/minutes, optional seconds and optional AM/PM. Each segment has a name, numeric value/range and readonly/parent details; one active segment participates in Tab navigation. Left/Right changes segments, Up/Down wraps the active unit, Home/End selects its limits, and digit input advances after two digits. Two-digit drafts persist across frames. AM/PM accepts A/P or keyboard toggling. Twelve-hour display preserves the 24-hour model. Disabled/readonly suppress mutations. Strict standalone parse/format functions accept/emit ASCII `HH:MM[:SS]` and reject out-of-range units. Custom min/max times, typed separators, full-width normalization, configurable formats and native input/IME integration remain pending. Meaningful tests exercise leap years and weekday grids over forty years, minimum/maximum/disabled dates, actual routed multiple-arrow navigation, weekend skipping, year controls, reverse range selection, all four themes, persistent segmented digits, hour/minute rollover, 12-hour periods and disabled/readonly behavior. DatePicker tests cover actual portal geometry outside a clipped parent, selection close with trigger focus restored in the same frame, seventeen trapped Tab events, Escape and outside dismissal. The same Calendar/TimeField event suite compiles with `CUI_PICKER_BASE_ONLY`, no theme/components linkage, and bare geometry; base drawing remains empty. Strict warnings, fully instrumented ASan/UBSan, and existing CTest pass before submission. Root owns build/distribution registration. ColorPicker includes a retained HSV model controlled by application RGBA bytes, a two-dimensional saturation/brightness surface, hue and alpha controls, numeric RGBA channel sliders and up to 64 palette swatches. Arrow/Home/End keys adjust named channel semantics. Pointer capture survives separate down/move/up frames and is cancelled explicitly. Readonly/disabled suppress changes. HSV conversion handles negative/wrapped hues and sanitizes nonfinite components; strict `#RRGGBB[AA]` parsing and formatting are allocation-free. A 12×8 common-rectangle grid approximates the SV gradient and shows a selected-cell outline; hue uses 24 bands and alpha uses 16 bands. Channels display their numeric values and horizontal ranges. Palette clicks and external replacements synchronize HSV; achromatic channel edits preserve hue. The current widget lacks editable hex/channel text, exact continuous shader gradients, a native eyedropper and upstream popup presentation/options. It is an inline, real interactive color control rather than a claim of complete ColorPicker parity. Color tests add 20,000 deterministic RGBA→HSV→RGBA and hex round trips, primary/wrapped-hue/nonfinite boundaries, channel/palette keyboard/pointer behavior, cross-frame captured SV release, readonly/disabled checks, semantic ranges, all themes and measured gradient geometry. The base-only flavor exercises the same color reducer without theme/components. Twelve-hour TimeField semantics expose the displayed 1..12 range; Home/End preserve AM/PM while choosing 1/12. ## Picking a screen color The website's **Pick from screen** button uses the browser EyeDropper API. Select any screen pixel; Escape cancels without changing the controlled color. The chosen sRGB bytes replace RGB and preserve the current alpha. Unsupported browsers show an availability message. Navigation or disabling the component cancels an outstanding request. Screen access belongs to the host, so no browser or operating-system type enters CUI's public API. Native hosts can open their platform picker from a button callback, then assign the returned color to their application-owned `cui_color` and schedule a frame: ```c /* Run after your host picker completes successfully, on the UI thread. */ cui_color sampled; if (cui_color_parse_hex(cui_string("#1A8F64"), &sampled)) { sampled.a = color.a; /* Optional: preserve the existing opacity. */ color = sampled; cui_invalidate(ui); } /* The next cui_color_picker call synchronizes its retained HSV state. */ ``` The browser requires a secure context and a user gesture; call `new EyeDropper().open()` directly in the click handler before awaiting anything or scheduling a C frame. A resolved `sRGBHex` can be parsed with `cui_color_parse_hex`; cancelled or rejected requests must leave the value unchanged. See the [Chrome EyeDropper guide](https://developer.chrome.com/docs/capabilities/web-apis/eyedropper) and [API specification](https://wicg.github.io/eyedropper-api/). CUI's native adapters currently do not implement an OS screen picker; applications provide that host capability. Optional single-date time editing uses the separate `cui_date_time_picker.h` model and Base/Styled facade, not legacy DatePicker selection storage. See [DateTime picker](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DATE_TIME_PICKER.md) for explicit sync, ordered day confirmation, draft preservation, presets/clear, popup-fit policy and binding/source-event limitations. No timezone or date-time range is supported. --- ## Styled Plot composition Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PLOT.md # Styled Plot composition [`cui_plot_view.h`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_plot_view.h) adds immediate axis, bitmap and path rendering composition above the standalone [`cui_plot.h`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_plot.h) math module. Applications own scales, samples, commands, RGBA pixels, labels and callback state. Core retains layout regions and pointer capture; this layer has no retained series/widget tree, implicit allocations or platform types. See [PLOT_MODEL.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PLOT_MODEL.md) for geometry, scales, stacking, arc and radial contracts. The axis behavior was audited against frozen upstream `crates/base/src/plot/axis.rs` and `label.rs` at commit `87d10ae5e1299d1be18670a37570c5402f952e34`. The C implementation is original. The rasterizer below is a bounded software implementation rather than a claim that upstream's renderer/path cache was ported. ## Axes and numeric ticks `cui_plot_axis_defaults(width,height)` starts with the X line enabled, Y line hidden, and both axes absent. Set `has_x`/`has_y` and their positions relative to the top/left. An absent axis suppresses its line and labels. `x_line` and `y_line` hide only the line, preserving labels, matching upstream PlotAxis. Supply `cui_plot_axis_text` arrays with borrowed `cui_str` text, pixel tick, font size and alignment. Zero font size selects the source default 10px. START/CENTER/END alignment means left/center/right anchored about the label's X coordinate. Alpha-zero label colors use theme `muted`; alpha-zero axis stroke uses theme `border`. There is no way to request a transparent fallback color: hide the line or omit the label explicitly. At default 10px the source positions are preserved: X END labels start 6px below the axis; X START labels start 14px above. Y END/START label anchors are 2px right/left of the line, with vertical position tick minus 5px. For larger fonts, the C layer deliberately uses `-(font_size+4)` above X and `tick-font_size/2` beside Y instead of the frozen source's fixed 10px offsets. `cui_plot_axis_gutter(font_size)` returns font size plus 8px, matching the source helper. It returns zero for invalid/nonpositive sizes. Gutters are advisory; applications reserve their own plot rectangle. `cui_plot_axis_layout` returns measured rectangles and original label indices without submitting UI elements. It uses Core's configured font measurement. Each axis is bounded to 256 labels. Inputs must be finite: positive surface extent up to 16384, positions/ticks within +/-16384, font sizes up to 1024. Label geometry and required count remain unchanged on INVALID; CAPACITY publishes the required label count without partial geometry. Buffers must be stable and disjoint during the call. `cui_plot_axis` submits the same rectangles and centered 1px axis lines inside a fixed-size surface. Labels can extend outside that surface; ancestor clipping still applies. This allows explicit gutters rather than silently truncating labels at the axis edge. `cui_plot_axis_ticks` combines linear/log scale ticks and mapping with caller `cui_plot_numeric_tick` storage. It returns `%.17g` numeric text, values and center-aligned labels. These structs contain pointers to their own text arrays: keep them at their initialized addresses and copy only their `label` members into X/Y label arrays. Keep tick structs and label arrays live through `cui_end_frame` (and any renderer use of the draw list). Desired count is 2..256 and advisory; actual count may differ. Capacity queries return the actual count. No locale, automatic category labels, formatter callback, collision avoidance, rotated labels, grid lines or tick marks are supplied. ## Caller-owned software output `cui_plot_raster` clears and writes a straight-alpha RGBA8 buffer. The caller passes width, height, row stride and available byte capacity; at least `stride * height` bytes are required. Padding bytes after each row are preserved. Each `cui_plot_shape` points to pure Plot path commands with explicit fill, stroke color and stroke width. Use theme colors when constructing shapes. Alpha-zero fill/stroke disables that operation. Later shapes blend over earlier ones with straight-alpha source-over composition. Move/Line/Cubic/Close commands are supported. Cubics use 16 uniform parameter chords; this is an explicit approximation without adaptive error control. ARC commands are rejected: call `cui_plot_arc_flatten` first. Translate relative arc/radial points to the desired center before rasterization. Bars are closed rectangular paths produced from projected bounds; line/area commands come from `cui_plot_path`. No extra Chart dependency is introduced. Fill uses the even-odd rule across explicitly closed subpaths. Open runs receive only strokes. Stroke segments have round ends/joins through their union, with no dash/miter/cap style configuration. Pixel centers determine coverage: there is no anti-aliasing, gradient, texture, shadow or color-space conversion. Bitmap edges clip output. Defined coordinates/control points are finite within +/-16384; stroke width is 0..1024. Surfaces are 1..1024 per dimension, at most 64 shapes, at most 4096 commands and flattened segments per shape. The total `width * height * segment_count` work is capped at 64 million. Capacity failures (buffer size, segment expansion, workload) and invalid geometry leave **all pixels unchanged**, including when a later shape is invalid. Shape arrays, commands and pixel storage must be disjoint and stable for the entire call. The implementation uses a fixed segment scratch array, approximately 160 KiB on typical 64-bit hosts, and no allocation. This favors bounded portable output and small headless plots; a GPU/native path adapter can consume the same math commands independently. ## Bitmap composition and interaction `cui_plot_view` submits a borrowed `cui_bitmap`, then optional themed axes on top, in a fixed-size box equal to the bitmap's pixel dimensions. Axis dimensions must equal the bitmap dimensions. Any valid caller-created bitmap is accepted, including higher-quality output from another renderer (up to 16384 per axis). The bitmap's pixels must remain valid through renderer completion. Increment its revision whenever pixels change; the view does not modify it. Labels and their text must remain live through draw-list consumption. Invalid options return before submitting elements. Core frame-capacity errors follow normal Core behavior and cannot roll back an already submitted frame; check `cui_last_error` after `cui_end_frame`. The image semantic uses the supplied accessible `name`. Set `interactive=true` to opt into primary-pointer activation. A validated release on the same view invokes `on_activate` synchronously once per event with bitmap coordinates, relative to the previous frame's view bounds. Release outside cancels capture; secondary clicks, disabled views and passive views do not activate. The handler can update application state for the next frame. Pointer activation does not opt into focus or keyboard activation. The component does not pan, zoom, select a datum, create a tooltip or retain a hover model automatically. Use pure `cui_plot_inverse`, clipping/nearest/arc queries and application-owned state to implement those interactions. Scales must be updated explicitly. This complete example builds a themed line, numeric X labels and a view, then consumes its bitmap with the software renderer: ```c #include #include "cui/cui_plot_view.h" #include "cui/cui_software.h" int main(int argc, char **argv) { assert(argc == 2); /* Pass a readable font file path. */ cui_font *font = cui_font_open(argv[1]); assert(font); unsigned char pixels[96 * 96 * 4]; cui_theme theme = cui_theme_light(); cui_plot_sample points[] = {{8,0,70,true},{40,0,20,true},{80,0,50,true}}; cui_plot_path_command commands[32]; size_t count = 0; assert(cui_plot_path(points,3,CUI_PLOT_CURVE_NATURAL,CUI_PLOT_GAPS_SKIP, false,commands,32,&count) == CUI_PLOT_OK); cui_plot_shape line = {.commands=commands,.count=count, .stroke=theme.primary,.stroke_width=2}; assert(cui_plot_raster(pixels,96,96,96*4,sizeof pixels,&line,1, theme.surface) == CUI_PLOT_OK); cui_plot_scale scale = {CUI_PLOT_LINEAR,0,10,8,80,false}; cui_plot_numeric_tick ticks[16]; assert(cui_plot_axis_ticks(&scale,6,ticks,16,&count) == CUI_PLOT_OK); cui_plot_axis_text labels[16]; for(size_t i=0;i #include "cui/cui_plot_view.h" #include "cui/cui_software.h" int main(void) { cui_context *ui=cui_create((cui_config){.width=80,.height=80}); cui_software *renderer=cui_software_create(80,80,NULL); assert(ui && renderer); cui_theme theme=cui_theme_light(); cui_plot_bar_sample bars[]={{8,48,12,true,true},{36,48,28,true,true}}; cui_plot_bar_options style=cui_plot_bar_defaults(); style.band_width=20; style.corners=(cui_corner_radii){6,6,0,0}; cui_plot_sample points[]={{18,0,12,true},{46,0,28,true}}; cui_plot_dot_options dots=cui_plot_dot_defaults(); dots.size=8; dots.use_theme_fill=false; dots.fill=theme.surface; dots.custom_stroke=true; dots.stroke=theme.primary; assert(cui_begin_frame(ui,80,80,.016f)); cui_begin_box(ui,1,(cui_box){.width=64,.height=64,.fixed_width=true,.fixed_height=true}); cui_begin_absolute_box(ui,2,(cui_box){0},(cui_rect){0,0,64,64}); assert(cui_plot_bars(ui,3,&theme,(cui_size){64,64},bars,2,&style)==CUI_PLOT_OK); cui_end_box(ui); cui_begin_absolute_box(ui,4,(cui_box){0},(cui_rect){0,0,64,64}); assert(cui_plot_dots(ui,5,&theme,(cui_size){64,64},points,2,dots)==CUI_PLOT_OK); cui_end_box(ui); cui_end_box(ui); cui_draw_list draw=cui_end_frame(ui); assert(cui_last_error(ui)==CUI_OK); assert(cui_software_render(renderer,&draw,theme.background)); cui_software_destroy(renderer); cui_destroy(ui); return 0; } ``` For a geometry-only build, compile this example with `src/components/cui_plot.c`, `backends/software/cui_software.c`, `build/libcui.a` and `-lm`, using the same strict C11 flags above. Tests cover circular corner exclusion, custom/fallback border pixels, theme fills, radial centers, independent rounded/square bar corners, renderer clamping, fill callback inputs, missing/degenerate samples and invalid preflight suppression. ## Tooltip and appearance state Use the pure caller-owned lifecycle helpers described in [PLOT_MODEL.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PLOT_MODEL.md#caller-owned-hover-and-appearance-lifecycle) to retain a selected datum during exit. Keep its borrowed dot array alive until `has_state` becomes false, and paint the tooltip only when `has_state` is true. The bitmap view does not populate this state automatically. Feed progress from the application's existing animation policy and request another frame with `cui_invalidate` while the clock is moving. Honor `cui_reduced_motion` by snapping to the target, and suppress hover overlays while appearance is incomplete if you want the source PlotElement ordering. Completed appearance generations and linear stagger timing are reusable independently of drawing; the application owns scope disposal, easing, pointer springs, and the tooltip's content/layout. For a bitmap or custom path renderer, use `cui_plot_bar_path` instead of submitting the styled quad. It emits a closed cubic path with independent physical corner radii, consumed directly by `cui_plot_raster`. See [PLOT_MODEL.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PLOT_MODEL.md#rounded-bar-paths-for-custom-renderers) for its capacity contract and explicit cubic approximation limits. The styled driver continues to use Core rounded quads; it does not route through this rasterizer. For source-style Pie/Arc seams, choose `CUI_PLOT_ARC_SOURCE_PADDING` with `cui_plot_arc_flatten_ex` before rasterizing. It reproduces the source's .0001 radian override for spans at least π and its radius/span epsilon rules. Existing flatten calls retain seamless full turns. See the [Arc policy contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PLOT_MODEL.md#explicit-frozen-arc-padding-policy); hover hit testing still ignores visual padding, matching the frozen source. ## General labels and measured ellipsis `cui_plot_labels_layout` measures a caller-owned array of `cui_plot_label` using Core's configured text measurement. Origins are relative to the plot surface; START leaves x unchanged, CENTER subtracts half the measured width, END subtracts its full width. Font size zero selects the source's 10px default. Text is a single line, and y is its Core top origin. `cui_plot_labels` submits the collection in a fixed surface with the same geometry. Supply explicit colors: transparent labels stay transparent rather than falling back to theme muted. The frozen Text font_weight builder stores a field that its painter ignores; this API uses normal text rather than claiming weighted source rendering. Shaping/baseline metrics follow the configured CUI font backend, not identical upstream ShapedLine. Arrays are bounded to 256 labels, text to 4096 bytes each, font size to 1024px, origins/extents/label dimensions to 16384px. Layout errors preserve the output rectangles; insufficient capacity reports the count. Drawing preflights the whole collection before submitting any boxes. Keep label text alive through renderer completion. The label collection does not add retained state, automatic gutter allocation or a semantic chart model; tooltip content composition is a separate driver. `cui_plot_truncate_text` copies into caller-owned NUL-terminated storage and reports required bytes including that terminator. It follows the source's binary search over Unicode scalar boundaries for the longest measured prefix plus `…`. A nonpositive width budget keeps the original text. When no prefix fits, it returns the ellipsis alone even if that also exceeds the budget. Input must be valid UTF-8 and at most 4096 bytes; size zero defaults to 10px. Measurement must return finite nonnegative dimensions no greater than 16777216px. This does not split UTF-8 byte sequences, but may split a combining or emoji grapheme, as does the source. No locale, wrapping or automatic truncation is implied. Invalid inputs preserve output and required; insufficient capacity preserves output and sets required. Input/output may alias. If storage is used as a label, keep it stable through renderer completion. ```c #include #include "cui/cui_plot_view.h" static cui_size measure(void *user, cui_str text, float size) { (void)user; return (cui_size){(float)text.length * size / 2, size}; } int main(void) { /* Configure the application's real font callbacks for shaped text. */ cui_context *ui = cui_create((cui_config){.width=100, .height=60, .measure=measure}); assert(ui); char text[32]; size_t required; assert(cui_plot_truncate_text(ui,(cui_str){"Revenue",7},10,30, text,sizeof text,&required)==CUI_PLOT_OK); cui_plot_label label={.text={text,required-1}, .origin={50,10}, .align=CUI_ALIGN_CENTER, .color={30,30,30,255}}; assert(cui_begin_frame(ui,100,60,.016f)); assert(cui_plot_labels(ui,123,(cui_size){100,60},&label,1)==CUI_PLOT_OK); cui_draw_list draw=cui_end_frame(ui); assert(draw.count>0); /* Render draw before releasing text or destroying ui. */ cui_destroy(ui); return 0; } ``` The pure [tooltip cursor gate](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PLOT_MODEL.md#tooltip-cursor-gating-from-plotelement) handles current-bounds desktop coordinates and explicit long-press state before your datum resolver runs. Refresh desktop state each frame using the application's hit/occlusion decision; use `update.changed` to invalidate from mouse-move events. Long-press detection and capture stay in the adapter/application. Resolve the live cursor, suppress during appearance, then update hover memory; this does not automatically make the bitmap view interactive or render an overlay. Use the pure `cui_plot_sankey_link_path` to draw a tapered ribbon from existing Chart node/link geometry through `cui_plot_raster`. It preserves independent end widths, minimum painted width and source midpoint-X cubic controls. See the [source ribbon contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PLOT_MODEL.md#source-sankey-ribbon-paths); this adds a path builder without a second graph/layout solver or renderer cache. The [shared Base Sankey graph model](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PLOT_MODEL.md#shared-base-sankey-graph-model) now supplies topology, alignment and relayout independently of Chart. Use source-default options for standalone Plot; the Chart adapter preserves its own defaults, raw throughput reporting and legacy zero-flow alignment. The graph and tapered ribbon path are caller-owned math outputs, not an automatic styled Sankey widget. ## Frozen Axis offsets and explicit colors `cui_plot_axis_source_defaults` selects the frozen base Axis contract without changing existing styled calls. It sets `source_offsets` and `explicit_colors`. X labels sit at axis+6px on End or axis-14px on Start; Y labels sit at axis±2px and tick-5px. These offsets stay fixed even for 20px or 30px fonts, exactly as the source derives them from its 10px constants. Measured text alignment still subtracts half/full width for CENTER/END, and each label retains its selected font size. The source route submits a single normal line through Core; shaping and baseline metrics remain backend-specific rather than identical upstream pixels. Explicit colors preserve alpha zero for labels and axis strokes; supply the actual solid colors you want. Alpha zero no longer chooses theme muted/border. With legacy `cui_plot_axis_defaults`, offsets continue to scale the Start gap and Y centering with font size, and zero-alpha colors continue to use theme fallback. The two appended booleans can be selected independently. Axis absence and line visibility still gate line/labels independently as before; no automatic gutters, tick formatter or placement policy is introduced. `cui_plot_grid_ex(...,stroke,true)` likewise preserves its supplied color, including transparent, matching the source Grid stroke behavior. Pass false or use the unchanged `cui_plot_grid` for alpha-zero theme fallback. Dash geometry and its existing bounded-output/error contract are shared by both paint routes. General gradient/Background fills and renderer path caching remain separate unsupported features; these options implement actual solid-color behavior. For a virtualized list of plots, the [bounded appearance scope registry](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PLOT_MODEL.md#bounded-appearance-scope-registry) remembers multiple completed generations while its enclosing scope is painted consecutively. Begin/end it explicitly each host frame and pass the innermost registry into child composition. Returning completed children can skip draw-in; interrupted children restart. No retained list/plot tree or implicit scheduler is introduced by this numeric state helper. For enter/exit animation, sample a separate `cui_plot_transition_clock` per channel with `cui_plot_transition_step`, feed its value to `cui_plot_hover_track`, and schedule a frame when `request_frame` is true. Initialize the channel at zero before its first hover target of one, since the source transition adopts its first target immediately. Signed delays, cubic-out (default) or synchronous custom easing, reversal shortening and reduced-motion snapping are supported. This host-driven clock does not add renderer keyed state. See [projected transition clocks](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PLOT_MODEL.md#projected-transition-clocks) for exact policy-change and ownership rules. Pointer glide uses `cui_plot_spring_step` with caller-owned scalar state, explicit seconds and a policy from `cui_plot_spring_defaults`. Pass hover memory's `entering` flag to snap on entry; later target changes preserve momentum and advance toward the previous target before retargeting. Schedule while `request_frame` is true. Use independent states for each coordinate. This is an explicit host seam, not automatic scoped renderer state or theme projection. The gallery shape selector exposes linear, natural cubic, step-after, area, radial, rounded-bar and dot previews. All use the same projected samples, scale and native C geometry; bars/dots sample every eighth point to bound software preview work. Zoom/pan resamples the function through the current scale. These previews do not imply automatic shape hit testing, animation clocks or renderer path caching. The software path route can retain caller-owned `cui_plot_path_cache` storage across frames. `cui_plot_path_cache_get` rebuilds and flattens only on a changed shape key; `cui_plot_raster_cached` accepts its borrowed relative segments plus current origin and colors. Origin/color changes reuse tessellation, and empty paths are cached. Pixel rasterization still runs; this does not add a Core native mesh cache or implicit element cache lifetime. See [cached tessellation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PLOT_MODEL.md#shape-keys-and-cached-tessellation) for bounds, key composition and view lifetimes. ## Styled tooltip composition `cui_plot_element` composes the existing view plus datum resolution, marks, ordinary children and tooltip content. It uses caller-owned hover/transition state and Core frame time/reduced motion. Supply current global layout bounds, live pointer position and an occlusion-aware hover flag; previous `cui_bounds` cannot provide those current bounds automatically. Tooltip content runs last inside an inert plot-sized portal with inherited hover opacity and may position its own body relative to that portal. The selected datum/cursor survives exit until progress reaches zero. The driver invalidates while its clock requests frames. See [the exact host seam](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PLOT_MODEL.md#styled-plotelement-composition) for touch gates, callback ordering, ownership and renderer limitations. This complete example intentionally knows its absolute plot placement. A host with flowing/scrolling layout must provide that frame's actual placement instead. ```c #include "cui/cui_plot_view.h" #include static cui_plot_result datum_at(cui_plot_point p, cui_plot_rect bounds, cui_plot_tooltip_state *out, void *user) { (void)bounds; (void)user; *out = (cui_plot_tooltip_state){.index = p.x < 32 ? 0 : 1, .cross_line = p}; return CUI_PLOT_OK; } static void tooltip_body(cui_context *ui, cui_id id, const cui_theme *theme, const cui_plot_hover_memory *hover, cui_plot_rect bounds, void *user) { (void)bounds; (void)user; cui_begin_absolute_box(ui, id + 10, (cui_box){.background = theme->surface}, (cui_rect){(float)hover->cursor.x + 4, (float)hover->cursor.y + 4, 40, 20}); cui_text(ui, cui_string("datum"), 10, theme->text); cui_end_box(ui); } int main(void) { cui_context *ui = cui_create((cui_config){.width = 100, .height = 100}); assert(ui); static unsigned char pixels[64 * 64 * 4]; cui_plot_view_options view = {.bitmap = {pixels, 64, 64, 256, 1}, .interactive = true}; cui_plot_element_state state = {0}; cui_plot_element_options element = { .bounds = {10, 15, 74, 79}, .pointer = {30, 35}, .hovered = true, .enter = {.duration = .12}, .exit = {.duration = .16}, .resolve = datum_at, .tooltip = tooltip_body }; cui_theme theme = cui_theme_light(); assert(cui_begin_frame(ui, 100, 100, .016f)); cui_begin_box(ui, 1, (cui_box){.width = 100, .height = 100, .fixed_width = true, .fixed_height = true}); cui_begin_absolute_box(ui, 2, (cui_box){0}, (cui_rect){10, 15, 64, 64}); assert(cui_plot_element(ui, 3, &theme, &view, &state, &element) == CUI_PLOT_OK); cui_end_box(ui); cui_end_box(ui); (void)cui_end_frame(ui); /* render this list before the next begin_frame */ cui_destroy(ui); return 0; } ``` ## First-paint appearance Set `element.has_appearance=true`, supply `generation`, `frame_serial` and the `appear` transition policy, and retain the same `cui_plot_element_state` across frames. Increment the serial for every host frame, including omitted plots. The first paint starts at linear time zero; zero duration/reduced motion is complete immediately. `on_appear` runs before datum resolution and drawing, allowing caller-owned marks or bitmap data to use its eased progress. The driver does not choose a reveal style. Use `cui_plot_appear_value_stagger` on the sample for staggered marks: local linear time is eased independently for each mark. The callback sample pointer is borrowed for that call; payloads obey the normal renderer lifetimes and bitmap revision rules. Owner rekey, a frame gap or a new generation restarts the appearance. Pass an active innermost `appear_scope` registry begun with the same frame serial to remember completed generations across omitted plots. Begin/end that scope even on frames without the plot. Unfinished appearances replay after omission, and scope rekey/gaps forget completions. Appearance still runs for passive/disabled plots and keeps ordinary children composed; hover is suppressed until linear time reaches one. Default policy is Base's zero duration, with product timing supplied by the host. See [channel binding](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PLOT_MODEL.md#first-paint-appearance-channel-binding) for capacity failures and exact lifetime rules. ## Software fill and stroke backgrounds Frozen shapes accept upstream Background values verbatim. The portable cached-path route supports solids, two-stop sRGB/Oklab gradients, slash and checkerboard patterns through `cui_plot_raster_backgrounds`. Fill and stroke backgrounds are independent, with an explicit relative frame anchored to geometry. Cache origin translation moves geometry and paint together without rebuilding segments. ```c cui_plot_background gradient = cui_plot_linear_background_source( 90, (cui_plot_color_stop){{255, 0, 0, 255}, 0}, (cui_plot_color_stop){{0, 0, 255, 0}, 1}, CUI_PLOT_COLOR_OKLAB); cui_plot_background stripes = cui_plot_pattern_slash((cui_color){0, 0, 0, 128}, 2, 2); cui_plot_background checks = cui_plot_checkerboard((cui_color){0, 0, 0, 128}, 4); /* Assign gradient/stripes/checks to a background shape's fill or stroke; * its cached path and positive background_frame remain required. */ ``` Angle0 points up,90 right; source projection scales the shorter axis before projecting onto the dominant extent. The older `cui_plot_linear_background` keeps its earlier diagonal projection. Caller angles/stops are preserved, including reversed stops, and never rotated automatically for a bar. Oklab mixes decoded linear RGB in Lab with independent alpha; transparent endpoint RGB still contributes. Output is encoded, gamut-clamped RGBA8. Pattern sizes are raster pixel units anchored at the frame minimum corner, with no implicit device scaling. Checkerboard odd cells are colored; slash uses source f32 packing and a one-pixel alpha ramp. Invalid zero periods, overflowing packing and invalid sizes fail before changing pixels. Patterns and gradients reuse existing bounded raster work and do not add allocation. The segment renderer does not reproduce GPU Hsla conversion, native path meshes or gradient Core quads. Existing solid widget drivers remain separate. See the [Background audit](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PLOT_MODEL.md#background-draw-routes-and-native-renderer-gap) for exact pattern bounds, numeric rules and the remaining Core prerequisite. ## Portable native mesh preparation `cui_plot_fill_mesh` triangulates a single simple closed contour into caller-owned XY/ST vertices and bounds. It handles concave contours and either winding, with at most256 vertices, while rejecting holes and touching/self-crossing contours. Pass relative positions without duplicating the closing endpoint. Query capacity first, retain the successful mesh yourself, and translate XY/bounds at submission; ST coverage coordinates remain unchanged. `cui_plot_mesh_coverage` exposes the pinned analytic quadratic coverage formula for renderers receiving ST derivatives. Neither API submits UI or promises all Lyon stroke/fill behavior. See the [native contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PLOT_MODEL.md#native-triangle-preparation-and-coverage) for transaction rules, bounds, coverage semantics and remaining renderer work. ## Shader-source float colors Use `cui_plot_hsla_background_sample` when matching the source path shader's linear premultiplied color output. Its normalized Hsla inputs are converted to linear RGB; SRGB gradients encode/mix/decode, while Oklab gradients mix Lab. Alpha and supplied coverage multiply RGB only after color interpolation. `cui_plot_raster_hsla` applies those backgrounds to cached fill/stroke geometry and writes a caller-owned linear premultiplied float buffer. Stride/capacity are measured in RGBA pixels. The encoded byte rasterizer remains a separate route; choose a display transfer/format explicitly when consuming the float output. See the [source color contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PLOT_MODEL.md#source-hsla-and-premultiplied-path-output) for transparent colors, checked bounds and compositing semantics. ## Adaptive curves and default stroke geometry `cui_plot_cubic_flatten` adaptively produces a cubic contour at an explicit pixel tolerance (the pinned Lyon default is0.1). `cui_plot_stroke_mesh` accepts an open polyline and produces centered stroke triangles with Butt caps and Miter joins, including source miter-limit bevel fallback. These are reusable caller-owned geometry APIs; they do not change the legacy software raster sampling. ```c cui_plot_point contour[64]; cui_plot_mesh_vertex vertices[750]; size_t count = 0, vertex_count = 0; cui_plot_rect bounds; cui_plot_result result = cui_plot_cubic_flatten( (cui_plot_point){0, 0}, (cui_plot_point){0, 8}, (cui_plot_point){8, 8}, (cui_plot_point){8, 0}, .1, contour, 64, &count); if (result == CUI_PLOT_OK) result = cui_plot_stroke_mesh(contour, count, 1, 4, vertices, 750, &vertex_count, &bounds); /* On success, retain vertices; translate XY/bounds at native submission. * ST remains unchanged. Check result before using output geometry. */ ``` The stroke route is bounded to64 points and rejects reversals/self-overlapping outlines. Closed strokes, holes, dashes and alternative cap/join styles remain gaps. See the [adaptive geometry contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PLOT_MODEL.md#adaptive-cubic-contours-and-default-stroke-meshes) for error preservation, source miter semantics and exact limits. --- ## Headless plot scales and geometry Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PLOT_MODEL.md # Headless plot scales and geometry `cui_plot.h` is an original allocation-free C11 math module. It has no core, style, font, platform, or GPU dependency. It implements scale/viewport behavior and projected geometry, not a Chart or Plot widget. The pinned upstream Base linear, categorical scale and bar modules were reviewed as functional references; this code does not copy their Rust implementation. A `cui_plot_scale` has a strictly ascending data domain, a pixel range that can ascend or descend, a linear or base-10 logarithmic transform, and an optional clamp flag. Mapping and inverse mapping reject nonfinite inputs. Log domains and values must be positive. Inverted domains are invalid; equal domain/range endpoints are degenerate. Finite ascending log endpoints that become identical at the platform's transform precision are also rejected as degenerate. Outputs and mutable scales remain unchanged on errors. ```c cui_plot_scale y = { CUI_PLOT_LINEAR, 3, 97, 400, 20, false }; cui_plot_nice(&y, 6); /* Domain expands to 0..100. */ double pixel; cui_plot_map(&y, 25, &pixel); /* 305, with larger values higher. */ cui_plot_zoom(&y, 2, pixel); /* Keeps the value 25 at pixel 305. */ cui_plot_pan(&y, 10); /* Plotted data moves 10 pixels down. */ ``` `cui_plot_ticks` chooses ascending 1/2/5 steps in linear domains or transformed base-10 exponent space. Desired count is advisory and must be 2–1000. Ticks are finite, unique, and inside the current domain. Subnormal linear steps are bounded by the smallest positive double; steps near large domain offsets are bounded by representable spacing to prevent duplicate ticks. Log ticks can use fractional powers of ten. Nice domains round outward in transformed space, saturating at finite double limits while retaining original endpoints. Nice-step threshold decisions allow a few long-double arithmetic ulps so a libm rounding difference does not promote an exact unit step to two. Tick generation inspects neighboring transformed grid indices and applies strict final comparisons in the original double domain. Exact power-of-ten endpoints remain inclusive; excluded endpoints are not pulled into range by a broad relative epsilon or endpoint snapping. Tick generation uses bounded temporary storage for at most 1024 values and never allocates. Pass `NULL, 0` to query required capacity. Insufficient capacity returns `CUI_PLOT_CAPACITY` and reports the required count, without writing a partial result. A sufficiently sized output buffer receives the entire result. A narrow domain can contain no representable chosen ticks, yielding count zero. Pan shifts the transformed domain by a pixel delta. Zoom divides its span by a positive factor around the data coordinate at the supplied pixel anchor. A factor greater than one zooms in. Reversed ranges work with both operations. Operations reject overflow, underflow to a nonpositive log domain, and zoom levels that collapse the representable domain. Factor one and zero pan are exact no-ops. Zoom anchors outside the pixel range use extrapolated coordinates, even when subsequent mapping is clamped. Long-double intermediates reduce cancellation where the compiler supports extra precision. Scaled fractions also handle finite domains whose width exceeds `DBL_MAX` on platforms where long double equals double. This does not make doubles exact: narrow domains near enormous offsets have fewer meaningful positions. Numerical failures are explicit; no NaN/Infinity sentinel is returned. `cui_plot_clip_line` clips a segment to a finite ordered viewport; projection helpers map and clip a data segment or a vertical bar with an explicit baseline and pixel thickness. Reversed vertical ranges and negative-valued linear bars are supported. Logarithmic bars require a positive value and baseline. Invisible segments or zero-area clipped bars return `CUI_PLOT_EMPTY` without changing output. Scale clamping applies before geometry clipping; use unclamped scales when off-domain geometry should intersect the viewport naturally. Pure path commands, stacking and pie/arc queries are described below. No axis labels, retained series storage, hover composition, legends, accessibility chart description or animated transitions are supplied by the math module. The optional [styled Plot layer](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PLOT.md) adds themed axes and bounded software path/bitmap composition without changing this standalone module. `test_plot` checks 1500 deterministic forward/inverse and zoom-anchor cases, linear/log ticks, reversed ranges, transactional failures, subnormal domains, finite extreme domains/ranges, clipping, projected lines, and bar baselines. ## Browser demonstration The Plot gallery displays `sin(x / 12)` rather than only reporting scale metadata. Each frame samples 65 values using `cui_plot_inverse` and paints them with the existing Chart renderer. Zoom in/out change the domain around the viewport center; Pan left/right shift it; Reset restores 0–100. The domain readout and nice-tick count update with the retained scale. This demonstrates composing the numerical Plot API with a renderer. It does not introduce a separate public Plot widget or mouse gesture API. The scale is application-owned retained state; sampling and drawing are immediate. See `web/gallery.c` for the composed example. ## Categorical scales Band, Point and Ordinal were audited against the frozen upstream Base `plot/scale/{band,point,ordinal}.rs` at commit `87d10ae5e1299d1be18670a37570c5402f952e34`. The C implementation is original; it uses application-defined `uint64_t` category keys instead of Rust generic values. Intern string labels or other application values into stable keys; the application owns collision handling and label formatting. Key zero is valid. All three models remain application data and submit no rendering or semantics. Existing linear/logarithmic APIs retain their previous behavior. | Model | Domain ownership and duplicates | Output | | --- | --- | --- | | `cui_plot_band_scale` | Copies first-occurrence unique keys into caller storage | Band start, width, step, nearest slot | | `cui_plot_point_scale` | Borrows the entire domain, including duplicates | Evenly spaced positions, nearest entry | | `cui_plot_ordinal_scale` | Borrows domain and typed range; first duplicate wins lookup | A copy of a cycling range element or explicit unknown | Domains/ranges must remain alive while their models are used; scale structs and output arrays must also outlive their consumers. Band initialization uses a bounded 32 KiB scratch array so overlapping input and destination storage are safe and capacity failure cannot partially rewrite either storage or the model. Its deduplication is quadratic, bounded to 4,096 entries. Key lookup is linear; Point `at` and nearest calculations are constant time. These are deliberately bounded allocation-free models, not retained hash maps or implicit insertion. Point and Ordinal domain arrays may be replaced by calling their initializer again; failed initialization preserves the previous binding. ### Band geometry `cui_plot_band_init` reports the required **distinct** key count on `CUI_PLOT_CAPACITY`. Other initialization failures leave `required` untouched. A NULL storage pointer with capacity zero performs a capacity query (an empty domain needs zero storage and initializes successfully). All other scale and geometry outputs remain untouched on failures. Keep `required`, the scale struct and destination storage disjoint; the input key array may alias storage. The effective band count is the larger of distinct domain count and `options.band_count`; extra bands remain empty. Unlike Point or Linear, reversing Band's range does **not** reverse category order: Band always starts at the lower endpoint, matching the frozen source. If span is `R` and effective count is `N`, the source-specific policy is: - Base average is `R / N`; uncapped width is average times `(1 - padding_inner)`. - Outer inset is average times `padding_outer`. - For `N > 1`, step is average times `(1 - 2 * padding_outer / N)` times `(1 + padding_inner / (N - 1))`. - A single band is centered using its actual capped width, and its step is `R`. A single key with a larger explicit band count occupies the first band. These formulas follow the pinned implementation, not the general D3 band padding/align/round API. A width cap changes band widths, not multi-band starts or steps. Inner padding must be finite in `[0,1]`; outer padding must be finite, nonnegative and no larger than half the effective count. A supplied width cap must be finite and nonnegative. Invalid options are rejected; the frozen source accepts unchecked float setters, so this stricter numerical contract is explicit. Empty/zero-width ranges remain valid. Derived values that cannot fit a finite double report `CUI_PLOT_OVERFLOW` without publishing partial geometry. `cui_plot_band_map` maps a key; `cui_plot_band_at` maps an existing deduplicated domain index. Unknown keys and indices beyond the domain return `CUI_PLOT_EMPTY`. Nearest rounds relative to **band starts**, not centers, with halfway ties toward the next index. It clamps to the effective band count and can identify a reserved empty band past the domain. Empty or single-band layouts return index zero. For a multi-band layout with zero step, a pixel above the collapsed start returns the last slot; pixels at/below the start return zero, matching the source's saturating rounded-index behavior. Point's zero-range nearest instead returns zero for every pixel. ### Point and Ordinal Point preserves input domain order and duplicates. Positions run from the first range endpoint to the second; reversed ranges reverse their direction. A single entry sits at the midpoint. Key lookup uses the first matching entry, while `cui_plot_point_at` addresses later duplicate entries independently. Nearest rounds to the closest entry, with positive halfway ties toward the next index, and clamps to domain bounds. Empty, single-entry and zero-range scales return nearest index zero. Empty/unknown keys and unavailable indices return EMPTY without writing the pixel output. Nonfinite endpoints/pixels are invalid. Ordinal copies generic C range elements with `memmove`, so colors, numbers and application structs can be supplied without importing platform or Core types. For a key's first matching domain index `i`, output is `range[i % range_count]`. Duplicate entries remain in the domain and affect later unique keys' indices. The optional unknown pointer supplies one borrowed element for absent keys; known keys with an empty range still return EMPTY even with unknown configured. No implicit domain extension occurs. Element size must be nonzero, the range has at most 4,096 elements, and its total byte count and each individual element must each fit the 1 MiB bound (unknown is separate and shares the element size). These limits are checked before pointer arithmetic or copying. The output must have capacity at least `scale.element_size`; capacity failure leaves its bytes unchanged. NULL output with zero capacity queries that size for a resolvable key and returns CAPACITY. NULL output with sufficient capacity is invalid. The borrowed output data and destination must represent the same C type/element size; the scale does not reinterpret values or validate struct members. An output may overlap its source element because copying uses memmove; do not overwrite a borrowed domain/model or a different registered range value unless the application intends to change that model data. ### Reusable example The following complete C11 program links only `src/base/cui_plot.c` and the C math library. It computes bar geometry and a category palette without a renderer: ```c #include "cui/cui_plot.h" #include int main(void) { const uint64_t categories[] = {10, 20, 10, 30}; uint64_t storage[3]; cui_plot_band_scale bands; size_t required; assert(cui_plot_band_init(&bands, storage, 3, categories, 4, (cui_plot_band_options){.range_start = 0, .range_end = 300}, &required) == CUI_PLOT_OK); cui_plot_band_geometry geometry; assert(cui_plot_band_layout(&bands, &geometry) == CUI_PLOT_OK); double x; assert(cui_plot_band_map(&bands, 20, &x) == CUI_PLOT_OK); assert(x == 100 && geometry.band_width == 100); const uint32_t colors[] = {0xff3366ff, 0xff6699ff}; cui_plot_ordinal_scale palette; assert(cui_plot_ordinal_init(&palette, storage, 3, colors, 2, sizeof *colors, NULL) == CUI_PLOT_OK); uint32_t color; assert(cui_plot_ordinal_map(&palette, 20, &color, sizeof color) == CUI_PLOT_OK); assert(color == colors[1]); /* Compose a bar at x with geometry.band_width and the application's y scale. */ return 0; } ``` Compile this assertion-based example with `-UNDEBUG`: ```sh cc -std=c11 -Wall -Wextra -Wpedantic -Werror -UNDEBUG -Iinclude plot_example.c src/base/cui_plot.c -lm -o plot_example ./plot_example ``` Headless tests exercise the source's categorical cases plus transactional errors, capacity queries, duplicate handling, generic struct palettes, extreme finite Point ranges, overlapping Band storage, and 500 randomized forward/nearest round trips in both range directions. These scales do not establish full Plot parity. ## Allocation-free shape geometry `cui_plot_path`, `cui_plot_stack`, and `cui_plot_pie` accept caller arrays and write caller storage. Pass `NULL, 0` for output to query capacity. They return `CUI_PLOT_CAPACITY` and the required element count when storage is too small; empty input succeeds with count zero. Invalid inputs and numerical overflow leave both output and required count unchanged. No error writes partial output. Inputs, outputs and required-count pointers must be disjoint; buffers must remain stable for the whole call. The builders do not retain pointers or invoke callbacks. Sample/arc counts and total stack cells are bounded by `CUI_PLOT_CATEGORY_LIMIT` (4096). Path building uses a fixed index scratch array of approximately 32 KiB on 64-bit hosts; output can exceed 4096 commands. These contracts were audited against frozen `shape/line.rs`, `area.rs`, `stack.rs`, `pie.rs`, `arc.rs`, and `bar.rs` at the reference commit above. They expose portable geometry rather than upstream paint, path-cache, style, callback or label objects. ### Lines and areas Each `cui_plot_sample` contains already projected `x`, lower `y0`, upper `y1`, and `defined`. Line building ignores `y0`. Undefined samples' numeric fields are ignored, including NaN; defined coordinates must be finite. The caller maps data through linear/log/category scales before building commands. `CUI_PLOT_GAPS_SKIP` drops undefined samples and connects their neighbors, matching frozen upstream. `CUI_PLOT_GAPS_SPLIT` is an explicit extension: it starts a new path at each contiguous defined run. Leading, trailing and consecutive missing samples create no commands. Every singleton run emits a Move command. The upper path supports Linear, Natural (the source's Catmull-Rom-to-cubic formula with duplicated end neighbors), and StepAfter. StepAfter intentionally omits the final vertical leg, matching frozen upstream rather than assuming a D3 step curve. Cubic controls that exceed finite double range return OVERFLOW. Control differences divide their operands before subtracting to avoid intermediate overflow on targets where `long double` has double's range. Floating-point rounding still applies near the representable limits. With `area=true`, each run follows its upper curve, then visits all lower `y0` points in reverse with straight Line commands and emits Close. This allows stacked per-point lower baselines, an extension to frozen upstream's optional constant `y0`. Single-point areas are closed degenerate polygons. Areas always close at defined endpoints; they do not reproduce the frozen area behavior that could leave the fill open when the first/last original sample was missing. The lower boundary is linear even when the upper boundary is Natural or StepAfter. Commands contain points and two controls for Cubic; unused members are zero. A renderer interprets Move/Line/Cubic/Close, applies origin/clipping, and chooses fill/stroke/dot styles. No tessellation is performed here. ### Natural-order stacking `cui_plot_stack` consumes a series-major `cui_plot_value` matrix. Cell `series * point_count + point` produces the corresponding `cui_plot_stack_point` with lower `y0` and upper `y1`. Each column starts at zero and sums series in input order; undefined values contribute zero. Negative values share this signed cumulative baseline, matching frozen upstream; positive/negative divergent stacks, normalization, key sorting and alternate offsets are not implemented. Finite cumulative overflow fails transactionally. Original datum identity remains the caller's series/point index rather than a cloned payload. This complete example stacks two series, projects their boundaries through an inverted vertical scale, then produces closed area commands: ```c #include #include "cui/cui_plot.h" int main(void) { const cui_plot_value data[] = {{2,true},{3,true},{4,true},{1,true}}; cui_plot_stack_point stacked[4]; size_t required = 0; assert(cui_plot_stack(data, 2, 2, stacked, 4, &required) == CUI_PLOT_OK); const cui_plot_scale y = {CUI_PLOT_LINEAR,0,8,80,0,false}; cui_plot_sample samples[2]; cui_plot_path_command commands[8]; for (size_t series = 0; series < 2; ++series) { for (size_t point = 0; point < 2; ++point) { const cui_plot_stack_point cell = stacked[series * 2 + point]; samples[point] = (cui_plot_sample){(double)point * 100,0,0,true}; assert(cui_plot_map(&y, cell.y0, &samples[point].y0) == CUI_PLOT_OK); assert(cui_plot_map(&y, cell.y1, &samples[point].y1) == CUI_PLOT_OK); } assert(cui_plot_path(samples, 2, CUI_PLOT_CURVE_LINEAR, CUI_PLOT_GAPS_SPLIT, true, commands, 8, &required) == CUI_PLOT_OK); assert(required == 5 && commands[4].kind == CUI_PLOT_PATH_CLOSE); /* Submit commands to the application's path renderer here. */ } return 0; } ``` Compile with the same standalone C11 command shown above, using `-UNDEBUG` for this assertion-based example. ### Pie angles and arc queries `cui_plot_pie` keeps only defined positive finite values, preserving original indices and input order. Zero and negative values are skipped; missing numeric fields are ignored. It distributes the configured angular interval in proportion to values without sorting. Padding is finite nonnegative metadata, not subtracted from angles; start/end may reverse or coincide. Normalized summation avoids overflow when finite values have an enormous total. The last arc ends exactly at the configured endpoint. This differs from the source's unchecked f32 accumulator by retaining meaningful proportions for extreme finite inputs; very small proportions may still round to zero width. Angles are radians, zero at 12 o'clock and positive clockwise. `cui_plot_arc_centroid` computes the midpoint angle at the average radius, relative to an application-selected center. `cui_plot_arc_contains` takes a position relative to that center, includes both radius boundaries, and uses a normalized screen angle in `[0, 2pi)` with a half-open `[start_angle, end_angle)` interval. It ignores padding, exactly as frozen upstream's hit test does. Reversed or unnormalized intervals do not automatically wrap; applications must split wrapped intervals themselves. Radii must be finite with `0 <= inner <= outer` (stricter than source radius clamping). Query errors preserve output. Arc `value` and `index` are payload metadata, not inputs to centroid/hit arithmetic. Arc paths, tessellation and radial geometry are described below. Rounded corners, bar orientations/labels, path caches, axis/grid labels and full styled Plot composition remain separate work. Existing projected vertical bars still use explicit pixel width, clipping and baseline. Pure commands and math queries do not establish complete upstream Plot parity. ## Arc paths and bounded tessellation `cui_plot_arc_path` produces a closed circular/annular sector relative to `(0,0)`. `CUI_PLOT_PATH_ARC` appends an endpoint-arc command to the existing Move/Line/Cubic/Close vocabulary. Its `point` is the endpoint, `radius` is both circular radii, `clockwise` selects the screen sweep direction, and `large_arc` selects the sweep greater than pi. There is no ellipse rotation. Unused fields are zero. The renderer starts at the previous command's endpoint. Commands now have appended radius/flag members; rebuild consumers against the current header instead of assuming the old structure's byte size. A normal annular sector emits Move, clockwise outer Arc, Line to the inner endpoint, counterclockwise inner Arc, Close. Solid sectors use Line to the center instead of the inner Arc. Full turns use two semicircles per rim so coincident start/end points never collapse into an empty endpoint arc. At most seven commands are needed. Unlike the frozen implementation's artificial `0.0001` angular seam, full turns have no seam and ignore padding. Spans within `1e-12` radians of one turn normalize to exactly one turn. Finite radii satisfy `0 <= inner <= outer`; negative/reversed radii are errors, not source-style clamped radii. Positive spans must be at most one turn (apart from the tolerance above); greater spans are INVALID. Reversed/zero spans, zero outer radius, and sectors consumed by padding succeed with zero commands. For smaller sectors, outer angular inset is half `pad_angle`. For a nonzero inner radius the inner inset is half `min(outer / inner * pad_angle, span * 0.8)`. This follows the frozen padding width policy, but retains user padding for spans above pi instead of the source's `0.0001` override. Tiny nonzero radii/spans are accepted rather than applying the source's f32 epsilon cutoff. Angles reduce modulo one turn before coordinate arithmetic; finite large angle offsets can still lose a small configured span in the input double representation. `cui_plot_arc_flatten` constructs the same sector with Move/Line/Close only. Pass `segments_per_turn` from 4 to 1024. Each rim uses `ceil(rim_span * segments_per_turn / (2*pi))` equal angular chords, at least one for a nonempty rim. Maximum radial sagitta per chord is `radius * (1 - cos(pi / segments_per_turn))`, apart from floating-point rounding. The outer rim is traversed clockwise, the inner rim in reverse; a solid sector adds the center. At most 2051 commands are needed. This is bounded polygonal approximation, not a triangle mesh, anti-aliasing or GPU tessellation API. The application applies center translation, clipping, fill rule and styling. Both builders share capacity-query and no-partial-write contracts above. ## Radial lines and areas `cui_plot_radial_path` uses `cui_plot_radial_sample` with angle, `radius0`, `radius1`, and defined status. Angles follow the pie convention; vertices are relative to `(0,0)`. Defined radii are finite/nonnegative, stricter than the frozen RadialLine's unchecked radius accessor. Lines use only `radius1` and ignore `radius0`. SKIP bridges missing samples, matching frozen upstream; SPLIT starts separate contiguous runs. Input order controls polygon order. Open strokes emit Move/Line. A closed stroke adds Close only for runs of at least three vertices. Fill paths always close and omit runs with fewer than three vertices, matching frozen RadialLine; request fill and stroke separately if both are needed. `area=true` instead follows `radius1`, reverses all `radius0` vertices, and closes each run, including degenerate singleton runs. It ignores closed/fill flags. Radial area is a CUI extension: the frozen source contains RadialLine but no separate RadialArea generator. There are no natural radial curves, angular sorting, radius interpolation, dots or paint callbacks. The fixed scratch index array has the same 4096-sample bound as Cartesian paths. This standalone example builds a solid pie sector and a closed radar polygon: ```c #include #include #include "cui/cui_plot.h" int main(void) { const double pi = acos(-1.); const cui_plot_arc quarter = {0,1,0,pi/2,0}; cui_plot_path_command commands[32]; size_t count = 0; assert(cui_plot_arc_path(&quarter,0,20,commands,32,&count) == CUI_PLOT_OK); assert(count == 4 && commands[1].kind == CUI_PLOT_PATH_ARC); assert(cui_plot_arc_flatten(&quarter,0,20,16,commands,32,&count) == CUI_PLOT_OK); assert(count == 7 && commands[6].kind == CUI_PLOT_PATH_CLOSE); const cui_plot_radial_sample radar[] = { {0,0,10,true}, {pi/2,0,20,true}, {pi,0,15,true}, {1.5*pi,0,12,true} }; assert(cui_plot_radial_path(radar,4,CUI_PLOT_GAPS_SKIP,true,false,false, commands,32,&count) == CUI_PLOT_OK); assert(count == 5 && commands[4].kind == CUI_PLOT_PATH_CLOSE); return 0; } ``` Compile with the standalone C11 command above (`-UNDEBUG` for assertions). Tests cover quadrant coordinates, radius boundaries, arc direction/large flags, full turns, hollow/solid shapes, padding exhaustion and inner-pad clamping, tiny/extreme radii, flatten counts, missing radial runs and transactional errors. ## Reusing existing Sankey geometry The frozen Plot exports a real Sankey shape/layout solver (`shape/sankey.rs`), including topology, alignment, value scaling and link paths. CUI already exposes caller-owned Sankey node/link geometry via `cui_chart_sankey_layout` and `cui_chart_sankey_link_bounds` in [`cui_chart.h`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_chart.h), with Chart options for alignment, linear/sqrt value scale and relaxation iterations. See [`CHART.md`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CHART.md) for the current Chart implementation and limits. The pure model now exposes a shared Base graph solver plus the source ribbon path separately; see [the shared graph contract](#shared-base-sankey-graph-model). The original CUI Chart solver's math was extracted and audited against frozen Plot Sankey. Chart now delegates topology, relaxation and end widths to that shared seam; its adapter preserves Chart defaults, raw throughput and caller geometry. This avoids counting the older Chart API itself as standalone Plot parity. ## Bar alignments and grid quads `cui_plot_bar_layout` consumes already projected `cross`, band width, baseline, and value-end coordinates. Cross is the band's leading edge, unlike the older `cui_plot_project_bar` helper's mapped center. Bottom/Top produce vertical frames; Left/Right produce horizontal frames. The value axis bounds use `min(baseline,value)` and `max(baseline,value)`, so each orientation supports values on either side of the baseline. Zero band width or equal baseline/value returns valid degenerate geometry without clipping or rendering. The output includes source-exact default label origins. Vertical labels anchor at `cross+width/2`; above means value minus 12px, below means value plus 2px. Bottom chooses above on ties; Top chooses below on ties. Horizontal labels anchor at value plus/minus 2px and `cross+width/2-5`; Left chooses right on ties, Right chooses left on ties. Text alignment, actual text measurement and custom label content remain the application's responsibility. `gradient_angle` is 0/180/90/270 degrees for Bottom/Top/Left/Right, matching the frozen metadata; this does not add a gradient renderer. Inputs are finite, band width is nonnegative, and overflow/invalid inputs preserve the entire output. `cui_plot_grid_layout` implements frozen `grid.rs` geometry: vertical X lines first, then horizontal Y lines, each as a 1px quad centered on the configured coordinate. For example X=10 produces X bounds 9.5..10.5. Line lengths follow positive width/height; positions outside the surface are not silently clipped. Applications or ancestor boxes decide clipping. Dash entries alternate dash/gap starting at zero for each line. Odd patterns repeat twice to preserve SVG parity. Negative entries clamp to zero; empty or all-nonpositive patterns draw solid lines, matching the source. An even pattern with only positive gaps draws no quads. Final dashes clip to the line's endpoint. Nonfinite entries are INVALID. Tiny positive steps that cannot advance at the current double position return DEGENERATE rather than looping indefinitely. Extents are positive finite at most 16384; positions are finite within +/-16384. At most 256 lines per axis, 64 dash entries and 4096 quads are accepted. Capacity queries publish exact counts unless more than 4096 quads are needed; then CAPACITY publishes 4097 as a **lower bound** and no larger buffer bypasses the bounded generator. Coarsen the dash pattern or split the grid into smaller calls. Other errors preserve required count; all errors preserve output quads. No allocation or retained pointers are used; arrays must be disjoint and stable for the call. Tests cover orientation/tie behavior, source dash cases, centered quads, numerical failures, budget limits and transactional capacity failures. The frozen exports only ScaleLinear/Band/Point/Ordinal, and only Natural/Linear/ StepAfter Cartesian curves. There is no frozen StepBefore curve or Step scale being omitted under another name. Decimal value support, retained paint caches, custom label/content callbacks and renderer-specific styling are separate from these original C geometry APIs. ## Frozen Area fill/stroke paths `cui_plot_area_paths` complements the extended `cui_plot_path(...,area=true)` API. It models frozen `shape/area.rs` command construction explicitly: each `cui_plot_area_sample` has independent X/Y availability, and the optional baseline is one constant. Missing X/Y pairs are skipped and neighbors connect. When a baseline is supplied, the fill closes only if at least two valid pairs remain and both original endpoint X values exist. Those original X values are used for closure even if their Y values are absent. A missing original endpoint X leaves the fill open. Without a baseline the fill stays open. A singleton returns a Move-only fill and stroke, reproducing the source's early return. Fill and stroke have identical upper curves (Linear/Natural/StepAfter), then only fill appends its baseline segments and Close. This keeps closing edges out of the visible stroke, unlike painting a closed area with both fill/stroke colors on one command array. Source constructors/accessors are represented by caller-materialized samples rather than callbacks; accessor side effects are not reproduced. Available X and paired Y coordinates must be finite; unused Y values and absent baseline numeric fields are ignored. Curved-control overflow is checked before either output is written. `cui_plot_area_buffers` supplies separate stable/disjoint fill/stroke arrays and capacities. CAPACITY publishes both required counts without touching either array. INVALID/OVERFLOW preserve both counts and arrays. Count is bounded to 4096 samples. The implementation uses approximately 160 KiB of fixed sample/ index scratch storage on a typical 64-bit host and no allocations. Array contents must remain stable during preflight and emission. Both arrays may be NULL with zero capacities for a query. Returned counts describe commands, not whether a renderer produces a nonempty tessellation from them. The open fill path retains source command construction without claiming exact upstream tessellation. CUI's bounded rasterizer fills only explicitly closed runs; append a Close command in separate renderer-owned storage if an open contour should be implicitly filled. Native adapters can use their own implicit-fill rules. Pass fill and stroke as separate `cui_plot_shape` objects: ```c #include #include "cui/cui_plot.h" int main(void) { const cui_plot_area_sample points[] = { {0,2,true,true}, {1,4,true,true}, {2,0,true,false}, {3,3,true,true} }; cui_plot_path_command fill[32], stroke[32]; cui_plot_area_buffers output = {.fill=fill,.stroke=stroke, .fill_capacity=32,.stroke_capacity=32}; assert(cui_plot_area_paths(points,4,CUI_PLOT_CURVE_LINEAR,true,0, &output) == CUI_PLOT_OK); assert(output.stroke_count == 3 && output.fill_count == 6); assert(fill[5].kind == CUI_PLOT_PATH_CLOSE); assert(stroke[2].kind == CUI_PLOT_PATH_LINE); return 0; } ``` Compile with the standalone command above (`-UNDEBUG` for assertions). ## Complete frozen Plot export audit This is a feature audit of the pinned **base Plot module**, not a declaration of complete parity. It covers every exported family from `plot/mod.rs`, `scale.rs`, `shape.rs`, and public `label.rs`; private implementation behavior was inspected where it changes the public result. Evidence is in `test_plot.c`/`test_plot_styled.c` and the contracts above. A successful geometry case does not validate all paint styles, lifecycle behavior or f32 corner cases. | Frozen export/features | Current CUI route | Exact gaps or deliberate differences | |---|---|---| | `Scale`, `PlotValue`; f32/f64/feature-gated Decimal; tick and default nearest=0 | Explicit C double scale/category functions | No generic trait, Decimal arithmetic or named continuous nearest-index query; discrete nearest available | | `ScaleLinear::new` from unordered domain extent; extrapolating tick; reversed/equal pixel range | `cui_plot_linear_extent_init/tick` plus strict `cui_plot_scale` navigation | Extent/tick supports unordered finite values, empty/equal domains with no tick, reversed/equal pixel ranges and extrapolation; strict map still rejects equal ranges; CUI log/ticks/clamp/navigation are extensions | | `ScaleBand` dedup, leading reserved bands, width cap, inner/outer padding, step, nearest | Band init/layout/map/at/nearest | Uint64 application keys and bounded copied domain; stricter finite/padding/cap validation; no hash-generic domain or source unchecked negative widths | | `ScalePoint` owned domain, duplicate-first map, tick-at, nearest | Point init/map/at/nearest | Uint64 keys, borrowed arrays, bounded finite validation rather than owned generic Vec | | `ScaleOrdinal` domain/range replacement, unknown, first duplicate, cycling cloned output | Ordinal init/map; reinitialize to replace arrays | Byte copies preserve C value representations but do not deep-clone arbitrary payloads; pointers remain caller-owned; finite capacity bounds | | `Curve::{Natural,Linear,StepAfter}` | Cartesian path and source Area builders | Source Catmull-Rom controls and omitted final StepAfter vertical reproduced; no additional upstream StepBefore/Step scale exists | | `Line` data/X/Y accessors, source skip-gaps, stroke/width, dots/size/fill/stroke, paint/cache | Materialized samples, path commands, shape raster stroke | Dot geometry/themed drivers now available; no accessor callbacks or source renderer mesh cache; software solid/two-stop gradient Background route available; caller-owned software segment cache available; numeric bounds/precision differ | | `Area` data/X/Y1, optional Y0, fill plus separate 1px upper stroke, curves, paint/cache | `cui_plot_area_paths` separate contours; two raster shapes | Source accessor callbacks/cache/backgrounds absent; open/singleton upstream tessellator result not reproduced; extended per-point closed areas remain separate | | `Bar`, `BarAlignment` orientation/gradient angle, cross/band/base/value, fill(frame,alignment), labels, corner radii | `cui_plot_bar_layout`, projected vertical helper, rectangular paths | Geometry/label anchors, solid fill callback and Core per-corner styled driver available; pure rounded-bar paths support software solid/two-stop gradients; no generic label callback or native arbitrary Background renderer; negative width is rejected | | `Pie` positive-value arcs/index/padding and angular limits | `cui_plot_pie` | No accessor callback/borrowed arbitrary datum payload; stable normalized double summation replaces unchecked f32 sums; pad is metadata | | `ArcData`, `Arc` radii, centroid, contains, padded paint/cache | Arc metadata, centroid/contains/path/flatten | Strict nonnegative ordered radii rather than source clamping; explicit SOURCE_PADDING reproduces >=pi .0001 seam override and epsilon behavior, legacy SEAMLESS remains available; spans above one turn rejected; flattened output can use software segment cache, software two-stop Background route available for flattened paths, no native mesh cache | | `RadialLine` index-aware angle/radius, open/closed stroke, >=3-point fill, dots, paint | Materialized radial paths plus raster | Themed radial dot driver available, but no accessor callbacks; nonnegative radii enforced; split gaps and radial area are extensions, not separate upstream exports | | `Stack`, `StackPoint`, `StackSeries` keys/index, cloned datum, natural signed baseline, missing=0 | Series-major `cui_plot_stack` cells | Numeric stacking covered; key names/indices and data payload references supplied by application; no Rust-style cloning or retained series allocation | | `Sankey`, graph/link/node/layout/error types, topology/layout/layout_from, alignment, linear/sqrt, relaxation, ribbon path | Shared Base graph/path model and Chart adapter | Shared pure topology/layout/layout_from, adjacency queries, source defaults, scaled values and tapered ribbon path available; bounded capacities/strict finite nonnegative values and checked doubles differ; Chart adapter delegates while preserving its public contracts | | `PlotAxis`, `AxisText`, `AxisLabelSide`, `AXIS_GAP`, `axis_gutter` | Axis defaults/layout/paint/ticks/gutter | Line visibility, fixed source offsets/explicit colors via source constructor, legacy themed/font-scaled route preserved; dynamic Backgrounds absent | | `AxisLabelPlacement::{Outside,Inside}` | Application places labels/reserves gutters; Chart has its own layer | No standalone Plot placement enum or automatic gutter allocation; source PlotAxis itself only records position/side | | `Grid` X/Y, stroke, dash array, centered quads | Grid layout/themed paint | Dash parity/defaults and explicit-color paint covered; bounded counts, stricter finite input and DEGENERATE nonprogress behavior; Core Grid driver remains solid-only; generic software path route is separate; no native arbitrary Background | | `Text`, `PlotLabel`, text width/truncation helpers | Caller-owned PlotLabel collection/layout/paint and measured UTF-8 ellipsis helper | No automatic tooltip content/prepaint; frozen font_weight builder records a field that PlotLabel.paint ignores, not a verified weighted-text rendering feature | | `PathCache`, `PathCaches`, `ShapeKey` | Caller-owned flattened-segment cache, translated raster and shape-key helper | Cache hits skip builder/cubic flattening; empty builds are warm; opaque FNV keys preserve f32 bit sensitivity, not Rust hash values; no renderer-native stroke triangles or implicit keyed slot bank | | `PlotMotion` pointer Spring, enter/exit/appear Transitions | Caller-owned scalar transition clock with signed delay, easing and reversal shortening | Enter/exit projected clocks and scalar pointer glide available; explicit host policies and first-paint generation binding; no automatic theme projection/keyed renderer clock | | `PlotAppear` complete/progress/is_appearing/staggered and `PlotAppearScope` | Caller-owned completed-generation slot/registry and linear stagger clock | Bounded multi-plot completed map with explicit consecutive-frame lifetime; styled driver binds first-paint generation/linear time/easing/reduced motion via explicit host frame serial and active registry; no implicit scope tree | | `TooltipState`, `PlotHover` state/progress/deprecated focus/is_hovered/is_entering/glide; scope helpers hover_progress/is_hover_entering/pointer_spring | Caller-owned index/dots/crosshair memory with lingering exit state | Scalar pointer glide and styled resolver/content driver available; no implicit scope lookup or automatic OS/event-to-datum routing | | `Plot` trait prepaint/paint/id/interactive/appear_generation/appear/tooltip_state/hover/tooltip | Bitmap view plus optional `cui_plot_element` resolver/marks/children/tooltip driver | Caller-owned hover clocks and inert portal composition; current bounds/pointer/occlusion supplied by host; first-paint appearance binding available; no trait-equivalent renderer prepaint or automatic cache binding | | `PlotElement` full-size layout, element-state appear, current-bounds cursor, occlusion-aware mouse/touch tracking, tooltip prepaint/paint | Core layout/image semantic and validated click capture | Fixed bitmap extent with styled tooltip composition/exit clocks and explicit redraw requests; no full-size auto layout, current-frame Core hitbox/prepaint query, OS gesture detector or implicit scope state | | `origin_point` translation utility | Caller adds relative offsets before raster; Core offsets styled children | No separate named pure translation helper; ordinary finite coordinate addition remains caller responsibility | Missing renderer/lifecycle rows are real remaining Plot scope. Similar Chart, Core, effects or text APIs can be reused in application composition, but their existence does not make the standalone Plot contract equivalent to the frozen module. No row above asserts full widget parity. ## Dot geometry and source-style marker drivers `cui_plot_dot_layout(center,size,output)` models the Line/RadialLine marker quad: a square centered at the point, uniform corner radius `size/2`, and a fixed 1px border. Zero size succeeds with degenerate geometry; negative/nonfinite size and nonfinite centers are INVALID. Finite bound overflow preserves the entire output. This is pure geometry without a Core/theme dependency. Input-coordinate precision and half-size rounding follow C double arithmetic, not the frozen f32 bit pattern. The optional styled layer supplies Cartesian/radial marker and rounded-bar composition in `cui_plot_view.h`, described in [PLOT.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PLOT.md). These reuse Core's existing rounded-quad renderer; they do not turn the bounded path rasterizer into a gradient renderer. The pure `cui_plot_bar_path` also represents per-corner rounding as bounded cubic path commands. The frozen dot stroke fallback is reproduced for supported solid colors: explicit stroke overrides fill, otherwise the 1px border uses the resolved fill color. Theme defaults are a deliberate styled-layer policy, while frozen base dots default to transparent fill and frozen base bars default to black. ## Caller-owned hover and appearance lifecycle `cui_plot_hover_track` follows the frozen hover memory contract: a live datum updates the index, crosshair, borrowed dots and cursor; exit retains the last state until progress is zero. `hovered` means a currently live datum, while `has_state` also includes a fading tooltip. `entering` means live with exactly zero progress, which lets an application snap its existing pointer spring on entry. Unlike the source's optional cursor path, this API rejects live data without a cursor. Dot storage must remain valid throughout the exit fade; clearing at zero releases the borrowed pointer. Invalid inputs preserve memory. The helper does not resolve a datum, draw a tooltip or schedule frames. `cui_plot_appear_scope` is one slot per application identity, rather than the source's keyed map/thread-local scope. Call `cui_plot_appear_complete` before starting a clock. Record its linear progress with `cui_plot_appear_record`; only a completed generation persists. An interrupted appearance therefore restarts when reconstructed; a completed generation can resume immediately. Identity changes clear the slot. A new generation can replay without forgetting the old completed generation until the new one completes. Reset the slot when the enclosing application scope disappears: the helper cannot infer that event. `cui_plot_appear_stagger` implements the source's linear-time staggering: spread clamps to 0 through .95, the index clamps to the last mark, and count zero or one uses the original clock. Apply the application's existing easing **after** staggering. All clocks must be finite and in [0,1]. Pass progress one for appearance and live hover (zero for exited hover) when `cui_reduced_motion` is true; record completion so later frames do not restart the appearance. Outside a source-style hover scope, use progress one and entering false. This is a state contract, not an implementation of PlotElement, motion presets, retained element scopes, tooltip layout, occlusion or renderer path caches. ## Source-compatible Linear extent and tick The frozen `ScaleLinear::new` derives a domain extent from unordered input and its `tick` returns no coordinate when the domain has zero extent. Pixel ranges may be reversed or equal. `cui_plot_linear_extent_init` and `cui_plot_linear_extent_tick` expose this behavior separately from the strict `cui_plot_scale` navigation model: an empty input initializes [0,0], singleton or all-equal values produce `CUI_PLOT_EMPTY` on tick, and a nondegenerate domain with equal pixel endpoints maps every finite value to that endpoint. Tick extrapolates outside the extent. Empty/error results preserve the output pixel; invalid construction preserves the entire destination model. Construction accepts at most 4096 finite doubles, copies only their extent, and retains no input pointer. CUI uses checked double coordinates rather than the source's generic PlotValue and f32 output; NaN/infinity are rejected and unrepresentable extrapolation returns `CUI_PLOT_OVERFLOW`. This API has no inverse, automatic nice bounds, clamp, tick collection or category behavior. Existing strict scale validation, zoom and pan contracts remain unchanged. ```c #include #include "cui/cui_plot.h" int main(void) { const double values[] = {3, 1, 2}; cui_plot_linear_extent scale; double pixel; assert(cui_plot_linear_extent_init(&scale, values, 3, 12, 12) == CUI_PLOT_OK); assert(cui_plot_linear_extent_tick(&scale, 2, &pixel) == CUI_PLOT_OK); assert(pixel == 12); return 0; } ``` ## Rounded Bar paths for custom renderers The frozen Bar paints a normalized rectangle with independent corner radii. `cui_plot_bar_path` reuses `cui_plot_bar_layout` for all four orientations and values on either side of the baseline. Radii are ordered top-left, top-right, bottom-right, bottom-left in physical coordinates; they do not rotate when alignment changes. Each finite nonnegative radius clamps to half the shorter frame side, matching CUI's styled adapter policy. The source delegates rounded quad tessellation to upstream; this helper is a portable path representation of that style, not a claim of identical renderer output. A nondegenerate bar emits ten commands: Move, four alternating edge Lines and corner Cubics, then Close. The quarter-circle cubics use kappa `0.5522847498307934`; zero-radius corners still emit degenerate cubics. Existing `cui_plot_raster` flattens these cubics to sixteen chords each and samples pixel centers without antialiasing. Degenerate width/height returns `CUI_PLOT_EMPTY` and required zero. A zero-capacity query returns `CUI_PLOT_CAPACITY` and required ten; insufficient capacity preserves every output command. Invalid geometry or radii preserve both commands and required count. Caller radii may alias output: they are copied before any command is written. No gradient, labels, clipping, retained shape or renderer cache is introduced. ## Explicit frozen Arc padding policy `cui_plot_arc_path_ex` and `cui_plot_arc_flatten_ex` accept `CUI_PLOT_ARC_SOURCE_PADDING` to select the frozen Arc's padding/default rules. For every positive span at least π, the source overrides `ArcData.pad_angle` with .0001 radians. This applies to half circles, large sectors and full circles, not just the full-circle seam. Smaller sectors keep the supplied padding. Annular inner padding retains the source's outer-radius pad-width conversion and cap at 80 percent of the unpadded span. Inner radii at or below 1e-12 use a center wedge; outer radii or positive spans below 1e-12 produce no path. The source policy uses a single endpoint arc on each rim, leaving the intentional seam even for a full turn. Flatten uses these same padded endpoints. It is an explicit alternative to `CUI_PLOT_ARC_SEAMLESS`, the unchanged policy of legacy `cui_plot_arc_path` and `cui_plot_arc_flatten`: legacy full turns ignore padding and use two semicircles. The source's source-comment says full circle, but the actual conditional is `da >= PI`; this API follows that wider condition. Both policies retain CUI's finite nonnegative ordered-radius and at-most-one-turn bounds. The source separately clamps negative radii and permits unordered radii; those are not exposed here. Coordinates use checked doubles and a double π threshold, not identical source f32 rounding. Paths close explicitly; no cached upstream renderer path or exact tessellation claim follows. Centroid and contains remain independent of either paint policy, and contains deliberately ignores padding as the source does. Capacity/invalid errors preserve command buffers. ## Tooltip cursor gating from PlotElement The frozen PlotElement stores an optional cursor as a visibility gate, then resolves coordinates from the live pointer and current bounds during prepaint. `cui_plot_cursor_mouse` exposes its desktop per-frame refresh: supply the application's occlusion-aware hovered decision and live global position each frame. A visibility flip requests a corrective frame; movement changes the stored relative position without that per-frame request. For mouse-move event handling, notify/invalidate on `update.changed`, as the source event handler does. A stationary pointer therefore picks up the new local position after relayout. `cui_plot_cursor_long_press` exposes detected Started/Moved/Ended/Cancelled phases. Started opens only when hovered, inside bounds, and not default-prevented, and reports `prevent_default` for the application to consume. Moved does nothing before a start; once active it follows the gesture even outside the bounds and ignores subsequent hovered/default-prevented decisions. Ended and Cancelled close it. Changed long-press state requests a frame. The application detects long presses and owns gesture identity; these functions do not inspect OS input, steal capture, synthesize delays or resolve Core semantic targets. Use separate state for mouse and touch, or reset when switching modes. `cui_plot_cursor_resolve` uses stored state only as a visibility gate. It derives relative coordinates from the supplied live global pointer/current bounds, returns no cursor outside bounds or during appearance, and preserves relative output on no-hit. Bounds follow Core's half-open containment (left/top included, right/bottom excluded), rather than claiming exact upstream edge policy. Accepted positions and positive bounds must be finite; unrepresentable subtraction returns OVERFLOW. Invalid/overflow inputs preserve memory and outputs. Feed a resolved cursor to the application's datum resolver, then pass that optional datum to `cui_plot_hover_track`. Exiting can retain the previous tooltip while its progress fades. This sequence represents actual source cursor/state behavior without adding generic Plot callbacks, a tooltip renderer, an implicit retained scope or the source's prepaint/paint child tree. Application hit testing, occlusion, overlay content and paint order remain explicit. ## Source Sankey ribbon paths The frozen `sankey_link_path` connects the source node's right edge to the target node's left edge using a closed ribbon. `cui_plot_sankey_ribbon` holds those x coordinates, each end's center y and independent widths. The pure `cui_plot_sankey_link_path` generates the same five command roles: Move to the source upper edge, Cubic to the target upper edge, Line to its lower edge, reverse Cubic to the source lower edge, Close. Both cubics use the midpoint of source and target x for their controls. Each end independently uses `max(end_width,min_width)/2`; the nominal global link width is not substituted. Origin offsets apply to every endpoint/control point. Reversed x directions are supported; no flow-direction assumption or rerouting is added. Pass existing `cui_chart_sankey_node.x1/x0` and `cui_chart_sankey_link_geometry.source_y/target_y/source_width/target_width` into this structure to render Chart-computed layouts through the bounded Plot rasterizer or a custom path renderer. This keeps the pure model independent of Chart headers and avoids claiming that Chart topology equals full Plot Sankey parity. Graph construction, errors, layering, relaxation, layout_from, value scaling and alignment are now exposed by the shared Base model below; Chart preserves its own adapter policies. The path uses finite doubles, finite origin and nonnegative end/min widths; invalid inputs and unrepresentable translated geometry preserve output and required. A capacity query reports five, and insufficient storage preserves commands. Zero widths still produce a closed degenerate contour. Input geometry may alias command storage because the complete path is prepared before copying. The existing rasterizer uses sixteen chords per cubic, pixel-center sampling and no antialiasing; renderer-specific tessellation/cache and general Background styling remain unsupported. ```c #include #include "cui/cui_plot.h" int main(void) { cui_plot_sankey_ribbon link={10,90,30,50,8,16}; cui_plot_path_command commands[5]; size_t required; assert(cui_plot_sankey_link_path(&link,1,(cui_plot_point){0,0}, commands,5,&required)==CUI_PLOT_OK); assert(required==5 && commands[4].kind==CUI_PLOT_PATH_CLOSE); return 0; } ``` ## Shared Base Sankey graph model `cui_plot_sankey_topology`, `cui_plot_sankey_layout_from` and `cui_plot_sankey_layout` expose the frozen exported graph workflow without Core, Chart or platform dependencies. The implementation extracts the original CUI Chart C solver math into Base, with source-specific public contracts. This is shared solver provenance rather than a second independently invented layout algorithm. The Chart adapter preserves its existing defaults and raw throughput reporting; the pure model uses source defaults and scaled values. Caller graph storage contains node/link arrays and capacities. Inputs use node indices; topology copies and scales link values once, computes max(incoming, outgoing) node values, longest-path depth/height, structural adjacency counts, alignment and x coordinates. `cui_plot_sankey_link_breadths` factors the source internal end-width calculation for adapters that already have positioned nodes; it updates centers/end widths transactionally without changing nominal widths or topology. This is a shared Base operation, not an extra frozen export claim. Missing endpoints return INVALID with optional `CUI_PLOT_SANKEY_MISSING_NODE` and the missing index; cycles (including self links and zero-valued cycles) return INVALID with `CUI_PLOT_SANKEY_CIRCULAR_LINK`. Zero-valued links still count as edges. All graph arrays/counts remain unchanged on failure. Input buffers and the graph's two output arrays must be disjoint. Layout_from accepts an unmodified graph from topology/layout and reuses its ranks and already-scaled values, avoiding another topology sort. It recomputes alignment and geometry for the current extent/options. It does not rescale if value_scale changes, matching the frozen source. Node/source/target indices and rank consistency are checked; arbitrary edits to graph topology/value metadata are unsupported. `cui_plot_sankey_layer_count` returns zero for empty/invalid graphs. `cui_plot_sankey_node_links` queries incoming/outgoing link indices sorted by opposite node y0 with input-index ties; topology y0 zero gives input order. It replaces the source's allocated per-node vectors with bounded caller output. Defaults are node width 24px, padding 8px, Justify, six relaxation iterations, Linear scaling and extent[0,0,1,1]. Explicit zero width/padding/iterations stay zero, unlike the older Chart adapter's zero-selects-default policies. Alignment supports Left, Right, Center and Justify, including source structural-edge rules for isolated/zero-value nodes. The explicit `legacy_value_alignment` option (default false) supports Chart's older sum-based Justify/Center behavior, where zero-flow edges do not anchor alignment. This compatibility option is a CUI extension, not a frozen builder export. Relaxation sorts neighbors, resolves collisions, centers each column, and alternates a .15-height stagger for equal-height single-node columns when slack permits. End widths independently fill each node side proportionally, including imbalanced and sqrt-scaled graphs. Nominal link width remains the global value-to-height scale, not a minimum painted width; apply that minimum through the ribbon path helper. Coordinates/indices/scaled values remain explicit in output, with no element tree or renderer cache. Bounds are 256 nodes/1024 links/100 iterations, finite nonnegative values and width/padding<=16384. Extent coordinates have absolute value<=16384, positive height and nonnegative width; node width may exceed the extent width, as with source defaults in its unit extent. Empty/all-zero/isolated graphs are supported. Sqrt scales once during topology. Negative/NaN/infinite values are rejected rather than inheriting unchecked source arithmetic. Checked double/long-double math may differ from source f32 rounding; unrepresentable totals/intermediates return OVERFLOW transactionally. Large per-call fixed scratch is stack-owned (approximately 300KiB at the deepest layout call); no allocations occur. Caller storage stays live while queried/drawn. No full Sankey widget or source-error formatting/owned-vector API equivalence is claimed. ```c #include #include "cui/cui_plot.h" int main(void) { cui_plot_sankey_node nodes[3]; cui_plot_sankey_link_layout links[2]; cui_plot_sankey_graph graph={nodes,links,0,0,3,2}; const cui_plot_sankey_link input[]={{0,1,9},{1,2,4}}; cui_plot_sankey_options options=cui_plot_sankey_defaults(); options.value_scale=CUI_PLOT_SANKEY_SQRT; assert(cui_plot_sankey_topology(&graph,3,input,2,&options,0)==CUI_PLOT_OK); /* Measure labels against graph layers, then fix the available extent. */ options.extent=(cui_plot_rect){0,0,200,100}; assert(cui_plot_sankey_layout_from(&graph,&options)==CUI_PLOT_OK); assert(graph.nodes[1].value==3 && graph.links[1].value==2); return 0; } ``` ## Bounded appearance scope registry The frozen `PlotAppearScope` holds a map from plot global identity to its last completed generation. This matters in virtual lists: a plot that disappeared after completion skips its draw-in when it returns, while an interrupted plot starts again. `cui_plot_appear_registry` now models that multi-plot behavior rather than asking one single slot to represent the entire scope. Initialize it with caller-owned `cui_plot_appear_scope` storage (capacity 0..4096), then call `cui_plot_appear_registry_begin` for every frame the scope is painted, using a stable scope identity and host frame serial. The same serial is idempotent; the next serial preserves completed entries. A skipped/backward frame or changed scope identity clears the logical count. Serial wrap is treated as a discontinuity. Call end when leaving the scope. Query/record require an active scope, preventing accidental use of a disposed scope's entries. Explicit init discards remembered completions without touching borrowed storage. Before starting a plot's clock, query `(plot_identity,generation)`. A completed match draws immediately at progress one. Otherwise run its independent clock and record linear progress. Only progress one inserts/replaces the completed generation. An incomplete appearance consumes no slot and leaves the previous completed generation intact, exactly as the source map does. A completed plot's entry remains when that child disappears while the enclosing scope is still painted. At capacity, completing a new identity returns CAPACITY without mutation; replacing an existing identity still succeeds. The host chooses a storage/error policy instead of silently evicting remembered plots. Nested source scopes choose the innermost map. Portable composition passes the explicit inner registry to its children; after leaving it, use the outer one again. There is no global/thread-local lookup, retained Element child, implicit window state or first-paint scheduler. Identity values represent application plot identities unique inside that scope (not automatic global path hashing). The registry stores only numeric completed generations, not plots/resources or motion state. Scope disposal and frame cadence remain host responsibilities. ```c #include #include "cui/cui_plot.h" int main(void) { cui_plot_appear_scope entries[4]; cui_plot_appear_registry scope; bool complete; assert(cui_plot_appear_registry_init(&scope,entries,4)==CUI_PLOT_OK); assert(cui_plot_appear_registry_begin(&scope,100,1)==CUI_PLOT_OK); assert(cui_plot_appear_registry_record(&scope,7,42,1)==CUI_PLOT_OK); assert(cui_plot_appear_registry_end(&scope)==CUI_PLOT_OK); /* Child 7 may be absent in frame 2; scope persistence remains. */ assert(cui_plot_appear_registry_begin(&scope,100,2)==CUI_PLOT_OK); assert(cui_plot_appear_registry_complete(&scope,7,42,&complete)==CUI_PLOT_OK); assert(complete); assert(cui_plot_appear_registry_end(&scope)==CUI_PLOT_OK); return 0; } ``` ### Projected transition clocks `cui_plot_transition_step` supplies the scalar `Transition` clock used by frozen `PlotMotion` enter/exit channels. Zero-initialize a separate caller-owned clock per stable channel. Supply monotonic seconds, a finite target, and a policy with nonnegative duration and signed delay; NULL easing uses source cubic-out. A synchronous easing callback may implement another easing, must return finite samples, and must not mutate the clock. It is called once per sample and again at a retarget's initial progress. Returned `request_frame` tells the host when to schedule another frame; the helper does not schedule, retain element IDs, or project theme policies automatically. The first target is adopted immediately. Later retargets first sample the old trajectory, then start from that value. Reversing to the prior origin shortens the new duration by the traversed easing fraction, including the source's repeated-reversal factor. Other retargets restore the policy duration. Current delay/easing apply to every sample, while duration is stored at retarget time. Positive delay yields `DELAYED`; negative delay advances the initial sample. Reduced motion or zero duration snaps immediately and bypasses delay. Backward timestamps saturate elapsed time to zero. Invalid policies/state/callback results preserve clock and output; nonfinite interpolation reports overflow. These are finite double scalar channels, rather than generic source `Interpolate` values. ### Scalar pointer spring glide `cui_plot_spring_step` covers the frozen `PlotHover.glide` scalar Pixels channel. Use separate zero-initialized `cui_plot_spring_clock` states for independently keyed x/y coordinates. `cui_plot_spring_defaults(response_seconds)` matches source damping 1, epsilon .001 and travel enabled; response zero snaps. Response is the undamped oscillation period, not a completion deadline. Damping below one can overshoot, above one approaches slowly, and zero is undamped. The analytic oscillator is adapted from CUI's existing tab spring C mathematics, with original clock ordering implementing the frozen source contract. The first value is adopted immediately. A later call advances elapsed time toward the **previous** target before adopting its new target, preserving current position and velocity. `request_frame` remains true until both displacement and speed are below epsilon, then position snaps exactly to target with zero velocity. A resting call leaves its timestamp unchanged. Backward timestamps saturate the elapsed step to zero; the host should normally provide monotonic seconds. Current policy parameters govern the elapsed step, as in the source. Reduced motion, `travel=false`, response zero, or `entering=true` pins both position and velocity to the target. Feed `cui_plot_hover_memory.entering` to the latter argument to avoid gliding from a previous hover location on the entering frame. Finite double channels and checked arithmetic are CUI's bounded contract, rather than source f32 renderer values. Invalid parameters/state preserve state/output; nonfinite propagation reports OVERFLOW without mutation. Very small responses, extreme magnitudes/damping or elapsed oscillation angles may exceed representable math. The host must schedule requested frames and project its theme policy. Renderer keyed clocks, implicit PathCaches slot lifetime and renderer prepaint tooltip layout remain absent; host-serial first-paint appearance and styled immediate portal composition is available through the host-bound PlotElement seam. ### Shape keys and cached tessellation `cui_plot_shape_key_init(extra)` plus `_point` and `_float` hash the same kinds of origin-relative projected points and geometry extras used by frozen ShapeKey. CUI uses original FNV-1a over native representations, not Rust DefaultHasher; keys are opaque process-local values and must not be persisted or compared with upstream numeric hashes. Point coordinates are checked finite and float-range, then converted to f32 to follow source point key sensitivity. Float append keeps raw bits, including signed zero. Include curve style and other geometry inputs in extras; hashes can collide, as with the source's opaque 64-bit key. The styled `cui_plot_path_cache_get` caches flattened relative segments in caller storage. A key change invokes the build callback once, consumes its borrowed Move/Line/Cubic/Close commands synchronously, and tessellates each cubic into 16 chords once. Hits skip both callback and tessellation. An empty build is cached and `is_warm` is true even on its first empty build, matching the actual source implementation rather than the misleading reuse wording in its doc comment. `cui_plot_raster_cached` consumes those cached segments and a separate origin, fill, stroke and stroke width. Scrolling/origin and paint-color changes reuse the same geometry. Origin translation affects pixels while retained relative segment storage remains unchanged. Pixel rasterization still happens on every call; this is a software polyline tessellation cache, not cached pixels or upstream's native stroke/fill triangle mesh. Stroke width is evaluated at raster time here, unlike source PathBuilder's stroke tessellation, so this route can reuse geometry across width changes. ARC commands must first be flattened using the existing arc helper. Cache init accepts at most 4096 segments. Invalid commands/origins and capacity failures preserve cache/storage/output (a failed miss invokes its callback, but does not change the key). Successful EMPTY changes the key and returns an empty borrowed path. Relative and translated coordinates must stay within +/-16384. Borrowed views remain valid until a successful miss replaces storage. All arrays must be stable/disjoint from cache metadata, output and pixels. The host owns one cache per stable shape slot, or two independent caches for Area fill/stroke; no window/element keyed `PathCaches::for_paint` lifecycle or slot auto-growth exists. The Core renderer still has no native cached path command/triangle seam. ### Styled PlotElement composition `cui_plot_element` layers a portable driver onto the existing bitmap/axis view. The host supplies **current** global bounds, live pointer position, and an occlusion-aware `hovered` decision; those bounds must match actual frame layout and bitmap extent. Core's `cui_bounds` is previous-frame data and must not be passed as current bounds during scrolling/relayout. A real Core prepaint hook and current hitbox query are still required for automatic source renderer behavior. One zero-initialized state is retained per stable owner. Resolver preflight uses live pointer minus current bounds every frame, including a stationary pointer while layout moves; appearance suppresses the live datum. The synchronous resolver returns OK with relative datum geometry or EMPTY. It may not compose UI or mutate driver storage. Enter/exit transition policies use Core frame time and reduced-motion, must produce normalized progress, and request redraw through `cui_invalidate`. Borrowed dot arrays must survive replacement or completed exit. The last datum and relative cursor remain during exit, then are dropped at zero. Bitmap/axes compose first, then marks and ordinary-child callbacks. The primary activation callback uses existing validated Core release routing with current host bounds. Tooltip content composes last in a plot-sized global portal at layer1 (or a supplied positive layer), with inherited hover opacity. The callback positions its body relative to that portal; un-clipped content may extend outside plot bounds. Tooltip descendants are inert: they paint, but cannot take semantics, focus or activation. This display-overlay policy is a bounded CUI choice; source `AnyElement` tooltips can contain arbitrary interactive content. Touch hosts run the existing long-press reducer on `state.cursor` before this call and set `touch=true`; desktop mouse visibility is then not synthesized. Long-press default prevention and host OS gesture detection stay explicit. On a passive/disabled plot the driver clears hover/exit-clock state while preserving appearance, skips resolver/tooltip, and still composes ordinary children. Owner changes reset state. Callback box stacks must balance, and text/bitmap payloads remain live through renderer completion. Preflight errors preserve state and submit no plot; general Core composition capacity is subject to the existing partial-submission contract. There is no separate callback measurement/prepaint pass or retained Element tree. ### First-paint appearance channel binding `cui_plot_appear_step` implements frozen Presence's first-frame 0→1 clock, separate from transition's first-target adoption. It stores linear time, applies projected easing only to `progress`, and supplies `cui_plot_appear_value_stagger` to sample each mark's clamped local time before easing. Default NULL easing is cubic-out; zero duration or reduced motion completes immediately. Completed samples return one without invoking easing. Signed delay and checked clock arithmetic follow the existing transition seam. Policy callback/user data remain borrowed while a sample is used; invalid callback results preserve state/output. Enable `cui_plot_element_options.has_appearance`, choose generation and policy, and increment host `frame_serial` every frame, including omitted plots. The styled driver owns the first-paint clock in its caller state, restarts after a serial gap/backward serial, owner rekey or generation change, and notifies `on_appear` before datum resolution and bitmap composition. This callback may prepare caller-owned bitmap/mark geometry, but must not submit UI or mutate options/driver/scope storage; its sample pointer lives only for that call. The driver does not choose a reveal/fade style for a bitmap: the source Plot also decides what appearance looks like. Geometry callbacks can use the sampled progress or stagger values; changed bitmap payloads require the normal Core bitmap revision/lifetime contract. Appearance runs even for disabled/passive plots and ordinary children still compose. Hover is suppressed while linear time is below one, even if easing already returned one, and appearance/hover frame requests are combined. Existing manual `appearing` suppression remains an additional gate. No generation means a complete sample. Defaults are Base's zero-duration policy; product timing is explicitly projected by the host, not inferred from a generic theme field. Pass an active innermost `appear_scope` registry begun with the same serial. Only a completed generation is recorded. A finished plot omitted then remounted under that still-painted scope is complete immediately; an unfinished one restarts. Changing/removing the scope resets the local appearance channel. Scope rekey/gaps clear remembered completions through its existing begin/end contract. Registry capacity errors are preflight failures: no plot/state/completion entry is submitted or changed. Explicit caller frames, registry storage and unique owner IDs substitute for window keyed element state; they do not add an implicit retained scope tree or a renderer layout/prepaint scheduler. ### Background draw routes and native renderer gap Frozen Base Plot exports no standalone `PlotStroke` or `Fill` wrapper. Its shapes accept upstream `Background` directly. The pinned dependency is `upstream-pre =0.3.8`; its Background supports solid, two-stop linear gradients, slash/checkerboard patterns, and sRGB/Oklab interpolation. Plot's Bar explicitly uses a supplied background verbatim and never rotates its angle for orientation. Source story area gradients also use reversed stops (opaque at1, transparent at0). CUI's portable `cui_plot_background` supports all four source background kinds on cached software paths. `cui_plot_linear_background_source` selects the pinned shader's short-axis rescaling and dominant-axis projection; angle0 points top, 90 right, increasing clockwise. The earlier `cui_plot_linear_background` retains its full projected diagonal for compatibility. Both preserve stop order, clamp outside stops and define equal stops as a right-continuous hard edge (source shader division at equal stops is undefined). Finite stop positions remain0..1. `CUI_PLOT_COLOR_SRGB` interpolates encoded RGBA8 channels. `CUI_PLOT_COLOR_OKLAB` decodes sRGB bytes to linear RGB, uses the standard Oklab matrices/cube roots, mixes Lab and alpha independently, then encodes and clamps RGB to the byte gamut. Endpoints preserve their exact input bytes, including transparent RGB. This is straight alpha, not premultiplied interpolation: transparent endpoint RGB still contributes. Black/white halfway is99 in Oklab versus128 in encoded sRGB. upstream accepts Hsla and prepares shader colors in a different representation; this checked RGBA8 CPU route does not promise byte-identical GPU color output. `cui_plot_pattern_slash(color,width,interval)` retains the pinned source's unusual packing: each parameter is converted to f32, multiplied by255 and truncated, then packed as `width_scaled*65535+interval_scaled` and rounded to f32. Shader width decoding divides that float by65535 then255, without flooring; interval uses its remainder modulo65535. The diagonal period is their decoded sum times sin(pi/4). Signed remainder and the source one-pixel alpha coverage ramp are preserved. Width/interval must be finite nonnegative, width<=257, interval<257, the packed integer must fit uint32, and the decoded period must be positive. Zero period and overflowing packing are rejected rather than inheriting undefined arithmetic. Widths within the same1/255 truncation bin have identical coverage; f32 packed precision can affect the decoded spacing. `cui_plot_checkerboard(color,size)` converts size to f32; finite size1/255..16384 is accepted. An odd `floor(x/size)+floor(y/size)` cell is colored, an even cell transparent. The shader's signed remainder behavior is retained: negative odd cells also become transparent. Both patterns anchor at the explicit frame minimum corner. Parameters use raster pixel units; expanding the frame does not stretch a pattern. Source Background has no independent scale/offset field. The host chooses pixel-unit sizes and the frame origin explicitly, including any device-scale conversion. Pattern alpha multiplies the supplied color alpha. `cui_plot_raster_backgrounds` consumes cached relative segments, explicit `background_frame`, independent fill/stroke backgrounds and stroke width. Gradient projection and Lab endpoints are prepared once per shape; covered pixels perform bounded color evaluation. Origin moves frame and geometry together without rebuilding. Backgrounds are never rotated for bar alignment. Buffers are borrowed, stable and disjoint from pixel output during the call. The existing limits remain64 shapes,4096 segments per shape,1024² pixels, 64-million pixel*segment work, positions/frame corners within +/-16384 and stroke width0..1024. Invalid/capacity failures preserve all pixels. Pattern and Lab evaluation add constant work per covered pixel, with no allocation or unbounded tessellation. Old solid APIs retain their defaults. Quad-based Bar/Dot/Axis/Grid drivers still accept solid colors; use pure paths and this software route for gradient/pattern fills and strokes. The shader audit uses the exact `upstream-pre-wgpu =0.3.8` crate from the frozen lock (checksum439c5421cafe1a7cf68d0c0ae5cc82b26fad6b0e6345ac98d20acaf1f2463914), `src/shaders.wgsl` gradient preparation and `background_color`. Double geometry, RGBA8 output and segment rasterization remain deliberate portable differences. Native source painting requires a path/mesh command with bounds and tessellated vertices, fill/stroke background and clipping/coverage attributes. Source PathCache origin translation moves bounds and XY vertices while keeping coverage attributes unchanged. Core currently exposes rectangle/text/bitmap draw routes, not this path/mesh contract; adding it belongs to the integrator's Core/adapter work. The software segment cache does not become a native stroke triangle cache through naming, and per-pixel rasterization still runs on each frame. ### Native triangle preparation and coverage The pinned upstream `PathBuilder` uses Lyon fill/stroke tessellation, expands its indexed result to triangle-list vertices and assigns every vertex ST=(0,1). `PathVertex` holds XY, ST and content-mask bounds; paths carry their bounds and Background. The separate direct quadratic `Path::curve_to` emits ST=(0,0), (.5,0),(1,1) on its control triangle. The path shader interpolates ST and computes `f=S*S-T`, screen gradient `2*S*grad(S)-grad(T)` and coverage `clamp(.5-f/length(gradient),0,1)`; if length(grad(S))<.001 it uses coverage1. Fragments produce premultiplied `(RGB*alpha*coverage,alpha*coverage)` regardless of the generic quad output mode. Source origin translation changes XY and bounds but not ST; device scaling changes XY/content masks but not ST. `cui_plot_fill_mesh` produces usable portable triangle-list vertices with relative `xy` and constant `st=(0,1)`, plus geometric bounds. Caller-owned arrays retain those vertices and can translate them when sending them to a native renderer. The original allocation-free ear-clipping implementation supports a single simple implicitly closed contour in either winding, including concave contours, with3..256 distinct vertices and coordinates within +/-16384. It checks all nonadjacent edges before tessellation. Holes, touching/self-crossing edges, repeated adjacent vertices and collinear corners are rejected; this is not a replacement for all Lyon fill rules, curve flattening or stroke joins/dashes. Use existing geometry/flattened paths to supply the contour, omitting the repeated closing endpoint. The256-vertex bound caps both stack storage and cubic-time worst-case ear search (under17 million candidate tests). No platform or Core renderer types enter this pure Base API. A NULL output with capacity0 queries the required expanded vertex count and returns CAPACITY. CAPACITY changes only `required`; vertices and bounds remain unchanged. Other errors preserve all outputs. Input/output buffers must be stable and disjoint. Successful output bounds include contour corners; they do not add an antialias margin or content mask. `cui_plot_mesh_coverage` evaluates the exact source analytic formula for explicit interpolated ST and derivatives; constant-ST triangles have solid coverage. It does not infer triangle-edge coverage, schedule rendering or build a retained native cache. Zero gradient at a nonconstant-S point is DEGENERATE; nonfinite arithmetic is OVERFLOW. Core mesh submission, background shaders, clipping, triangle-edge sampling and adapter resource caching remain integrator-owned renderer work. The software segment cache and this mesh preparation are separate representations. ### Source Hsla and premultiplied path output `cui_plot_hsla_background` and `cui_plot_hsla_background_sample` provide the pinned path shader's separate color contract. Hsla fields are normalized finite float0..1. The source hue/chroma/lightness conversion produces RGB that the shader interprets as **linear**, unlike the existing encoded `cui_color` byte contract. Solid and pattern backgrounds use that linear RGB directly. A two-stop SRGB gradient encodes each endpoint, mixes encoded RGB and independent alpha, then decodes RGB. An Oklab gradient converts the linear endpoints to Lab, mixes Lab/alpha independently and converts back to linear RGB. Transparent endpoint RGB participates before final premultiplication; interpolation is not performed on premultiplied Lab values. Reversed stops and the checked equal-stop hard edge retain the existing portable rules. The sampler returns `cui_plot_linear_rgba` with RGB multiplied by both resulting alpha and explicit coverage0..1. This matches `fs_path_rasterization`, which always emits premultiplied path fragments. It performs no byte quantization, display transfer or gamut clipping: small out-of-gamut Oklab results remain visible to the consuming renderer. CPU double geometry/transforms with float output preserve the source equations, not GPU f32 instruction-level rounding. For black/white midpoint, opaque SRGB is approximately.214041 linear RGB and Oklab is.125; transparent black/opaque white also produces alpha.5 and therefore premultiplied RGB.107021/.0625 respectively. These differ intentionally from the encoded RGBA8 sampler's128/99 byte results. `cui_plot_raster_hsla` uses the same cached segment geometry, fill/stroke order, round-segment stroke coverage and bounded work as the byte rasterizer, but writes caller-owned **linear premultiplied float RGBA** pixels. Stride and capacity are in RGBA pixels (not bytes). Its clear input is already premultiplied, with finite RGB0..alpha and alpha0..1. Compositing uses `above + below*(1-above.alpha)` for both RGB and alpha. Gradient/Lab endpoint preparation happens once per shape; patterns preserve fractional alpha without intermediate byte rounding. All validation/capacity errors preserve the entire pixel output. Padding beyond the active width remains untouched. Input/geometry/background/output buffers must remain stable and disjoint during the call. This float route is usable preparation/reference output for native adapters, not a display buffer or automatic native Background command. Consumers choose their target transfer/format. It does not add Lyon curve tolerance, stroke joins/dashes, triangle-edge antialiasing or renderer resource caches. ### Adaptive cubic contours and default stroke meshes The frozen upstream PathBuilder delegates curves to Lyon. The lock pins `lyon_geom1.0.19` (checksum4336502e29e32af93cf2dad2214ed6003c17ceb5bd499df77b1de663b9042b92) and `lyon_tessellation1.0.21` (checksumdabea159dc6eea9171a541b458134b70ca95e3162d068132b2b3b9bc01aad06e). Its default fill/stroke tolerance is0.1 pixels; stroke defaults are width1, Butt caps, Miter joins and miter limit4. The pinned `stroke.rs` compares squared normal length against `4*limit*limit`: its limit is miter offset length divided by **full stroke width**, not half-width. This source detail is preserved. `cui_plot_cubic_flatten` supplies an original adaptive de Casteljau route from four explicit cubic control points to a caller-owned polyline including start and end. Each accepted subcurve's control hull is within the caller's tolerance of its chord segment. Checking distance to the finite chord also preserves collinear overshoot/backtracking; checking only an infinite supporting line would incorrectly collapse such a curve. Use0.1 for the pinned default tolerance. Smaller tolerances add subdivisions. Finite controls/positions must be within +/-16384 and tolerance1e-6..16384. The route is bounded to4097 output points and 24 subdivision levels, without allocation. The algorithm differs from Lyon's cubic-to-quadratic approximation and does not claim identical sample positions. `cui_plot_stroke_mesh` converts a single open polyline into nonoverlapping triangles for its stroke outline. It uses Butt caps (no extension past endpoints) and centered Miter joins. Corners exceeding the pinned full-width miter test bevel the outer edge; the inner intersection remains a miter. Straight forward runs omit redundant corners. Width0 yields EMPTY with required0/bounds0; positive width<=1024 and miter limit1..64 are accepted. A90-degree corner remains mitered at limit1; a150-degree corner exceeds that limit. Its triangle vertices have source tessellator ST=(0,1), reusable by the native mesh seam. The caller may pass adaptive cubic points directly to the stroke route when the polyline has2..64 points. Geometry outside +/-16384 returns OVERFLOW. Exact reversals, repeated adjacent points and touching/self-overlapping outlines fail rather than producing ambiguous overdraw. This route has no holes, closed-path joins, dash splitting, variable widths or Round/Square caps; it does not replace all Lyon stroke options. Source complex stroking remains a gap. The existing software raster's16-chord/round-segment behavior is unchanged. Both functions support caller-capacity queries and preserve geometry on errors. Cubic caller CAPACITY sets the exact required count; an internal subdivision or point-budget CAPACITY preserves required too because no complete answer exists. Stroke uses the fill mesh transaction contract, with at most252 outline points and750 expanded vertices. Input/output buffers must remain stable and disjoint. Retaining meshes, moving XY/bounds, clipping, triangle edge coverage and paint submission belong to the host/Core integration. ### Multi-contour fill rules and arrangement triangles `cui_plot_fill_mesh_contours` adds implicitly closed polygon contours with EvenOdd and NonZero rules. The frozen Area, Arc and filled RadialLine call `PathBuilder::fill()`. Inspected published `upstream-pre=0.3.8` `src/path_builder.rs:75..97` selects `FillOptions::default()`; Cargo.lock pins `lyon_tessellation=1.0.21`, whose `src/lib.rs:476..490` defaults to EvenOdd, tolerance0.1 and intersection handling enabled. Select `CUI_PLOT_FILL_EVEN_ODD` for that source fill rule. NonZero is an explicit extension for callers supplying oriented contours. The implementation decomposes the polygon arrangement into horizontal bands at every vertex and proper edge intersection. Inside each band edges have a stable horizontal order; parity or signed winding selects filled intervals, which become trapezoids split into non-indexed triangles. Holes, crossing contours, self intersections, coincident edges, repeated closing vertices and collinear vertices are supported. Horizontal and zero-length edges contribute no winding. Triangle ST is `(0,1)` and bounds cover emitted fill geometry. Empty or cancelled geometry succeeds with zero vertices and zero bounds. Total input points are bounded to256, with at least3 per contour. Coordinates must be finite within +/-16384. Caller scratch consists of `long double` events and `size_t` edge-order arrays. For n input points reserve at least `n+n*(n-1)/2` events and n indices (32896 events and256 indices at the limit). Scratch may change on every result and must be disjoint from inputs, outputs, bounds and count. Workspace shortage returns CAPACITY preserving count; mesh shortage returns CAPACITY publishing its exact required vertex count. Both preserve mesh and bounds. A NULL mesh/zero capacity queries the count. Validation errors preserve all output data. Two traversal passes avoid partial output, without allocating or retaining input data. This is an original arrangement tessellator, not Lyon triangle topology. Predicates use `long double` but do not require extended precision; nearly coincident events can round together on platforms where it equals `double`. Intersection event heights are rounded to output `double` precision before sorting, preventing extra scratch precision from creating invisible bands. Band endpoint tests avoid requiring a representable interior midpoint. No exact predicate arithmetic, configurable snapping tolerance, source f32 rounding or source curve approximation is claimed. Flatten curves explicitly before using this API. The old `cui_plot_fill_mesh` keeps its stricter simple-contour contract. Complex source stroke joins/dashes, direct curved ST patches and automatic path-command/renderer routing remain separate gaps. Input and generated triangle limits remain bounded CUI extensions rather than full Lyon parity. Headless tests compare donut and bowtie areas, hole interior coverage, contour orientation and coincident-contour cancellation. Independent ray winding and triangle coverage oracles exercise overlapping and crossing contours, shared endpoints, repeated closure and nearby crossing bands. Capacity failures and extreme/nonfinite inputs verify output preservation. Native warning builds, ASan/UBSan and actual WASI execution exercise the portable path. ### Closed, capped, joined and dashed triangle strokes `cui_plot_stroke_mesh_ex` supplies closed contour strokes, independent Butt, Square and Round endpoint caps, and Miter, Bevel, Round and MiterClip joins. `cui_plot_stroke_defaults()` selects width1, miter limit4, Butt caps and Miter joins, matching the pinned source defaults. The source RadialLine closes its stroke for more than2 points; closed CUI inputs require at least3 points and may repeat their first point at the end. Caps are ignored for closed strokes. The existing `cui_plot_stroke_mesh` retains its original strict contract. Stroke geometry is the NonZero union of consistently oriented segment quads, join wedges and cap polygons, passed through the multi-contour arrangement backend. The resulting triangles avoid repeated coverage at joins and self crossings, including overlapping square dash caps. Closed loops retain their interior hole. Miter-limit comparisons use offset-length/stroke-width, matching `lyon_tessellation=1.0.21 src/stroke.rs:2316..2319`; over-limit Miter joins bevel. MiterClip follows the pinned source clip line at `miter_limit*half_width` (`src/stroke.rs:1722..1726,2277..2306`). Exact reversal uses the segment union seam for bevel/miter variants and a disk for round joins; source tessellator vertex ordering and precision are not reproduced. Round disks are inscribed regular polygons with an explicit4..64 segments per turn (default32); their radial chord error is at most `half_width*(1-cos(pi/segments))`. This explicit tessellation budget differs from Lyon's default curve tolerance0.1. Points are bounded to64, width0..1024, miter limit1..64 and finite input/generated coordinates within +/-16384. Generated primitives may total no more than256 points/85 polygons. A round stroke with many corners can exceed this budget even with valid input; internal CAPACITY preserves count, mesh and bounds. Generated geometry outside the coordinate bound returns OVERFLOW. Duplicate consecutive points return DEGENERATE. Width0 returns EMPTY with zero count and bounds after validation. The caller supplies the fill workspace; reserving32896 events and256 edge indices covers the generated-primitive limit. Output size queries and output capacity failures publish the exact vertex count without writing mesh or bounds. Workspace shortages preserve count. Input, workspace and output buffers must be disjoint. No allocations, platform types or renderer dependency are added. `cui_plot_stroke_mesh_dashed` implements the pinned upstream `PathBuilder::dash_array` alternating draw/gap policy for flattened polylines. Inspected `upstream-pre=0.3.8 src/path_builder.rs:108..119` repeats odd arrays twice; `:276..304` splits measured draw ranges into separate stroked subpaths. The CUI implementation preserves joins inside a run and applies caps at each run end. Closed input includes its closing edge, but drawn ranges at the beginning and end are distinct capped runs, following source range splitting. Source Plot Line itself exposes no dash setter; this API covers its underlying path builder. Patterns require1..64 finite strictly positive distances. Source zero/negative patterns can fail to advance its loop; CUI rejects them. Splitting is bounded to1024 steps and64 points per drawn run, with the same256 generated primitive point budget. Nonadvancing positive distances return DEGENERATE; budget failures return CAPACITY preserving all output metadata. Polyline arclength is exact segment length rather than the source curved-path measurement tolerance0.01. No phase offset is introduced because the source API supplies none. Headless checks verify cap areas/bounds, closed seam continuity and holes, reversed contour orientation, each join variant, old default area compatibility, self-crossing round-stroke distance/triangle-coverage oracles, and dash phase, odd repetition, corner joins and unmerged closed seams. Tests also exercise output/workspace/internal budgets, nonfinite patterns and generated overflow. Exact Lyon triangle topology, automatic path-command curve routing, variable-width attributes and source curve sampling remain outside these APIs. --- ## Popover source anchors Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/POPOVER_ANCHORS.md # Popover source anchors Semantics are audited against upstream reference commit `87d10ae5e1299d1be18670a37570c5402f952e34`, especially component Popover, base Popup live anchor positioning and Positioner corner clamping. `cui_popover_begin` is an additive C API for source-style Popover positioning and arrows. Existing `cui_surface_begin` retains its legacy side placement, 6px gap, opposite-side overflow selection and size reduction. Existing public state and options structs have unchanged ABI. Recompile/link against the new library to use the added symbols. This API is C-only until binding coverage is explicitly updated; family catalog presence does not imply binding option parity. ```c cui_surface_options options = { .viewport = {0, 0, 640, 480}, .anchor = {120, 80, 100, 32}, /* current-frame trigger rectangle */ .width = 240, .height = 160, .margin = 4, .hide_close = true, .popover_appearance = CUI_POPOVER_APPEARANCE_SOURCE, }; cui_popover_position position = { .mode = CUI_POPOVER_POSITION_ANCHOR, .anchor = CUI_POPOVER_TOP_LEFT, .reference_rem = 16, .arrow = true, }; if (cui_popover_begin(ui, theme, state, cui_string("Details"), (cui_str){0}, options, position)) { cui_text(ui, cui_string("Popover content"), theme->font_size, theme->text); cui_surface_end(ui); } ``` Read `include/cui/cui_surface.h` for the complete contract. Initialize state with `CUI_SURFACE_POPOVER` and open it with `cui_surface_open` as for existing surfaces. Always balance a successful begin with `cui_surface_end`; a false begin has no caller-owned boxes to close. Supply updated trigger bounds each submitted frame. Anchor names identify the popup's own anchor: TopLeft/Center/Right open below the trigger, BottomLeft/Center/Right open above it. LeftCenter opens to its right; RightCenter opens to its left. Alignment follows the named trigger edge/corner. Anchor mode clamps without flipping or shrinking the chosen dimensions. Width/ height <=0 select 420/260; invalid active geometry is rejected before overlay state updates. `cui_popover_surface_geometry` exposes these defaults and placement as a pure helper with unchanged output on failure. `reference_rem` is a logical size from app/host root sizing configuration. Zero selects 16. Never infer it from a theme font. Default offset is reference_rem/4; arrow depth is reference_rem*3/8 and is added to surface distance. With `custom_offset=true`, signed offset including 0 replaces the default gap. Finite negative gaps may overlap the trigger. Clamping may alter the apparent gap. Source logical placement retains fractional coordinates; host pixel snapping is separate. Arrow base inset uses the theme radius, even if the surface radius is refined. Fill follows the effective refined background. Appearance NONE without explicit background refinement uses theme popover for the arrow. The 1px outline uses theme text at alpha 26/255 and is absent for NONE. Arrow triangle and ring seam patch paint after panel contents at its layer, inherit panel opacity and clip to both the supplied viewport and host viewport. Decoration does not enlarge the panel hit/dismiss bounds, create semantics or receive focus. It remains visible with an inert ancestor and while another modal owns input. A separate inert paint portal uses local prepaint so visual painting does not require input eligibility. Geometry and vertices are copied into context-owned frame storage; do not retain draw-list pointers across the next begin-frame. Arrow payload/paint-command capacity failure balances internal boxes and suppresses the final draw list. Ordinary layout-node capacity follows Core semantics: failure remains balanced but ordinary paint may be partial. Retry on a later adequately sized frame. The portable outline uses a bounded 2px miter and triangle meshes. upstream's external PathBuilder tessellation/raster AA is not reproduced exactly. Source fill, anchor, tip and seam equations do not establish exact pixel parity. Software, SDL_GPU and Sokol support Core mesh commands. SDL3 now supports bounded analytic meshes through prepared CPU coverage textures; see `design/SDL3_MESH.md` for its limits. The browser Canvas adapter has exact headless mesh-mask and opacity evidence at DPR 1 and 2. The gallery additionally tests all eight anchors, signed offsets, clamping, opacity, inert paint and modal ordering with desktop and touch input. Physical GPU hardware checks remain separate from Xvfb/software validation. This slice does not cover Popover transition, right-click trigger or focus/control parity. ## Browser gallery The Popover story starts with its existing legacy account card. Select **Source anchors (opt in)** to use `cui_popover_begin` and a real centered CUI trigger. All eight names identify the popup's own anchor. Controls map directly to `mode`, `anchor`, `custom_offset`, signed scalar `offset`, `arrow` and `reference_rem`. The latter is explicit application/host root sizing: zero means 16 logical pixels; the sample also offers 16, 24 and 32. It is never inferred from the theme font. Inactive controls are disabled in legacy mode. Edge clamp moves the actual trigger to the lower corner. The gallery schedules one settling frame when the newly laid-out trigger differs from the bounds used for composition, then returns to idle. It retains popup size and anchor direction. Opacity and inert controls wrap the real stage. Open the card first to observe paint persisting under an inert ancestor while child semantics/input disappear. The modal demonstration uses a separate ordinary dialog at explicit layer 200, above the card's default layer; it does not implement automatic overlay ordering. Closing that dialog updates its control. Route changes close both surfaces and reset the demonstration controls. The complete C11 snippet reflects the current positioning and stage settings. `tests/web/test_popover_anchor_gallery.py` drives actual mouse/CDP touch input, checks all eight source equations against real CUI bounds and mesh vertices, compiles the displayed snippets with strict C11 warnings, and reads actual Canvas pixels for centered arrow joins, opacity, inert persistence and modal backdrop ordering. Fractional clamped Canvas rectangle edges can still antialias the join differently from mesh pixel-center coverage: a dark fill value 10 can read 9 at an adjacent join pixel. Clamped geometry is checked separately; exact centered join assertions retain exact values. This known raster difference is not claimed as upstream pixel parity. Browser font, accessibility and focus limitations remain. --- ## Opt-in Popover source appearance Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/POP_OVER_APPEARANCE.md # Opt-in Popover source appearance This slice implements consumed surface appearance against upstream-component 0.7.1 commit `87d10ae5e1299d1be18670a37570c5402f952e34`, `crates/component/src/styled.rs:16–125,186–194` and `crates/component/src/popover.rs:355–361`. It does not complete the Popover family. Append `popover_appearance = CUI_POPOVER_APPEARANCE_SOURCE` to `cui_surface_options` for a POPOVER. Zero/LEGACY preserves the existing surface background, text, padding and 1px border with no shadows. SOURCE uses theme popover/popover_foreground, theme radius, 12 logical pixels padding (p_3 at the pinned 16px rem baseline), no ordinary border and these ordered DROP layers: | x | y | sigma | spread | ink | | --- | --- | --- | --- | --- | | 0 | 0 | 0 | 1 | theme text RGB, alpha26 | | 0 | 4 | 3 | -1 | black alpha26 | | 0 | 2 | 2 | -2 | black alpha26 | The first layer is an expanded filled rounded caster, not an outline. Original caster radii are retained before spread. Core copies the three layers onto the actual portal node; ancestor opacity is applied by Core once. Layer alpha is the nearest byte to 0.1. This is numerical CUI raster parity, not certification of upstream's GPU kernel/AA/color identity. NONE skips background, padding, radius, border and shadow defaults. Explicit refinement flags apply afterward in every policy, including NONE: background/foreground/radius/padding/border and a replacement ordered list of up to eight mixed DROP/INSET layers. A zero-count SHADOWS refinement explicitly removes default shadows. Values are owned copies; no layer pointers remain borrowed. Unflagged properties do not override defaults. Unknown flags/policy, count overflow, invalid finite geometry or invalid layer kind/geometry reject before Base input reduction or decision callbacks. The pure `cui_popover_style_resolve` leaves output untouched on failure. Styled and Base begin return false for invalid Popover configuration. Other surface kinds ignore these Popover-only options. Host rem changes require an explicit padding refinement; theme font size is not a rem proxy. CUI retains its automatic title/Close/body composition, whereas source Popover content is arbitrary caller content. NONE uses theme text as the fallback for that explicit title; source would inherit the enclosing element's foreground. An explicit foreground refinement overrides this fallback. Body children keep their caller-specified colors. General inherited text styling, arbitrary source StyleRefinement, arrows/anchor policy and appearance-off parent-color identity are not completed here. Appearance does not alter outside-dismiss policy. Public Popover does not receive an invented 150ms animation: the source's private dropdown helper is a separate consumer. ## Tests and registration Root registers these new files; this worker does not edit global build or distribution files: * `tests/unit/test_popover_appearance.c`: strict composed Core/Popover commands, light/dark distinct semantic colors, exact caster/order/radii, legacy and NONE custom shadows, resolver invalid geometry/count/kind, pending-dismiss callback/state atomicity. * `tests/integration/test_popover_appearance_native.c` with `popover_appearance_fixture.h`: value-copy actual styled commands before destroying their Core context; identical TEXT omission for geometry/alpha proof; Software/SDL Renderer/SDL GPU/Sokol readback at DPR1/2, light/dark opaque/translucent surfaces. Does not claim font pixels. Link cui_software, cui_sdl3, cui_sdl_gpu, cui_sokol and their native dependencies; define GL_GLEXT_PROTOTYPES. Needs a real Vulkan/GL display. Utility GPU window is constrained square because tiling WM resizing would otherwise introduce intentionally unsupported anisotropic scale. * `uv run tests/web/test_popover_appearance.py --output OUTPUT --chromium PATH`: pinned Playwright1.58, Zig0.16 reactor, actual composed command exports, Canvas/WASM shadow values/pixels and legacy/NONE absence at DPR1/2. This is a standalone fixture, not gallery wiring. Strict native build passes. Full baseline CTest162/163 has only expected stale generated `distribution` failure; Root regenerates after integration. Actual native and Chromium1208 fixtures each pass8 source frames. Native readback compares straight interior/outside points within three byte levels to the independently scaled Software reference; corner AA identity is not promised. First plain-Xvfb Vulkan failure and real-display anisotropic fixture failure were retained at `/tmp/cui-popover-native.log` and `/tmp/cui-popover-gpu-debug.log`; fixed real-display proof is `/tmp/cui-popover-native-display.log`. Browser log `/tmp/cui-popover-browser.log`. Scoped ASan/UBSan with leak detection passes (`/tmp/cui-popover-asan-final.log`); actual Wasmtime49 WASI headless assertions pass (`/tmp/cui-popover-wasi-final.log`). Rust is not used by this slice. The opacity test confirms half-opacity ink13 across all three layers. --- ## Progress Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PROGRESS.md # Progress Progress uses a controlled normalized fraction (`0..1`). Submit it each frame; its numeric semantic value is the target fraction even while the visible bar animates. Indeterminate progress is busy and has no numeric value in the browser accessibility bridge. It never adds a Tab stop. ```c #include void draw_download(cui_context *ui, const cui_theme *theme, cui_progress_motion *motion, float fraction, double now) { cui_progress_options options = cui_progress_defaults(); options.name = cui_string("Downloading assets"); options.size = CUI_CONTROL_SMALL; options.motion = motion; options.now_seconds = now; cui_progress_ex(ui, cui_id_from(ui, "download"), theme, fraction, 240, options); } ``` Keep a zero-initialized `cui_progress_motion` in application state and supply a monotonic host clock in seconds. The first submission displays the value immediately. Later changes animate over 180ms by default, and reversing a target continues from the currently displayed value. Set `duration` to customize it; zero selects the default. `reduced_motion`, or context reduced motion, snaps to the target. The return value reports whether another animation frame is needed; CUI also invalidates the context while moving. For a loading bar, set `indeterminate = true`. The defaults use the frozen one-second cycle: the segment grows from the left, then contracts toward the right using quadratic ease-in-out. Reduced motion produces a static centered 35% segment. Invalid or negative clock values also select that static segment. A zero-initialized options struct preserves the earlier CUI 1.6-second, fixed-width 30% loading cycle; explicitly set `source_motion = true` or use the constructor to select the source-style cycle. Extra-small/small/medium/large heights are 4/6/8/10px; positive `height` overrides them. The bar radius is half its height, except that a square theme remains square. `custom_corners` and `corners` refine each corner on both track and fill. `custom_color` and `color` override the solid fill, including transparent color; the track uses 20% of its alpha. Zero/negative/nonfinite width selects 160px. Nonfinite fractions become zero; finite fractions clamp to `0..1`. CUI uses fractions rather than the reference's `0..100` percentage API. ## Base composition `cui_progress_measure` is allocation-free, independent geometry in normalized track units. It returns the clamped fraction, segment start/length and whether loading needs another frame. An application can scale the geometry to pixels and paint its own track, indicator or arbitrary child content with Core boxes. Inside the root box, call `cui_base_progress` with the same ID to register progress semantics without painting. The styled adapter uses this same base behavior. There is no independent interaction reducer in the styling layer. `cui_progress_animate` is a caller-owned deterministic value transition, also usable by custom styling. Its duration is explicit, with zero meaning instant; invalid arguments preserve the state and output. A regressing clock is held at the last observed time. The move easing is cubic-bezier `(0.2,0,0,1)`; arbitrary easing/theme-motion-token overrides remain a separate API gap. The loading formula and sizes follow the [frozen Progress source](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/crates/component/src/progress/progress.rs). The quadratic easing was checked against its pinned `upstream-pre 0.3.8` dependency (crate SHA-256 `d7f0bc3ebba070f8981b3f8e905a12f47d27794a30d029e59cdb9edf7a4b3360`). No engine or runtime dependency is added. Base and styled tests cover geometry, cycle boundaries, reduced motion, colors/sizes, reversal continuity, clock regression, invalid-state transactionality and controlled semantics. ## ProgressCircle `cui_progress_circle` uses the same controlled fraction, semantic behavior, caller-owned value motion and source loading cycle. Start from `cui_progress_circle_defaults`. Its nested `progress` options supply size, name, clock, loading/reduced-motion flags and color; bar height/corner/style fields do not affect the ring. Extra-small/small/medium/large diameters are 8/12/16/20px. A positive `diameter` overrides them up to256px. Keep a `cui_progress_circle_state` with writable RGBA storage, capacity and a zero initial revision. Defaults rasterize at twice logical size; required storage is `ceil(diameter*raster_scale)^2*4` bytes. Scale must be greater than zero and at most4; output is bounded to512px per side. Pixels are borrowed by the draw list: retain them unchanged until rendering completes. Use distinct state/storage for simultaneously displayed circles. Insufficient capacity submits no UI, invokes no child callback and preserves motion, pixels and revision. The optional content callback composes children at the ring's center. Use a larger custom diameter for a text label. It runs synchronously; its user data and borrowed strings follow normal Core frame/render lifetimes. The circle is a progress indicator, with no automatic interaction or Tab stop. `cui_progress_circle_measure` exposes pure annulus/start/end geometry; `cui_progress_circle_raster` produces a portable4x4 antialiased RGBA bitmap without allocating. Stroke width is `min(diameter*0.15,5)`, with clockwise arcs starting at12 o'clock and a20%-alpha track. Transparent/custom colors remain explicit. CUI uses its raster sampling rather than upstream vector paths; the reference's0.0001-radian path-closing seam for spans at least half a turn is not reproduced. Arbitrary vector/style refinement and child clipping are application composition, not automatic source tree reproduction. --- ## Python controlled Single/Range Slider Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PYTHON_SLIDER_MODEL.md # Python controlled Single/Range Slider Unreleased Python subset over the matching [C bridge V1](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_SLIDER_MODEL.md). Legacy `slider()` remains scalar/float/autocommit with its original CHANGE timing. The separate [Node/TypeScript subset](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NODE_SLIDER_MODEL.md) uses the same bridge. The [Rust subset](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/RUST_SLIDER_MODEL.md) adds a restricted callback context; MSRV1.85.1 checks remain pending, alongside native numeric accessibility delivery, typed touch/SET injection and V2 gradient adapters. This does not complete the Slider family or all language bindings. ## Complete authored UI [Copy the complete Python program](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/bridge/examples/slider_model.py). It authors a label, nested Row/Column Slider, accept/reject button and owner/status label. The handler prints actual phase/current/requested pairs and explicitly accepts UPDATE using a receipt, or rejects by leaving the owner unchanged. It contains all initialization, callbacks, composition and deterministic input. With the [CMake/Ninja/C11 prerequisites](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DEPENDENCIES.md), Python3.10+ and no pip dependencies, from the checkout on Linux: ```sh cmake -S . -B build -G Ninja -DCUI_BUILD_NATIVE=OFF -DCUI_BUILD_BRIDGE=ON cmake --build build --target cui_bridge export PYTHONPATH="$PWD/bindings/python" export CUI_BRIDGE_LIBRARY="$PWD/build/libcui_bridge.so" python bindings/bridge/examples/slider_model.py python bindings/bridge/examples/slider_model.py --reject --vertical python bindings/bridge/examples/slider_model.py --single ``` These commands produce real windowless Core UIs, pointer focus and keyboard proposals. For an interactive native window, build the SDL/text adapters and pass `--font /absolute/path/font.ttf`; the same authored UI uses `App.run()`. Automated native checks always use private Xvfb through `scripts/test_local.py`. Replace the explicit shared-library path for the platform; local runtime evidence for this slice is Linux, not a claim of tested platform packages or registry release. ## Author and configure Import from `cui_bridge`: `slider_model`, `SliderSingle`, `SliderRange`, `SliderDomain`, `SliderConfig`, `SliderScale`, `SliderOrientation`, `SliderLayout`, `SliderPhase`, `SliderReason` and `SliderPart`. Exact definitions are in [`slider_model.py`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/python/cui_bridge/slider_model.py). `slider_model(key, config, confirmed, text="Selection")` is a distinct builder. Confirmed is `SliderSingle(end)` or `SliderRange(start,end)`, never a scalarized range. Domain and values retain Python float/C double precision. Config owns domain, horizontal/vertical orientation, fixed/parent layout, length/rem, uint64 source generation, request emission, readonly, reverse fill, reduced motion and focus-ring visibility. IDs/epochs/sequences/targets remain bounded Python ints; no float conversion. Geometry is float32, exactly as the C contract specifies. Records are frozen dataclasses. Numeric inputs reject bool/nonfinite values, invalid ordering/domains and out-of-range integers before wire conversion. Parent layout ignores/canonicalizes length to0. Configuration/owner validation is authoritative again in C. `.configure(config, confirmed)` replaces the complete pair/config atomically, preserving the C reducer for captured CANCEL; `.set_value` replaces only the same Single/Range kind. `.get_config()` and `.get_value()` copy actual C values once mounted. Use the existing `.disabled()` and `.label()` for node policy/name. Call `.on_request(callback)` or `.on_request(None)` to register or release the Python handler. Handler absence does not change explicit config readonly/request flags; manual polling remains available. Mount requires only Row/Column ancestors. Unsupported ancestry and missing API are detected before any C node is created. Mount lazily enables the independent FIFO at4096 records; call `app.enable_slider_requests(capacity)` first to select another bounded capacity. Reenable with a different capacity rejects, without resizing or discarding backlog. Normal old-only trees do not enable the feature. Parent-fill follows actual host constraints; vertical registered-scroll admission and all optional source presentation features are not established by this wrapper. ## Poll, dispatch and decide `app.step()` only steps, exactly as before. `app.poll_slider_requests()` yields owned `SliderRequest` copies without callbacks. Each copy includes frozen receipt, Single/Range current/requested, current/gesture domains and original input/event metadata. Input/event tags and flags retain the documented C vocabulary; absent evidence remains absent, rather than guessing a key/pointer source. Copied wire records reject malformed or noncanonical evidence before exposing a request: absent input has all-zero fields, repeat is 0/1, coordinates and numeric evidence are finite, inactive numeric evidence is zero, and an absent source flag requires UNKNOWN. A queue namespace must exist before a receipt is published. Invalid records raise `BridgeError`; already copied requests remain unchanged. This validates provider records and does not invent unavailable host metadata. `app.dispatch_slider_requests()` invokes typed handlers after C has returned. `app.dispatch()` first runs the preexisting legacy event dispatch, then the typed FIFO. There is no global ordering between queues. A legacy callback that advances the frame can expire pending typed receipts; it is not replayed or retimed. Native `run()` uses that same after-frame order and existing exception trampoline. The handler may mutate external owner/userdata, enqueue later input/work, change configuration, explicitly accept, remove the Slider or close the App. During a typed callback, nested step/run/dispatch/typed-dispatch reject. No ctypes view, mutable native borrow or live C call spans user code. Each entry is popped once before its callback; an exception propagates outside C, resets the dispatch guard, does not autoaccept/retry that entry, and leaves subsequent entries queued. Call `app.accept_slider_request(request.receipt, whole_pair)` explicitly. It may accept another valid full pair, not only `requested`. C validates actual issued sequence, latest admitted painted frame, source/config revision and current policy. Polling/rejection does not accept. Current stays the immutable submission-entry snapshot; repeated original-order keys evolve requested intent even when earlier proposals were rejected. Acceptance schedules later paint and never emits legacy CHANGE. Already accepted work/user effects are not rolled back. Receipts carry an opaque Python namespace marker with no App or C pointer. Keep them within their matching app/library instance; serializing numeric fields does not recreate acceptance authority. The copied data remains readable after future frames, removal or close, while acceptance can expire. `.remove()` removes this leaf, prunes later native queue entries and releases its handler. Closing releases typed handlers; dispatch stops without another C call after close. The owner OS thread must stay alive through destroy; typed-enabled close enforces that thread. This retained builder has no temporary hide/reconcile API. Conditional omission before mounting authors no node; dynamic removal is the supported omission route. It does not claim retained hidden-node/reinsert semantics from C-only frame tests. `.part_bounds(SliderPart...)` returns actual completed geometry or `None` for absence; thumb boxes are outer rem-sized geometry, not inner surfaces/rings. Disabled track/fill remain present, while thumb paint is omitted. `.presentation()` returns a frozen render-status/Core-time/passive-wake copy or `None` before observation. Failed completed frames raise without manufacturing geometry. Neither getter certifies renderer/native AT success or enables V2. ## Compatibility and proof limits `app.supports_slider_model()` requires the complete optional symbol group, V1 support bit and all exact native record sizes. Missing/partial/unsupported groups leave old loads and old-only mount/dispatch unchanged; typed use fails explicitly. No emulation using old scalar sliders or reduced precision is attempted. Local checks use the real current bridge for authored UIs and a distinct process loading the preserved actual pre-typed bridge for fallback. The old binary's source revision is unknown. CI's actual-old-library case skips unless `CUI_BRIDGE_OLD_LIBRARY` supplies such a fixture; offline partial-group rejection still checks every missing symbol. Complete example modes and current-library ordering/acceptance/errors/lifetime tests do not need that historical artifact. --- ## Unreleased Python localized TimeField Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PYTHON_TIME_FIELD_LOCALIZED.md # Unreleased Python localized TimeField Focused worker validation and sixteen configured root CTest entries pass, including fifteen localized methods against actual current, old and partial providers, the headless authored example and existing Python regressions. Canonical resource, usage and installed-skill gates remain pending; no package or native-interactive validation is claimed. The C bridge has separate focused proof; see [bridge contract and limits](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_TIME_FIELD_LOCALIZED.md). Existing scalar `time_field(...).time_value(...).on_change(...)` remains unchanged and usable with older libraries. JS/TS, Go and Rust localized authoring remain unimplemented; direct foreign C state/style and pure parser/formatter records are not exposed by this Python subset. The [complete authored example](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/bridge/examples/time_field_localized.py) creates independent English/H23 and Arabic/H12 fields, current-value summary, read-only, disabled, inclusive-bounds and clear-validation controls. Default mode composes and edits the actual UI headlessly. `--font` shares that same tree and handlers with the existing native SDL runner, without scripted input. Neither mode has runtime proof for the Python layer yet. Intended commands, using a matching existing built bridge (no installation): ```sh PYTHONPATH=bindings/python CUI_BRIDGE_LIBRARY=/absolute/path/libcui_bridge.so python bindings/bridge/examples/time_field_localized.py PYTHONPATH=bindings/python CUI_BRIDGE_LIBRARY=/absolute/path/libcui_bridge.so python bindings/bridge/examples/time_field_localized.py --font /absolute/path/font.ttf ``` The second is an intentional interactive launch, not an automated desktop test. No native launch has been executed here. Automated checks must run through `python scripts/test_local.py --build-dir build` in a private display, with the integrator registering `bindings/python/test_time_field.py` and the windowless example. Existing Python3 and ctypes suffice; no new dependency is introduced. ## Owned configuration and actual C editing `localized_time_field(key, config=TimeFieldConfig(), value=TimeValue(0,0), text='')` returns `LocalizedTimeField`, a kind55 widget opt-in; it does not replace the legacy factory. The App owns native time/editor state. Python owns immutable copies, never a native state view. All locale grammar, editing, validation and focus routing runs through the landed C widget, not a Python reducer. `TimeValue(hour,minute,second=0)` uses integer24/60/60 ranges (bool rejected). `TimeCycle.H23/H12`, `TimePrecision.MINUTE/SECOND` and `TimeTextStatus` mirror the published numeric vocabulary explicitly. `TimeLocale` contains ten digit tokens, separator, period separator, AM and PM; tokens are exact, pairwise prefix-free, nonempty UTF-8 of at most16 bytes without NUL. No locale registry, normalization, case folding or Python date parser is consulted. `TimeFieldConfig` adds optional `minimum/maximum` TimeValues, nonzero uint64 `edit_generation`, four segment names (at most64 UTF-8 bytes, empty selects C default) and strict bool `disabled/readonly/owner_invalid`. Bounds are same-day/inclusive, not overnight; minute precision requires zero active-bound seconds. Temporary config/locale construction is safe: native configure copies the entire 616-byte owned wire value before return. Both mounted and unmounted configure validate the same bounded record constraints. A native failure leaves the Python stored config unchanged. Change `edit_generation` for locale/name/domain resets; keep it stable for identical owner echoes. Cycle/precision and owner-time changes follow the actual C synchronization rules on the next ordinary writable frame. Do not manually clear/reset the native state every step. Methods: - `configure(config)` and `get_config()` update/copy owned config. - `time_value(h,m,s=0)` and `current_time()` retain the old setter/tuple semantics; `get_value()` returns a `TimeValue`. Domain-outside owner time is not clamped and owner replacement does not manufacture an edit observation. Minute hidden nonzero seconds remain invalid under the C widget rather than silently dropped. - `get_result()` returns immutable `TimeFieldResult`, or propagates the actual C unavailable/failed-frame status; it never substitutes a stale result. - `clear_validation()` changes transient edit validation only, not time, draft, owner-invalid or bounds. - `on_time_change(callback_or_None)` registers the typed applied-change observer. Localized `.on_change` rejects rather than silently promise a generic ASCII event; legacy `time_field` retains its original `.on_change` behavior. - `remove()` removes the native node, clears its handler and disposes this widget. ## Dispatch, failure and lifetime `App.supports_time_field()` checks the **complete ten-symbol optional group**, versions bit0 and exact616/80/64 native layouts. Missing/partial/unsupported groups leave scalar authoring available; localized mount fails before creating the tree. `enable_time_changes(capacity=4096)` can explicitly choose0–4096 (0 means4096); otherwise localized mount enables the default queue. Capacity is immutable after enable; same-size reenable is idempotent. Each configured live node reserves one possible observation before step mutates time/native input/Core state. Queue-full preflight leaves queued input and values/drafts intact; drain and retry. Python `step()` applies native edits without running callbacks. `poll_time_changes()` yields immutable `TimeFieldChange` copies; `dispatch_time_changes()` invokes typed handlers. General `dispatch()` retains existing legacy callbacks first, controlled Slider dispatch next, and localized TimeField callbacks last, each in its own FIFO. No new global cross-queue ordering is implied. Manual polling consumes the same records as dispatch; reading `get_result()` does not consume or replay them. Records retain full integer `frame_sequence` and `(slot,generation)` without float conversion. They retain no App/Widget/C pointer and confer no receipt authority. A change is one **already applied net aggregate** previous/final pair. Do not reapply it via `time_value` or invent an acceptance API. Net-zero editing emits no change. Result `changed` is net difference; `queued_change_count` is0/1 native queue production, not Python callback count; `rejected_count` counts original rejected events, not digits. Operation `status`, edit `validation` and final bridge `frame_status` are separate. Malformed output sizes/enums/reserved/UTF-8/identity or canonical inactive fields are rejected before any callback sees a record. A later failed frame retains applied changes with non-OK `frame_status`; explicitly call dispatch/poll after catching step error to observe them. This proves model mutation, not painting/native accessibility success. Latest-result getter stays unavailable after failed/omitted/unready submission until ordinary healthy recovery; diagnostic clearing alone is insufficient. Callbacks run only after C returns and may update external owner state, sibling text/config or handlers, remove a widget or close the App. Nested step/run/typed dispatch/poll is rejected. The current record is consumed before calling Python; on exception it remains a durable Python value, later C records remain queued unless teardown discards them, and the dispatch guard resets in `finally`. Close stops polling before another C call/callback and releases typed handler references. Retained records survive teardown; stale or removed handles never redirect to another widget. Do not mix live handles/apps/libraries; record copies are readonly observations, not cross-image authorization. Successful native enable uses the existing C owner-thread policy; Python records the enabling thread for safe close because C destroy is unchecked. Owner thread must stay alive through destroy; serialize calls, never race destruction. No new thread migration/locking architecture is provided. Default/shared WASM remain unsupported; this subset claims no IME/clipboard, one-root Tab parity or physical AT/native interactive proof. Prepared validation: real nested UI/paste/locale/bounds and aggregate copying, preflight retry, readonly/disabled, callback exception/close/removal, owner and app-local queue, failed-frame delivery through an actual later Slider capacity failure, malformed copied records and each missing optional symbol. Actual old module proof uses optional `CUI_TIME_FIELD_OLD_LIBRARY` in a separate process; without that path it skips honestly. The local run supplied the preserved old module and passed all 14 localized checks without skips; existing regression modules retained two unrelated optional skips. For optional real partial-group coverage, compile only the bridge translation unit against a matching already validated engine archive (no engine rebuild): ```sh python bindings/python/build_time_field_partial_provider.py \ --engine-archive /absolute/immutable/libcui.a --output /absolute/libpartial.so ``` Set `CUI_TIME_FIELD_PARTIAL_LIBRARY=/absolute/libpartial.so` when running the Python test, or configure `CUI_PYTHON_TIME_FIELD_PARTIAL_LIBRARY` for its registered CTest. The provider renames just the change-size export; remaining exports are real. Without this optional artifact the separate-process test skips. Keep it separate from the real older-library proof (`CUI_PYTHON_TIME_FIELD_OLD_LIBRARY`). The new, unreleased typed `TimeFieldConfig()` defaults to H23, minute precision and edit generation 1, matching the C initializer and the other typed bindings. Request `precision=TimePrecision.SECOND` explicitly for `HH:MM:SS` input (as the complete example does). This alignment does not change the legacy scalar `time_field()` factory or its seconds values. The focused default-wire and legacy factory regression added for this change awaits the next serial validation batch. --- ## Questionnaire source audit Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/QUESTIONNAIRE.md # Questionnaire source audit Questionnaire is registered in the main library and distribution. Its interactive gallery story is implemented; full source parity remains unfinished. The retained model and initial composable styled parts are implemented; this is not full parity. Reference commit: `87d10ae5e1299d1be18670a37570c5402f952e34`, `crates/base/src/questionnaire/{types,state,keyboard,control}.rs` and `crates/component/src/questionnaire/components.rs`. ## State and answers Ordered item definitions have a unique name, accessible label, optional description, required/multiple/disabled flags, choices, an optional retained Input editor and a validator. Choice values are unique within an item. Single-answer definitions reject multiple defaults even if one default is disabled. Disabled default choices do not enter the initial answer. A nonblank enabled initial input replaces defaults for single-answer items. Preserve the original input draft separately from the effective answer, including when a choice supersedes the freeform answer. Effective answers always use schema choice order. Disabling a choice hides it from the effective answer without deleting the retained selection; enabling restores it. Disabled items have empty effective answers and are excluded from totals and submission. Multiple-answer items may include both choices and freeform; single-answer items may include only one source. Whitespace-only freeform is absent. Setters validate names, choices and capacities atomically before changing model/editor/history. Programmatic setters are silent; user changes emit AnswerChanged. Reset restores initial answers and original input drafts while retaining current disabled flags and external errors. ## Validation and navigation Unanswered, Answered and Skipped are distinct states. An empty optional item is invalid until explicitly skipped. Internal errors distinguish Required, Unanswered and validator text; external errors take precedence. Disabled and skipped items suppress errors. After the first validation attempt, answer edits revalidate immediately. Any answer change clears completion and cancels pending confirmation. Current position and total refer to enabled items. Disabling the current item chooses the next enabled item, then the previous one; enabling an item when none is current selects it. Previous navigation does not validate; Next validates the current item. Submit validates every enabled item and returns to the first invalid one. A valid submission emits Completed once per completed state, then Submit every time. Changes allow a later Completed again. CurrentItemChanged is emitted by user navigation but not silent setters. Submission and validation snapshots preserve schema order. ## Activation, focus and timing Single-choice user activation selects then confirms after 150 ms, letting the selection become visible. Reduced motion still defers confirmation until after AnswerChanged callbacks, with no time delay. Activating the already-selected answer confirms immediately. Multiple-choice activation only toggles. Radio arrow movement changes selection without confirming. Another answer/current-item change cancels the pending confirmation; event subscribers may enable follow-up items before it runs. Enabled choices receive A–Z or 1–9 shortcuts by enabled position, skipping disabled choices. Focus moves between choices and the optional Input with the source's radio-group behavior. A selected choice owns Enter confirmation; an unselected choice owns activation. A focused nonempty Input retains arrows and text, while empty Input Up/Down may leave it. Ctrl/Command+Enter confirms; unrelated modifiers, repeats, IME composition and preferred character input must not trigger shortcuts. Rendered controls must use real Checkbox/Radio/Input behavior and graphical marks, with accessible names, description, set position and focus ownership. ## Verification requirements Port source behavioral cases for schema rejection, silent setters, draft preservation, reset, disabled restoration, schema order, external errors, cross-item validation, first-invalid focus, completion ordering, shortcuts, disabled-current fallback, delayed choice confirmation and no confirmation from radio arrows/typing. Add transactional capacity/UTF-8 and standalone base-link checks. Styled composition needs its own source audit and actual pointer/keyboard, four-size, disabled/error and focus tests before being called implemented. Full parity is not established by a state reducer or a static wizard screenshot. ## Current implementation evidence The portable retained model tests cover schema errors, disabled answer restoration, effective-answer change detection, input drafts, capacity/UTF-8 atomicity, optional skip validation, delayed/reduced-motion confirmation, and completion-before-submit ordering. Styled tests exercise all four card sizes, pointer activation and updated checkbox semantics, minimum card height, error/action visibility, Skip completion, actual text editing into a freeform answer, and disabled input suppression. Standalone strict C11 and ASan/UBSan checks pass; the existing branch CTest suite passes73/73. Remaining work includes typography/general layout refinements, comprehensive keyboard/callback coverage and platform accessibility integration. Bounded box-slot refinements and action/error localization are implemented below; ordered text/key reduction is also documented below. Existing styled code is a development checkpoint, not evidence that these gaps are complete. Input Enter confirmation and radio Left/Right wrapping now have native and sanitizer tests, including disabled-choice skipping, repeat suppression, event consumption, and no delayed confirmation from arrow selection. The explicit radio key helper must be called before choice rendering; complete root keyboard/callback coverage remains unfinished. The root now owns a nonmodal focus scope. The explicit answer-key helper traverses enabled choices and an empty input with Up/Down, wraps in schema order, selects radios without confirming, and preserves cursor movement for nonempty drafts. Call it inside the root before answer parts. Native and sanitizer tests cover the choice/input boundary. Automatic root capture and initially focused-answer restoration remain unfinished. The explicit confirm-key helper supports Enter on a focused filled choice/input and a host-selected Ctrl/Meta+Enter modifier. Modified submission owns and cancels the core activation token even when validation fails, preventing accidental radio selection. The native regression verifies this fallback failure and successful confirmation; sanitizer and existing73CTest gates pass. The browser story now exercises required validation, delayed radio navigation, optional Skip, typed freeform submission, reset, disabled controls and all four sizes. The integrated library passes 77 native and 75 sanitizer suites. Gallery coverage does not establish complete keyboard, styling, accessibility or composition parity. `cui_questionnaire_shortcut_keys` routes bare A–Z or 1–9 key identities to enabled choices by their visible shortcut position, focuses the chosen card, and uses the same delayed/repeated-choice confirmation model as pointer activation. Invoke it inside the root before input and choice parts. It ignores consumed events, repeat, modifiers, focused text input, disabled root/item, IME composition and preferred character input. The other explicit key helpers also yield to the two host keyboard-context flags. SDL tracks composition start/end when forwarding keys, and core default Enter/Tab/Space behavior yields to those flags. This prevents shortcut/default activation during composition; complete IME preedit rendering and automatic root keyboard capture remain unfinished. Arrow entry from a non-answer control now restores the first (Down) or last (Up) filled answer in schema order before choosing an unfilled answer. Restoring focus leaves the answer unchanged and does not schedule confirmation. A failing-before/passing-after headless regression covers both directions from an action button. Choice-card paint now follows the pinned selected/hover/invalid/disabled colors, transparent light or 20%-input dark idle background, size-specific card/indicator/shortcut radii and shortcut font sizes. The shared theme exposes explicit palette mode and the muted background token, populated from all 38 pinned palettes. Headless draw assertions exercise four sizes and idle/selected/hover/disabled states across every palette. The later focus band and bounded slot refinements below extend this checkpoint; arbitrary instance style refinement remains unfinished. Choice options now accept `render_indicator`, `render_content`, and `render_shortcut` callbacks plus a shared `render_user`. Each receives a borrowed `cui_questionnaire_choice_view` snapshot (item/choice indices, size, selected/multiple/disabled/invalid/focused state and shortcut character) and a stable slot ID. Callbacks emit balanced CUI child elements. Content replaces the default label/description rendering while the card retains its definition's accessible name, role and behavior. Indicator and shortcut wrappers apply the pinned source's offset from the answer line using the default adornment size, including when custom artwork has a different intrinsic height. A custom shortcut renderer still runs when the default shortcut is unavailable. Disabled opacity is inherited across custom content. Headless composition tests cover both radio and checkbox cards at all four sizes, intrinsic-size alignment, replacement precedence, pointer selection/focus, retained semantics, disabled/invalid snapshots and opacity. Null callbacks retain the default graphical parts, already covered across all 38 palettes. Bounded box-slot refinement is implemented below; typography/general layout refinement, comprehensive root event coverage and full accessibility remain unfinished. Source contract: pinned `crates/component/src/questionnaire/components.rs` choice renderers and `center_on_answer_line`. `cui_questionnaire_item_begin`, `cui_questionnaire_choices_begin`, and `cui_questionnaire_actions_begin` provide source-aligned composition containers. Pair each successful begin with `cui_questionnaire_part_end`. Item and Choices omit unknown, inactive and disabled items without opening layout nodes. Item carries the definition's accessible label/description and accepts programmatic focus while staying outside Tab order. Choices uses a Group for multiple answers and the appended RadioGroup semantic role for single answers. Item gaps are XS/S/M/L 8/12/16/24; choice and action gaps are 4/6/8/10. Actions arrange children horizontally with centered cross-axis alignment and remain renderable without an active item. The core `cui_semantic_parent` query exposes the completed frame's nearest semantic layout ancestor, with explicit parent metadata taking precedence. Native tests cover transparent intermediate boxes, reparenting and unavailable-frame queries. Container tests verify all sizes, radio/checkbox group roles, nested parent relationships, item focus restoration and Tab exclusion, child spacing/action alignment, inactive/disabled visibility and empty-item action composition. Root capture and inherited part sizes provide automatic composition; standalone parts retain explicit helpers. Arbitrary style refinement remains unfinished. Default shortcut badges paint the theme background independently of selected/hovered card fills; disabled cards halve the entire badge opacity. Draw-list regressions cover all 38 preset palettes and all four sizes. `cui_questionnaire_choice_position` returns the one-based position and total among enabled choices without allocating. Disabled/unknown choices or invalid arguments leave both required outputs unchanged. Styled radio/checkbox answers publish this position together with their definition description; runtime disabled changes recompute the enabled set. This semantic coverage does not imply a verified native screen-reader bridge. Focused answer cards now tint their existing border with the focus token and paint the pinned source’s 3px, half-opacity outside band. The band preserves translucent card interiors and does not alter card or sibling layout. `theme.hide_focus_ring` suppresses the band while retaining the focused border. Headless draw tests cover all 38 palettes and all four sizes; this does not complete root keyboard routing or platform accessibility. Questionnaire parts now inherit the root size through a context-owned, bounded 128-entry state-address table. Non-medium part sizes remain explicit overrides; `custom_size` permits an explicit Medium override. Parts outside a registered root use Medium. Publishing a 129th distinct root clears the bounded table before recording the new root, matching the source cache policy. Separate contexts do not share sizes. Draw-list tests compare all parts across all four sizes and verify overrides, context isolation and cache eviction; the same tests fail against the previous implementation. Root capture and basic cross-item focus routing are implemented below; full event/callback coverage remains incomplete. The root now captures unconsumed keys before child reducers using the preceding frame’s submitted part bindings. It handles answer/radio arrows, item navigation, alphabetic/numeric shortcuts, filled-answer Enter and Ctrl/Meta+Enter, while respecting input focus, unrelated modifiers, repeats, IME and preferred character input. Parts publish bindings through bounded context resources; the current list replaces the previous list each frame so omitted controls are reclaimed safely. Root numeric mode supplies part shortcut labels. Navigation restores the new Item focus; failed confirmation prefers the invalid item’s filled input/selected choice, then the first enabled answer. Native tests cover automatic composition without helper calls, cross-item focus, event guards, input cursor ownership, disabled roots, invalid confirmation, omission/reintroduction and resource-capacity failure. The regression fails against the previous root. Nested roots and comprehensive callback choreography still need source-level verification. ## Ordered input batches Questionnaire input now reduces queued events in order. A `TEXT` or clipboard paste followed by Enter in one frame synchronizes the new answer before confirmation. Enter followed by text confirms the answer that existed at Enter; remaining events targeted at the old input do not edit either the old answer or the next item. Completing the last item likewise stops the old input batch. Selection replacement and multiple text events each emit their answer change before the current-item/completion event. An empty Enter does not retroactively confirm text arriving later in the queue. Automatic root capture defers focused-input keys to this ordered path. An explicit confirm helper used inside the root also leaves focused-input Enter to `cui_questionnaire_input_control`. Filled-input arrows remain editor-owned; empty-input navigation keeps the root behavior. IME composition, preferred character input and repeated Enter do not confirm; disabled roots/inputs do not edit or confirm. Reduced motion does not reorder input events. `cui_base_input_reduce_event` exposes the shared single-event reducer for other composite controls. Register the textbox with `cui_interact` first, call the reducer once per event in increasing queue order, aggregate errors, then publish final semantics and paint. It does not submit semantics or process other queue entries. Borrowed clipboard and hit-test geometry are used synchronously. Invalid indices/NULL arguments leave editor, drag state and events unchanged. The ordinary `cui_base_input_ex` uses the same reducer and retains readonly, pointer selection, clipboard, IME, repeat, and delegated navigation behavior. Headless regressions cover text/paste plus confirmation, confirmation plus later text, empty Enter plus text, select-all replacement plus multiple edits, callback ordering, final completion, old-item event isolation, disabled/reduced-motion behavior, and single-event invalid/delegated-key handling. The text-plus-Enter regression fails against the previous Questionnaire component implementation. This fixes batch ordering; it does not establish full Questionnaire parity. Bounded choice slot refinements and localized labels --------------------------------------------------- `cui_questionnaire_options` accepts optional `indicator_style`, `content_style` and `shortcut_style` pointers to `cui_questionnaire_slot_style`. These refine a bounded subset of the existing portable `cui_box`: dimensions, uniform padding, gap, radius, background, border color/width, physical alignment and opacity. `fields` selects independent overrides, including transparent colors, zero border or radius and zero opacity. Unmasked values are ignored. Width/height accept `-1` for grow, explicit fixed `0`, or positive logical pixels through4096. Other lengths accept0..4096, opacity0..1, and alignment START/CENTER/END. The content wrapper retains its default grow width unless WIDTH is selected. Refinement follows the frozen source's three distinct seams: indicator and shortcut styles affect only their default elements; a custom renderer replaces that default element and therefore its style. Content style affects the wrapper around either default text or custom content. The adornment's vertical offset continues to use the default size metrics, so changing its dimensions does not recenter it against a multiline description. Card input, role, accessible name, selected/invalid state and disabled ancestor opacity stay independent. Slot opacity multiplies inherited opacity. No text color/font/weight inheritance, percentage/flex policy, per-edge styling or general upstream `StyleRefinement` parity is claimed by this box-only descriptor. ```c cui_questionnaire_slot_style content = { .fields = CUI_QUESTIONNAIRE_SLOT_BACKGROUND | CUI_QUESTIONNAIRE_SLOT_PADDING, .box = {.background = {240, 245, 255, 255}, .padding = 4} }; cui_questionnaire_labels labels = { .fields = CUI_QUESTIONNAIRE_LABEL_SUBMIT | CUI_QUESTIONNAIRE_LABEL_REQUIRED, .submit = {"Absenden", 8}, .required = {"Bitte beantworten", 17} }; cui_questionnaire_options options = {.content_style = &content, .labels = &labels}; /* Pass options explicitly to the relevant parts; root options do not publish * styles or translations to child submissions. */ ``` `cui_questionnaire_labels` independently masks Previous, Skip, Next, Submit, Required and Unfilled labels. Missing fields keep existing English defaults; a masked empty UTF-8 string deliberately supplies an empty label. A nonempty explicit label passed to `cui_questionnaire_action_control` wins over localization. Custom validator/external MESSAGE text stays exact. The progress sentence, item/choice text, input labels and keyboard identities are not translated by this bundle; applications already own their definition strings. There is no ambient locale registry or retained translation callback. Every options-taking part copies all supplied descriptor values at entry and validates them before routing, tick, model interaction or custom renderers. Unknown mask bits, invalid active dimensions/alignment/opacity and invalid active UTF-8 strings (including NULL data with nonzero length) reject the entire submission. This applies even to descriptors unused by that part, or refinements replaced by custom renderers. Bool entry points return false, input returns `CUI_QUESTIONNAIRE_INVALID`, and void entry points emit nothing; invalid options consume no events or opening scopes. As with other borrowed C inputs, descriptor pointers must address readable storage while copied. String bytes remain borrowed through completed-frame draw consumption. Root size inheritance is unchanged; these styles and translations have no root-to-part inheritance. Appending these fields preserves source defaults for zero/designated-initialized options but changes `sizeof(cui_questionnaire_options)` and its by-value ABI. Rebuild C consumers and use matched SDK/distribution snapshots; this is not an old-binary ABI compatibility guarantee. The headless `test_questionnaire_styled.c` regressions cover all four sizes, independent slot geometry/paint, default-based offsets, custom replacement, content grow/zero dimensions, transparent/zero overrides, disabled opacity and semantics, descriptor copying before a renderer mutates the original, translated action/error paint and semantic names, explicit/default/custom-message precedence, and invalid-option rejection before automatic root routing and callbacks. These are portable headless contracts, not browser/native screen-reader acceptance or complete Questionnaire source parity. Nested roots, comprehensive callback choreography, broader part/style methods and platform integration remain open. Optional [progress presentation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/QUESTIONNAIRE_PROGRESS.md) now supports localized accessible/visible text, decorative children and explicit bounded progress text metrics via an independent C header. The legacy helper keeps its English sentence and previous paint. This does not change other-part typography or add a Form role. --- ## Questionnaire geometry and numeric metrics Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/QUESTIONNAIRE_GEOMETRY.md # Questionnaire geometry and numeric metrics Include `cui_questionnaire_geometry.h` with matching CUI sources/library. This additive API does not resize legacy options, choice views or state. NULL and all-zero geometry preserve the original layout tree, text paint and reduction. No layout/paint option changes model events or disabled eligibility. Pass an independent descriptor to each `_ex` part. Root publishes its existing size/density only: numeric metrics and refinements never implicitly inherit. Existing keyboard policies can be passed independently; NULL retains the existing route inheritance. Existing progress, named presentation and observers are unchanged. The complete checked resolver lets the owner reuse numeric values explicitly, including with custom children. ```c #include "cui/cui_questionnaire_geometry.h" void questionnaire_geometry_example(cui_context *ui, const cui_theme *theme, cui_questionnaire_state *state) { cui_questionnaire_options options = {.design_size = CUI_DESIGN_BASE}; cui_questionnaire_geometry_options geometry = { .metric_fields = CUI_QUESTIONNAIRE_METRIC_MINIMUM_HEIGHT, .metrics = {.minimum_height = 64}, .card = {.fields = CUI_QUESTIONNAIRE_BOX_PADDING, .padding = {.left = 12, .right = 16, .top = 8, .bottom = 8}}, .answer = {.fields = CUI_QUESTIONNAIRE_TEXT_SIZE | CUI_QUESTIONNAIRE_TEXT_LINE_HEIGHT, .font_size = 18, .line_height = 28}}; if (!cui_questionnaire_begin_ex(ui, 100, theme, state, options, NULL, &geometry)) return; size_t item = state->current; if (cui_questionnaire_item_begin_ex(ui, 101, state, item, options, &geometry)) { if (cui_questionnaire_choices_begin_ex(ui, 102, state, item, options, &geometry)) { for (size_t choice = 0; choice < state->items[item].choice_count; ++choice) (void)cui_questionnaire_choice_control_ex( ui, 200 + choice, theme, state, item, choice, options, NULL, &geometry); cui_questionnaire_part_end(ui); } cui_questionnaire_part_end(ui); } cui_questionnaire_end(ui); } ``` Use application-owned collision-free IDs and schema lifetime as in the original Questionnaire API. The example assumes a valid initialized model and submissions inside a frame. No event facade, binding wrapper or automatic arbitrary text cascade is supplied. ## Resolution and validation Resolve existing legacy size/shared XS–9XL and density first. With shared size INHERIT, nonzero `custom_scalar` supplies a complete source numeric profile; non-INHERIT shared size wins. Scalar is finite (0,256]. Individual masked metrics then override that profile, including zero gaps/padding/minimum. No additional four-size enum or numeric inheritance cache is introduced. Lengths must be finite [0,4096]; font sizes finite (0,512]. Width is grow(-1), FIT(0), positive fixed; `fixed_zero_width` makes a masked zero width fixed zero. Scalar is independently validated even when shared size wins. Unmasked values are ignored. | Numeric custom V | Formula | | --- | --- | | root/item/choices/answer/content gaps | V / V / .5V / .625V / .125V | | card horizontal/vertical padding; minimum height | .75V / .625V; 2.75V | | indicator / radio mark / checkbox check | V / .5V / .875V | | shortcut box / text | 1.25V / .625V | | answer text / line box | V / 1.5V | | secondary / title / progress text | .875V / 1.125V / .75V | | card / shortcut radius | theme large / theme regular | Custom secondary/title/progress line boxes are natural(0), reflecting source branches that set size without a guaranteed explicit line box. Existing named presentation/progress APIs remain independently configured; this helper does not silently restyle them. Legacy helper values extract existing CUI paint, including legacy heading line+4 and natural shortcut/progress lines. Shared scales retain existing CUI geometry; their higher steps are CUI extensions. Fractions undergo Core layout quantization, not arbitrary fractional-pixel parity. Answer/secondary/shortcut refinements use the existing text masks. Resolved text views include color/style. They affect the default paint branch of the existing choice reducer. Effective answer first-line height aligns indicators/shortcuts; natural0 uses the configured font metrics. Invalid/missing metrics reject before interaction when a natural active answer requires them. No text/style cascade into custom children or editors is implied. The five box patches apply after built-in geometry/state paint. Card gap patches only the actual answer row; outer gap remains0. Explicit disabled opacity paint can be overridden without reenabling interaction. Ancestor opacity multiplies. Existing indicator/shortcut styles still patch their default elements; content style patches its wrapper, including around custom content. New card patches do not leak into those children. Unknown masks, nonfinite active values, invalid text styles and conflicting fixed card height reject before bindings, input reduction, callbacks or model mutation. Fixed height must be at least the resolved minimum and vertical padding; no maximum-height field is offered. The checked resolver leaves output untouched on failure. Entry bool meanings remain legacy: choice returns changed, container returns accepted/opened, so false on choice is not an error report. ## Minimum bounds and callbacks Opt-in cards use physical padding around a gap0 row, with a zero-width minimum spacer and the real answer row. The same outer ID owns paint, pointer/key/AT, focus ring and semantics; minimum blank area is interactive. FIT cards grow with long content. Fixed heights may overflow; ancestor clipping clips paint and pointer hits while semantic layout bounds can extend beyond the visible region. Very narrow widths/adornments retain ordinary layout overflow. No silent resize. New indicator/content/shortcut renderers take an immutable extended snapshot: old choice view, fully resolved numeric metrics and three text views. New wins over the corresponding old renderer. Old receives its unchanged legacy view; custom numeric values are never misrepresented as a legacy size. All descriptors are copied before children run. Callbacks run once in existing order and derived namespaces; shortcut OFF suppresses both new and old shortcut children. Snapshot, function and userdata are borrowed for synchronous submission only. Children balance boxes, avoid model mutation/input dispatch, and do not retain views. Drawn strings survive completed-frame consumption. Caller avoids namespace collisions, as for existing composition. No retained attachment or dispatch layer. Frozen source reference: `87d10ae5`, `crates/component/src/questionnaire/components.rs:85-253,297-364,527-678,772-975`. This covers bounded container/card/numeric/default-choice text geometry. Input left-only padding, independent editor paint/shaping, Button/trailing actions, Form role, arbitrary Styled inheritance and binding facades remain separate required followups. All78 entries remain; this is not full Questionnaire parity. --- ## Questionnaire keyboard policies Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/QUESTIONNAIRE_KEYBOARD.md # Questionnaire keyboard policies Include `cui_questionnaire_keyboard.h` with a matching library revision. These additive entry points preserve the existing options/model layout. They provide keyboard policy, not a snapshot/event facade. Existing APIs remain available. Zero/NULL preserves the corresponding legacy entry point. The three enum fields normalize unknown values independently to legacy. A copied options record carries no callbacks, strings, allocation, platform types or retained caller pointers. Root policy is copied before capture and applies to ordered input routing, including confirmation routed through an editor. Existing choice parts inherit the matching active root's shortcut mode; explicit standalone overrides are documented in the header. The host must keep per-part and root activation policies consistent. Legacy matching-root inheritance predates this API: the active root's `numeric_shortcuts` supplies ordinary choice badges even when the choice's own boolean differs. A zero-valued extension root preserves that behavior in both directions. Standalone choices retain their own boolean; a non-NULL explicit choice keyboard record follows the override rules in the header. Frozen source `87d10ae5e1299d1be18670a37570c5402f952e34` defaults shortcuts to absent (`base/questionnaire/state.rs:121,343–348`). OFF must suppress both key activation and the default/custom shortcut adornment. It does not disable actual choice controls. Letters/numbers retain enabled-position ordering. Source adjacent-answer restoration applies only from item focus (`state.rs:894–975`). The opt-in item-focus policy preserves selected-answer restoration there, but enters the first/last enabled answer from action/root focus. Legacy action-focus restoration remains unchanged. The standalone helper takes an explicit item ID because the existing helper does not know that container's ID. Source keyboard submission uses the host platform secondary modifier. The new record explicitly chooses Control, Meta or unmodified-only; it never guesses the platform. Exact modifier matching preserves rejection of Shift/Alt combinations. Bare Enter still requires a filled focused answer. Automatic-root legacy accepts Control or Meta; standalone legacy preserves its existing explicit modifier input. Nested roots currently share a context route stack. Each begin captures before pushing itself; therefore an outer root may inspect events before a later inner begin. A stack is not evidence of nearest-root dispatch isolation. The characterization test with distinct states confirms that outer capture can consume the key before the inner root sees it. Existing consumption order remains. No nesting architecture change is part of this slice; source capture ordering must be measured before claiming parity. The focused fixture covers queued keys for OFF/letters/numbers, item versus action focus, host modifiers, independent enum fallback, IME/repeat/modifier guards, standalone helper policies, real badge pixels, semantic names, custom renderer calls, zero-policy pixel/semantics/callback equivalence, and pointer/accessibility activation with shortcuts OFF. Existing Styled regressions cover editor ownership, disabled transitions and delayed confirmation. Validation uses strict Release via the private headless wrapper, focused WASI, compiled C guide and C++ header, and actual pinned repository formatting after the final source edit. Canonical registration, generated distributions, metadata and skills remain integrator-owned. ## Consumer composition The host chooses its submit modifier explicitly. Submit the policy once on the root; ordinary choice parts inherit its shortcut mode. OFF suppresses shortcut adornments (including custom shortcut callbacks) and letter/number activation, while pointer, focused-control keys and accessibility activation remain enabled. A standalone choice override only changes that part's display; it does not change root-wide shortcut routing. Keep root and part policies consistent. ```c #include "cui/cui_questionnaire_keyboard.h" void questionnaire_page(cui_context *ui, const cui_theme *theme, cui_questionnaire_state *state) { const cui_questionnaire_keyboard_options keyboard = { .shortcuts = CUI_QUESTIONNAIRE_SHORTCUT_OFF, .answer_entry = CUI_QUESTIONNAIRE_ENTRY_ITEM_FOCUS_ONLY, .submit = CUI_QUESTIONNAIRE_SUBMIT_CONTROL }; const cui_questionnaire_options options = {.width = 300}; if (!cui_questionnaire_begin_with_keyboard(ui, 100, theme, state, options, &keyboard)) return; size_t item = state->current; if (cui_questionnaire_item_begin(ui, 101, state, item, options)) { cui_questionnaire_heading(ui, 102, theme, state, item, options); for (size_t choice = 0; choice < state->items[item].choice_count; ++choice) (void)cui_questionnaire_choice_control(ui, 1000 + choice, theme, state, item, choice, options); cui_questionnaire_part_end(ui); } cui_questionnaire_end(ui); } ``` Definitions and caller workspace still outlive the retained state. The record is copied synchronously and may be stack allocated. IDs must remain stable and unique in the host tree; the example uses a single active item. Root capture uses previous frame bindings, so draw an initial frame before sending keyboard input. Standalone helpers do not inherit root options; pass their record explicitly. Their LEGACY shortcut mode preserves both `numbers=false` (letters) and `numbers=true`. The worker fixture registers the focused test and compiles this example without changing canonical build files. The private WASI driver extends the existing suite list in memory; canonical registration is an integrator follow-up. This slice does not complete the family's payload, compound presentation, localization, Form semantic or general styling gaps. The interactive gallery exposes an Enable choice shortcuts control alongside the existing numeric-hints switch. Its actual C composition uses `cui_questionnaire_begin_with_keyboard` and the matching standalone shortcut helper, so OFF applies to both rendering and activation. The copyable usage example shows explicit OFF. Headless `tests/web/test_questionnaire_shortcuts_gallery.py` checks actual Tab focus, ignored shortcut keys, default/custom hint suppression, letter/number selection and genuine touch selection while shortcuts are off. It does not establish the remaining snapshot, localization, style or binding surfaces. --- ## Questionnaire typed observation Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/QUESTIONNAIRE_OBSERVER.md # Questionnaire typed observation Include `cui_questionnaire_observer.h`. Rebuild every consumer/binding with matching headers and library: `cui_questionnaire_state` gained one observer pointer. Legacy initialization clears it; reset retains it. Legacy event/user fields, synchronous callback mutations, reducer return values and routing stay in place. No new input dispatch architecture or foreign-language callback bridge is provided. The observer is persistent but entirely caller-owned. Attach only after model init and while idle. A zero-initialized observer and immutable frame-array/arenas remain alive until fully detached and the outermost model/Styled operation returns. The handler/user pointers are retained across calls; their pointees stay host-owned. All records/text/frame regions and observer/model/schema/editor storage must be disjoint. Overlap/provenance and idle attachment to an unobserved model are caller preconditions, not runtime-detected safety guarantees. Do not move/copy attached models/observers, reinitialize them, or overwrite private bookkeeping. ## Basic lifetime This bounded recorder copies a name into separate host storage for retention. It never retains a callback pointer or a shallow payload view. Call `recorder_start` after model init, keep the recorder at the same address, and detach while idle before its storage goes away. Example capacities are application bounds; payload failure is explicit, never silently truncated. ```c #include "cui/cui_questionnaire_observer.h" #include typedef struct { cui_questionnaire_observer observer; cui_questionnaire_observer_frame frames[3]; cui_questionnaire_item_snapshot records[3][16]; cui_str choices[3][64]; char text[3][2048]; char last_answer_item[128]; bool name_too_large; cui_questionnaire_payload_status last_payload_status; } questionnaire_recorder; static void record_questionnaire(void *user, const cui_questionnaire_observation *event) { questionnaire_recorder *recorder = user; recorder->last_payload_status = event->payload_status; if (event->kind != CUI_QUESTIONNAIRE_ANSWER_CHANGED || event->payload_status != CUI_QUESTIONNAIRE_PAYLOAD_READY) return; cui_str name = event->answer.name; recorder->name_too_large = name.length >= sizeof recorder->last_answer_item; if (recorder->name_too_large) return; memcpy(recorder->last_answer_item, name.data, name.length); recorder->last_answer_item[name.length] = 0; } cui_questionnaire_observer_result recorder_start(cui_questionnaire_state *state, questionnaire_recorder *recorder) { /* recorder must already be zero-initialized and neither attached nor in flight. */ for (size_t i = 0; i < 3; ++i) recorder->frames[i].workspace = (cui_questionnaire_snapshot_workspace){ .items = recorder->records[i], .item_capacity = 16, .choices = recorder->choices[i], .choice_capacity = 64, .text = recorder->text[i], .text_capacity = sizeof recorder->text[i] }; return cui_questionnaire_observer_attach(state, &recorder->observer, 900, recorder->frames, 3, (cui_questionnaire_observation_handler){record_questionnaire, recorder}); } ``` ## Delivery and copied payloads Each active legacy emission produces one synchronous typed attempt **before** the original legacy callback. The typed callback is observational: copy bytes and update unrelated host bookkeeping only. Do not mutate/submit model/UI, invoke validation or observer configuration, or destroy/rebind resources from it. Legacy callbacks retain existing model mutations, nested calls and replacement of event/user. Subsequent legacy follow-up eligibility is checked as before. Silent setters/reset remain silent; attaching does not synthesize changes or lifecycle events. CurrentChanged copies optional previous/current names; AnswerChanged copies item name, effective choices/freeform and status. Presence booleans distinguish absent from empty names. Completed and Submit share one submission frozen after successful validation, before either legacy callback. If Completed edits, disables, resets, replaces the legacy handler or performs a guarded nested submit, the outer Submit still carries the same original data. Nested submissions receive different frames. Repeated successful submit still emits Submit; failed validation emits no success pair. No copied editor draft, custom validation-message or schema-edit event exists. Snapshots follow the existing copy-out rules: schema order, selected enabled choice values in definition order, skipped/unanswered entries included, disabled items omitted from submission, copied strings with length-excluded NUL terminators. Current model UTF-8 validation rejects embedded NUL. Frame arenas and observation views are borrowed through their callback only. A shallow structure copy is not a deep retained event; copy all required strings/arrays into separate host storage. The outer pair's backing frame is pinned through the entire outer submit, including intervening legacy callbacks, but its stack-local observation pointer is not retained. Metadata maps current/answer to CHANGE, completed to COMMIT, submit to SUBMIT; family `kind` preserves exact meaning. The nonzero application target does not register an element. Origin is UNKNOWN and evidence flags are zero even for actual pointer/key/accessibility/input/timer paths. A Base hook has no proven causal frame/index/activation; do not infer one from nearby queued events. Genuine Styled metadata forwarding would require a separately audited API. ## Bounds, detach and errors One frame is reserved per active emission; a submit pair holds one across both notifications. Nested legacy emitting calls use extra frames. NO_FRAME gives honest empty copied fields; CAPACITY gives exact requirements and unchanged arena bytes; OVERFLOW and defensive INVALID give empty data/zero requirements. Failure is shared by an outer pair, with no retry against later mutated state. There is no allocation, event replay, legacy event loss, rollback or altered model return. A missing typed handler counts attempts but performs no copy/delivery. Statistics count active attempts, deliveries and failed payloads, saturating with an overflow flag. Removed/inactive observers do not count later emissions. Idle detach returns OK. Detach from a legacy callback returns BUSY to report pending removal: later typed attempts stop immediately, but existing frames remain pinned until final in-flight return. BUSY does not reject removal. Reattach/reconfigure while known in-flight returns BUSY, including a different observer attempting to replace a pending detached one. Already attached idle state returns ATTACHED. Once drained, the model association clears; the caller can attach again while idle. No destruction notification is emitted. Keep all users/frame/model/schema/editor storage alive through outer return and renderer consumption before freeing it. There is no arbitrary destruction guard or concurrent-use contract. The focused tests compare attached/unattached legacy mutation traces, immutable outer versus nested submit data, event/user replacement, live choose/skip follow-up, capacity/depth errors, detach pinning, copied names including empty identity, ordered input plus actual key/pointer/accessibility routes and delayed timer. Existing Questionnaire, Styled, keyboard and snapshot suites remain regressions. Canonical CMake compiles this example and a C++ header consumer. The worker fixture delegates to those canonical registrations. The pinned WASI runner includes the observer suite and fingerprints its private header. The all-in-one distribution runs the same focused observer regression suite; direct observer, legacy model, keyboard and snapshot implementation entries have strict declaration checks. General event/binding uniformity, physical AT acceptance and the family's presentation/localization/Form/style gaps remain open. --- ## Questionnaire named text presentation Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/QUESTIONNAIRE_PRESENTATION.md # Questionnaire named text presentation Include `cui_questionnaire_presentation.h` with its matching library revision. Title, Description and ChoiceDescription use independent explicit text options; there is no style cascade or state/options ABI extension. Existing heading stays unchanged. Zero named options extract its title/description text metrics; two separate wrappers do not recreate heading's internal gap automatically. `TEXT_TOKENS` opts into default token tiers for four legacy sizes: title 14/20,16/24,18/28,20/28 and secondary 12/16,12/16,14/20,16/24 (XSmall,Small,Medium,Large). Title is medium weight; secondary normal. It adds an item-gap spacer after title when schema description is absent. Shared XS–9XL uses proportional title 1.125/secondary.875 font and line scale, a CUI extension. Explicit masked refinements win, including natural line height zero, normal style and transparent color. Font family IDs require matching host font support. Title/Description check schema existence, independently of current/disabled status. Use a successful Item container to gate them, as below. Empty schema Description omits its wrapper unless explicit visible content or child exists. ChoiceDescription takes explicit content without state. Error retains legacy current-item/invalid gating and one Alert named by localized model error. Custom decorative content replaces paint, not the Alert name. Token Error adds an 8px top spacer and secondary typography; zero Error preserves legacy paint. ```c #include static void custom_description(cui_context *ui, cui_id id, const cui_questionnaire_text_view *view, void *user) { (void)user; cui_begin_box(ui, id, (cui_box){.width = -1}); cui_text_ex(ui, view->text, view->font_size, view->color, view->line_height, view->style); cui_end_box(ui); } void draw_question(cui_context *ui, const cui_theme *theme, cui_questionnaire_state *state, size_t item) { cui_questionnaire_options base = {0}; cui_questionnaire_text_options text = {.policy = CUI_QUESTIONNAIRE_TEXT_TOKENS}; if (cui_questionnaire_item_begin(ui, 100, state, item, base)) { (void)cui_questionnaire_title_ex(ui, 101, theme, state, item, base, text); text.render_child = custom_description; (void)cui_questionnaire_description_ex(ui, 102, theme, state, item, base, text); /* Compose existing choices/input here with the same state. */ text.render_child = NULL; (void)cui_questionnaire_error_ex(ui, 103, theme, state, item, base, text); cui_questionnaire_part_end(ui); } } ``` Masked visible strings accept explicit empty, require valid UTF-8 without NUL, and remain borrowed through completed-frame draw use. Descriptors are copied at entry. Callback/view/user are borrowed synchronously and not retained; callback must balance child boxes and must not mutate state, route input or close owner. Use the supplied child namespace and avoid collisions with application IDs. A child wins over visible override; resolved view retains that override for use by the child. Invalid active options reject before output or callbacks. True means accepted, including omission, not a transaction over child/layout errors. No model events, validation or editor flushing occurs from these parts. This is bounded text composition, not arbitrary Styled: card/container/input/Button, action trailing layout, Form role and full binding presentation remain separate. The focused unit suite compares independent extracted pre-change text bodies to zero presentation using draw values, memberwise Alert checks and actual software pixels. The deterministic test glyph provider proves metrics/style/color transport, not native font shaping. Token tables, first-line line boxes, long copy wrapping, explicit empty/custom precedence, descriptor snapshots and passive routed pointer/key/AT behavior are covered. Native host screen-reader acceptance and browser presentation controls are not claimed by this slice. Canonical builds register this implementation with the existing Questionnaire module. Standalone `CUI_QUESTIONNAIRE_IMPLEMENTATION` includes the presentation implementation needed by legacy Error; the new `CUI_QUESTIONNAIRE_PRESENTATION_IMPLEMENTATION` entry redirects once to that same module. Both require matching generated headers. `CUI_IMPLEMENTATION_ALL` also includes it. Packaged C headers do not provide language-builder callbacks. The gallery's independent named-text picker offers extracted legacy parts, localized token text, explicit 17px/26px refinement and decorative Error content. The default still uses the existing heading/Error helpers, and the progress picker remains independent. The long localized description is example content, not a translation service. Real WASM desktop/touch checks validate through Next, retain one localized Alert ID across mode changes, verify decorative paint and bounds, compile all selected C11 examples and navigate choices/back. Presentation mode changes emit no model events. This evidence does not cover the deferred container/card/input/action layout or a language-builder presentation facade. --- ## Questionnaire progress presentation Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/QUESTIONNAIRE_PROGRESS.md # Questionnaire progress presentation Include `cui/cui_questionnaire_progress.h`. `cui_questionnaire_progress_ex` adds explicit progress text/children without changing legacy options or state layout. Zero progress options preserve legacy drawing and semantics. Rebuild matching headers/library to use the added symbol. This is bounded progress presentation, not a full family typography cascade or language-builder facade. ```c #include "cui/cui_questionnaire_progress.h" #include /* Application-owned storage must survive completed-frame consumption. */ typedef struct { char label[96]; } progress_text; bool paint_progress(cui_context *ui, const cui_theme *theme, const cui_questionnaire_state *state, progress_text *storage) { size_t position = cui_questionnaire_position(state); size_t current = position == SIZE_MAX ? 0 : position + 1; int n = snprintf(storage->label, sizeof storage->label, "Frage %zu von %zu", current, cui_questionnaire_total(state)); if (n < 0 || (size_t)n >= sizeof storage->label) return false; return cui_questionnaire_progress_ex( ui, 71, theme, state, (cui_questionnaire_options){0}, (cui_questionnaire_progress_options){ .fields = CUI_QUESTIONNAIRE_PROGRESS_LABEL, .label = {storage->label, (size_t)n}, .text = {.fields = CUI_QUESTIONNAIRE_TEXT_SIZE | CUI_QUESTIONNAIRE_TEXT_LINE_HEIGHT, .font_size = 14, .line_height = 20}}); } ``` LABEL replaces the accessible name and default visible sentence. VISIBLE replaces only visible text. A custom `render_child` replaces visible content altogether; its callback receives current/total and resolved text metrics. Numeric progress semantics always come from enabled item position/total, never supplied text. No current means zero. This is not completion percentage. The role remains a passive progress bar, with minimum zero and maximum enabled total. The callback runs once inside the full-width progress wrapper, with a stable, nonzero child namespace distinct from the root semantic ID. Like existing child composition, callers avoid collisions with their other IDs; derived IDs are not a global collision-free allocator. Balance child boxes; do not close the wrapper, mutate the model or dispatch input. View/user are borrowed for the call, not retained. Use the view's metrics explicitly when rendering text; CUI does not inherit an implicit text cascade. Ordinary decorative children avoid duplicate progress nodes; custom interactive descendants own their separate semantics. No model events, validation/editor flush or input consumption are added by this helper. Masked empty text is explicit empty, including `{NULL,0}`. Empty VISIBLE can hide the sentence while keeping an accessible label/numbers. Normally keep LABEL meaningful. Strings require valid UTF-8 with no embedded NUL and remain borrowed through completed-frame draw/semantic consumption. Descriptors are copied on entry; root options do not publish these strings or refinements to other parts. Unmasked values are ignored. The host formats/pluralizes labels with public position/total queries before submission; no locale registry is retained. Text masks independently set font size, line height, color and the complete `cui_text_style`. Explicit normal weight/false flags/family zero/letter spacing zero work. Font size is finite (0,512]; line height finite [0,4096], zero natural. Known weight and finite tracking are required. Shaping/font-family fallback and negative tracking constraints still belong to the host/Core. Source typography token relationships can be supplied explicitly; legacy sizes and XS..9XL/root inheritance retain their existing metrics. No arbitrary Styled inheritance, other-part typography, Core Form role or language presentation API is supplied. Unknown masks/invalid active values reject before any draw, semantics or callback. False reports invalid arguments/options. True means accepted submission, not rollback of custom child layout errors; use normal frame error reporting. Even a custom child must supply valid masked fields. All existing callbacks and observers retain their previous behavior. The focused tests use deterministic metrics and a test-only rectangular-glyph coverage provider with the actual software renderer. This proves layout/style/ color transport and pixels, not FreeType shaping, system fonts or physical AT. Headless actual-WASM gallery tests additionally cover opt-in localized/short/custom/ text-metric modes, stable numeric semantics, unchanged default presentation, compiled selected C snippets and desktop pointer/touch model advancement. This does not establish native font shaping or full family browser parity. --- ## Questionnaire snapshots Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/QUESTIONNAIRE_SNAPSHOTS.md # Questionnaire snapshots Include `cui_questionnaire_snapshots.h` and rebuild with the matching library. These pure Base helpers copy effective answers into caller-owned item records, choice descriptors and text storage. They do not validate, submit, call handlers, synchronize an editor draft, service pending confirmation or change the model. They do not provide event observation or freeze a legacy callback sequence. Measure reports item/choice counts and text bytes including one NUL per copied string. Copy always measures again, then checks every capacity before writing to any workspace region. CAPACITY returns exact current requirements and an empty new output while preserving all prior workspace bytes. INVALID/UNKNOWN_ITEM/ OVERFLOW clear requirements and output. Null mandatory output pointers are INVALID. No truncation occurs, including when a positive text capacity is insufficient. All supplied workspace regions, required/output records and model/schema/editor storage must be mutually disjoint. This is a caller precondition; arbitrary pointer overlap/provenance is not detected. No concurrent model mutation is allowed during a call. Successful workspace reuse invalidates older snapshots; failed copies do not. A structure copy alone does not clone its pointed-to strings/arrays, and a memcpy-relocated arena does not automatically rebase them. ## Caller-owned retained copy This example retains a submission independently of subsequent model edits and source definitions. The bounded application workspace may be too small; the result and measured requirements tell the caller that explicitly. The saved object must stay at the same address while its snapshot is in use. Publishing only after a successful copy preserves the previous saved record and its storage on failure. ```c #include "cui/cui_questionnaire_snapshots.h" typedef struct { cui_questionnaire_item_snapshot items[16]; cui_str choices[64]; char text[4096]; cui_questionnaire_submission_snapshot snapshot; } saved_questionnaire; cui_questionnaire_snapshot_result save_questionnaire( const cui_questionnaire_state *state, saved_questionnaire *saved, cui_questionnaire_snapshot_requirements *required) { if (!saved) return CUI_QUESTIONNAIRE_SNAPSHOT_INVALID; const cui_questionnaire_snapshot_workspace workspace = { .items = saved->items, .item_capacity = 16, .choices = saved->choices, .choice_capacity = 64, .text = saved->text, .text_capacity = sizeof saved->text }; cui_questionnaire_submission_snapshot next = {0}; cui_questionnaire_snapshot_result result = cui_questionnaire_submission_copy(state, workspace, required, &next); if (result == CUI_QUESTIONNAIRE_SNAPSHOT_OK) saved->snapshot = next; return result; } ``` For one item use `answer_measure`/`answer_copy`, with at least one workspace item record and a separate `cui_questionnaire_item_snapshot` output. That record includes a copied identity name, original schema index, status, disabled flag and answer. Individual disabled items retain name/status but expose an empty answer. Submission copies omit disabled items, include unanswered and skipped enabled items, and use schema order. They are available before validation/completion; copying a submission does not certify that it is valid. Selected enabled choice values use definition order, not selection order. Labels, descriptions and validation messages are not included. Freeform comes from the retained effective answer; an unsynchronized editor draft is excluded. Whitespace normalization remains the model's responsibility. `has_freeform=false` has a NULL zero-length string; zero choices/submissions have NULL array pointers. Text is packed as each name, its choices, then present freeform, with an appended NUL for each string. cui_str lengths exclude appended NUL; empty names/values still consume one byte. The current model rejects embedded NUL in its UTF-8 validation, so initialized valid models cannot supply embedded-NUL values. Use length-aware consumers. There is no deduplication or borrowed schema string in a successful snapshot. Buffers survive model reset, edits and source teardown for as long as the caller keeps the snapshot workspace alive and unchanged. `query_copy` needs no workspace. It reports enabled progress, current schema index, action visibility, confirmability and completion. No current enabled item gives SIZE_MAX item/position, progress zero and false action/confirmability flags. A filled invalid answer remains confirmable; this flag means answered/skipped, not validated. Visibility reflects model policy, not disabled ancestors or host-omitted buttons. Failed query resets the same sentinels. Existing model bounds remain: 4096 items and default4096/max1MiB input answer bytes. Snapshot counts/string totals and record extents use checked size_t arithmetic, without a new fixed choice/string cap. The arithmetic test probes private helpers at SIZE_MAX boundaries without forging a publicly valid model or reading fictitious string storage. Portable C cannot validate arbitrary source pointer provenance. Worker validation includes strict Release headless model/Styled regressions, focused snapshot tests, compiled C example and C++ header, plus focused WASI. Pure copy-out has no pixels; actual WASM execution verifies portable buffer behavior. No generic bridge or binding API is added. Snapshot query/copy support does not complete Questionnaire's event payload, compound presentation, localization, Form semantic or broader style gaps. --- ## Optional regex allocation oracle: CI failure and validation Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/REGEX_CI_ALLOCATION_RECEIPT.md # Optional regex allocation oracle: CI failure and validation The optional-regex job in CI run 38557271424 failed at `backends/regex/src/tests.rs:362` with `match allocated \\Aabc\\z` (observed 2, expected 0). The old test allocator used process-wide `TRACK`, `CALLS`, and `FAIL` atomics. `--test-threads=1` serializes Rust test functions, but it does not prevent other harness or runtime threads from allocating while the oracle measures `matching`. Those unrelated calls could enter both the zero-allocation count and the fault-injection sequence. The allocator probe now uses a constant-initialized thread-local `Cell` for the measurement flag, allocation count, failure position, and live-byte balance. The `matching` assertion still requires exactly zero allocations on the calling thread. Fault injection still rejects each measured allocation position on that same thread, and the live-byte comparisons still check that failed preparations release their allocations. The new regression allocates on a worker thread while the test thread measures zero, then allocates on the test thread and verifies a positive count. Validation used the exact pinned Rust 1.85.1 toolchain and existing verified crate archives in `/dev/shm/cui-next33-regex-native`: ```sh python scripts/build_regex.py --cache /dev/shm/cui-next33-regex-native --toolchain /dev/shm/cui-next33-regex-toolchain/rust-1.85.1 CARGO_HOME=/dev/shm/cui-next33-regex-native/cargo RUSTC=/dev/shm/cui-next33-regex-toolchain/rust-1.85.1/bin/rustc /dev/shm/cui-next33-regex-toolchain/rust-1.85.1/bin/cargo test --offline --locked --release --manifest-path /dev/shm/cui-next33-regex-native/source/Cargo.toml --target-dir /dev/shm/cui-next33-regex-native/target -- --test-threads=1 ``` Build succeeded; both tests passed. The same locked offline test command also passed ten consecutive runs with `--test-threads=2`. The vendored `regex-automata` emits its existing unused-method warning; no new warnings were observed from `cui-regex`. --- ## Published prerelease: v0.1.0-alpha.4 Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/RELEASING.md # Published prerelease: v0.1.0-alpha.4 [**v0.1.0-alpha.4 is published**](https://github.com/mattmezza/cui/releases/tag/v0.1.0-alpha.4) from frozen source `17533b899dd8fd179e6135dac753dd40204ddef4` on 2026-11-01. Matching Pages output, API/header maps and the native starter archive were independently verified. Download the versioned **native starter** from the release assets, or use the website starter download. It includes CUI source, fonts, Makefile and editable native dashboard/mail examples. Read [the starter guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NATIVE_APP_STARTER.md). The release batches typed Slider and localized TimeField authoring, six-slot C Dialog composition, configured C Badge artwork, software/SDL_Renderer V2, Skeleton palettes/responsive roots and owned C bridge Icon utilities. Read the [changelog](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/CHANGELOG.md) for supported subsets and binding omissions. Exact-source [CI](https://github.com/mattmezza/cui/actions/runs/41305957916), [native bindings](https://github.com/mattmezza/cui/actions/runs/41305957837) and [Pages/browser gates](https://github.com/mattmezza/cui/actions/runs/41305957995) pass. Installed C, native Python/Node/TypeScript, Go/Rust source consumers, actual-font text and the downloadable starter pass. Draft assets were downloaded and verified byte-for-byte before publication. Read [the release receipt](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/validation/alpha4-release.json) and uploaded ASSET_MANIFEST.json and SHA256SUMS for provenance and limits. The earlier local native run was 606/607; its generated-summary mismatch was repaired with 6/6 affected checks. Final compiler and test-harness repairs passed their affected checks and the complete hosted matrix. All 19 current skill tests pass. Do not describe the earlier local run as a single607/607 pass. Python metadata is `0.1.0a4`; npm/Cargo/public C are `0.1.0-alpha.4`, with CMake base `0.1.0`. The nested Go tag `bindings/go/v0.1.0-alpha.4` points to the same source. All 637 public Go proxy module files match the installed-consumer-tested archive. PyPI/npm/crates.io publication remains separate. Linux binaries are host-tagged, not manylinux certified; physical GPU/OS/accessibility acceptance and full component parity remain unfinished. All 78 baseline families are retained. Previous release records below are historical. For future releases, freeze a new reviewed revision and substitute its version throughout. Keep both published alpha.4 tags and their asset bytes immutable. # Published prerelease: v0.1.0-alpha.3 [**v0.1.0-alpha.3 is published**](https://github.com/mattmezza/cui/releases/tag/v0.1.0-alpha.3) from frozen source `a7dee36090cbe9c1ca1db1c7bed0cd804c69985f` on 2026-10-31. The website was deployed and verified at that revision. The release adds civil DateTime selection, date-only picker actions, Questionnaire observations, snapshots, keyboard policies, progress, presentation and checked geometry, plus explicit Popover anchors/arrows. SDL3 and the browser gallery gain bounded analytic mesh consumers with pixel and failure-path evidence. The gallery has actual desktop/touch controls and compiled usage examples for the new options. The batch also includes Avatar metrics, identity palettes, SVG placeholders and typed activation observers; reusable VideoPlayer defaults, seek icons, player-only browser fullscreen and an audible sample; and optional bounded native video/audio and macOS Speech host integrations. Injected Apple fixtures are separate from physical microphone, permission and recognizer acceptance. Linux/Windows speech recognizers and broader native media support remain gaps. The release also adds opt-in Stepper connectors, bitmap indicators and shared design sizes, with a controlled interactive gallery; nested Resizable examples and repeated desktop/touch drag regression coverage; split-button styling and metadata; and growing InputGroup containment. Stepper visual builders are available in Python, JS/TS, Go and Rust; centered/flexible geometry and interaction presentation also have additive C APIs. Those newer C presentation options remain documented binding omissions. Input caret/selection/IME projection after viewport changes still has a documented one-frame limitation. These additions do not establish complete Stepper, Input or Resizable parity or native GPU acceptance. The release additionally includes Spinner finite/reduced-motion browser contracts, opt-in HoverCard raw outside-release policy, and initially hidden SDL3 window creation with explicit visibility APIs. Hidden-window authoring has focused Linux private-Xvfb tests in all five language paths; other native platforms, Wayland and physical GPU behavior remain separately unverified. Initial named-element shadow setters and CSS blur conversion reuse existing renderers. Six builder root kinds have typed overrides across Python, JS/TS, Go and Rust. Eight additive C Checkbox/Radio/group facades can name indicators; legacy routes preserve anonymous identities. Indicator bindings, compound parts and portals remain open. Read `ELEMENT_SHADOWS.md`, `BRIDGE_SHADOWS.md` and `NAMED_SELECTION_INDICATORS.md` for ownership and limitations. These additions passed integrated CI, release artifact and deployment checks; that evidence does not close their documented broader parity gaps. CI preparation reuses checksum-verified raw optional-regex downloads and shares a private umbrella implementation across feature distribution tests. Independent self-contained distribution and standalone-module checks remain. Local and Windows CI timing samples are documented in `DISTRIBUTION_TEST_BUILD.md`; they are observational comparisons rather than controlled speedup measurements. Describe final CI results from the frozen revision, not preparation runs from an earlier candidate. Rebuild consumers with matching headers and libraries: the Questionnaire state and several by-value options changed since alpha.2. Read the current binding coverage for C-only options; source packaging does not imply equivalent foreign APIs or registry publication. All 78 baseline families remain present, with feature-level omissions documented. Full parity is unfinished. The published notes and asset manifest record the actual frozen revision, tested subset, host dependencies and remaining limitations. Published alpha.2 (`v0.1.0-alpha.2`, Python `0.1.0a2`) remains immutable. Alpha.3 does not move or replace the alpha.2 tag or assets. Keep alpha.1 (`v0.1.0-alpha.1`, Python `0.1.0a1`) and any associated published assets immutable. This version update does not retag or replace alpha.1. No package-name ownership, registry authentication, trusted publisher configuration, or cross-platform native compatibility is established by changing metadata. Publish a coherent release after each major completed body of work; batch related commits together. Do not turn each implementation commit into a release. ## Publication evidence All exact-main gates passed: [CI](https://github.com/mattmezza/cui/actions/runs/41226410425), [native binding callbacks](https://github.com/mattmezza/cui/actions/runs/41226410434) and [Pages with three browser shards](https://github.com/mattmezza/cui/actions/runs/41226410372). The public site verifier checked the same revision, docs, all 78 entries, API headers and native starter archive. Ten release assets were downloaded from the draft and compared byte-for-byte with local staging before publication; nine payload SHA-256 values and both annotated tag targets matched. Assets contain the source archive, Linux x86_64 static C install bundle, native Python wheel/npm tarball, Go source proxy bundle, Rust crate, notes, manifest, source inspection receipt and checksums. Installed C, native Python/Node, separate strict TypeScript 5.8.3, real-font packaged text and native Go/Rust consumer checks passed. Binary artifacts were built/tested with GNU libc 2.42 and compatible system SDL/FreeType/HarfBuzz; they are not certified for every Linux distribution. GPU and physical-platform acceptance remain deferred. The manifest records the earlier offline TypeScript metadata miss and the separate successful cached-compiler check; the combined command is not falsely reported green. The public Go tag `bindings/go/v0.1.0-alpha.3` points to the same source commit; the public Go proxy version-info endpoint was also verified against that commit. This does not establish PyPI/npm/crates.io ownership or publication. Use the asset manifest and current binding coverage when choosing a downloadable package. The procedures below remain the checklist for future releases; replace the tag, version and frozen source together rather than republishing immutable alpha.3. ## Version and source freeze | Surface | Alpha.3 version | | --- | --- | | Repository/GitHub release | `v0.1.0-alpha.3` | | CMake ABI/base project version | `0.1.0` | | Public C `CUI_VERSION` | `0.1.0-alpha.3` | | Python / wheel metadata | `0.1.0a3` | | npm / Cargo | `0.1.0-alpha.3` | | Go proxy version | `v0.1.0-alpha.3` | | Public nested Go module tag | `bindings/go/v0.1.0-alpha.3` | The Go module is `github.com/mattmezza/cui/bindings/go`; its public Git tag needs the subdirectory prefix. A repository release tag alone does not publish this module version. See the [Go module tag rules](https://go.dev/ref/mod#vcs-version). CMake's base version does not promise stable alpha ABI or full binding parity. Choose one reviewed commit, finish metadata changes, regenerate SDK copies, and commit them **before** building final assets. Require a clean packaging checkout and verified source content/provenance. Record the full commit SHA, compiler/toolchain versions, architecture, build options, dependency receipts, and validation logs. Do not publish packages staged from a dirty checkout just because packaging allows it. SDK `SOURCE_PROVENANCE.json` records the historical generator step; its HEAD and dirty flag are not a packaging-checkout receipt. Preserve it rather than rewriting history. Verify the complete generated SDK map against the frozen checkout and record the packaging commit plus final archive hashes externally. Alpha.3 includes that complete comparison in `source-artifact-inspection.json`. The audited tree repeats versions in Python project metadata, wheel backend NAME and METADATA, npm, Cargo, the Go packaging function, and CI artifact filenames. The Go `.info` timestamp is derived from the packaged Git revision. Verify it against the frozen revision before publishing a proxy bundle. Future version bumps must audit these literals or centralize their generation. The checker below requires Python 3.11 or newer and deliberately checks the existing format rather than rewriting binding manifests: ```sh python scripts/test_release_metadata.py --tag v0.1.0-alpha.3 python scripts/test_release_metadata.py --self-test ``` ## Build and review the assets Use a frozen checkout and an external build/output directory. The commands here are preparation examples; substitute approved absolute paths. Final artifact builds must wait until the integrator declares the source frozen. ```sh cmake -S . -B "$build_dir" -G Ninja -DCMAKE_BUILD_TYPE=Release -DCUI_BUILD_NATIVE=ON cmake --build "$build_dir" python scripts/test_local.py --build-dir "$build_dir" CUI_PACKAGE_NATIVE=1 python scripts/package_bindings.py python --output "$assets/native-python" CUI_PACKAGE_NATIVE=1 python scripts/package_bindings.py node --prebuilt --output "$assets/native-node" python scripts/package_bindings.py go --source-only --output "$assets/go-source" python scripts/package_bindings.py rust --output "$assets/rust-source" ``` Run SDK generator freshness checks and the installed-package, installed-text, and binding-run validators against these **exact** outputs. Consult [PACKAGING.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PACKAGING.md), [INSTALLED_TEXT_VALIDATION.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/INSTALLED_TEXT_VALIDATION.md), and [BINDING_NATIVE_RUN.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BINDING_NATIVE_RUN.md) for commands and prerequisites. Actual-font checks must pass rather than silently skip. Native Linux tests use the private Xvfb wrapper; never the maintainer's DISPLAY or Wayland session. Hardware GPU validation remains explicitly deferred where unsupported by Xvfb. Source-module validation alone does not validate exported archives. Review this asset inventory before creating a release: - A source archive from the frozen tag, with the full modular `include/cui` headers, sources, dependency manifest, licenses and build instructions. If shipping generated distribution headers, check their freshness separately. - An installed C library/header bundle labelled with OS, architecture, build configuration and shared/static flavor; include runtime dependency information and the license/notices for every included component. Test its consumer path. - The native Linux Python wheel and prebuilt npm tarball, with embedded source receipts and build information. Preserve valid original package filenames. - The Go source proxy `.zip`, `.mod`, `.info` as one labelled archive; the verified Rust `.crate`. Source packages can require local native development libraries. - Release notes, an asset manifest mapping every file to commit/build/flavor, SHA256SUMS, dependency/runtime reports, and validation logs or linked CI runs. Portable and native wheel/npm builds currently have identical basenames and versions. Keep separate output directories; for GitHub, put them inside clearly labelled outer archives if publishing both. Never overwrite one flavor with the other, or rename a wheel's compatibility tag to imply broader portability. The alpha wheel is host Linux tagged, **not manylinux certified**. Native assets currently have Linux validation only; label the actual tested architecture, not “all Linux” or “cross-platform”. Document SDL >= 3.2, FreeType, HarfBuzz and actual dynamic dependencies from the produced binary. Bundling a bridge does not bundle all its runtime dependencies. Keep the CUI MIT license and applicable third-party licenses/notices from `third_party/dependencies.json`; do not reduce third-party licensing to the top-level MIT license. ## GitHub prerelease publication The integrator executes these steps after checking the final manifest and tests. Set `release_sha` to the full frozen commit and `assets` to the reviewed output. Generate checksums over the final uploaded files, excluding SHA256SUMS itself; verify them after downloading the draft assets. Avoid uploading duplicate asset basenames. Prepare release notes describing the tested subset, explicit platform and runtime requirements, known limitations, and source revision. ```sh tag=v0.1.0-alpha.3 git tag -a "$tag" "$release_sha" -m "CUI $tag" git push origin "refs/tags/$tag" gh release create "$tag" --repo mattmezza/cui --verify-tag --draft --prerelease \ --title "CUI $tag" --notes-file "$assets/RELEASE_NOTES.md" "$assets/upload/"* # Inspect/download the draft and verify its manifest and checksums first. gh release edit "$tag" --repo mattmezza/cui --draft=false --prerelease ``` The source archive served by GitHub and any custom source bundle must resolve to the same tag SHA. Deploy the website from the corresponding reviewed source and verify its revision; a successful Pages deployment does not publish any registry package. Do not move a published tag to accommodate later website corrections. ## Registry gates (separate publication decisions) At the audited revision, npm has `private: true` and Cargo has `publish = false`. These intentionally prevent publication. The existing CI packages and tests local artifacts; there is no registry release workflow. Pages' `id-token: write` permission is for Pages deployment and proves nothing about registry trust. `python scripts/test_release_metadata.py --registries` rejects these observable manifest blockers; passing it would still not prove the gates below. **PyPI:** establish ownership/availability of `cui-bridge`, approve the distribution policy and Linux compatibility, and configure the exact GitHub repository, workflow filename and environment as a trusted publisher. Give only the publish job `id-token: write`, with environment protections and pinned actions; test a separate TestPyPI publisher first if desired. Review metadata, license contents, wheel RECORD, native dependencies and install tests. Current packaging does not establish manylinux policy compliance. See [PyPI publisher setup](https://docs.pypi.org/trusted-publishers/adding-a-publisher/) and [publishing permissions](https://docs.pypi.org/trusted-publishers/using-a-publisher/). **npm:** verify control of `@cui`, explicitly approve removing `private`, choose public scoped access, and configure a supported trusted publisher for the exact workflow/environment. Publish the reviewed native flavor only after deciding its runtime policy; an alpha should use an explicit `alpha` dist-tag rather than silently replacing `latest`, e.g. `npm publish reviewed.tgz --access public --tag alpha`. See [npm trusted publishing](https://docs.npmjs.com/trusted-publishers/) and [public scoped packages](https://docs.npmjs.com/creating-and-publishing-scoped-public-packages/). No npm login or ownership check was performed in this audit. **crates.io:** verify `cui-builders` ownership/availability and publisher credentials, explicitly approve enabling publication, inspect `cargo package --list`, and run `cargo publish --dry-run` with the intended features and clean consumer builds. The current packaging helper uses `--allow-dirty --no-verify --offline`; a generated crate is not evidence that registry verification passed. See [Cargo manifest publication controls](https://doc.rust-lang.org/cargo/reference/manifest.html#the-publish-field). **Go:** validate a clean external consumer without local `replace` paths, then push the separate `bindings/go/v0.1.0-alpha.3` tag at the same release SHA if publishing that module is intended. Check public source retrieval and module checksums. A local proxy archive is not proof that public proxy ingestion works. ## Corrections and rollback Keep published versions and tags immutable. Before publishing a draft, replace incorrect draft assets and regenerate checksums. After publication, document the problem, use registry-supported deprecation/yank mechanisms when appropriate, and issue a new version (for example, `v0.1.0-alpha.3`, Python `0.1.0a3`) with corrected assets. Never retag, force-push, or upload different bytes under an already published version. A website rollback can deploy a known-good revision independently while clearly identifying which library release its instructions describe. --- ## Resizable panels Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/RESIZABLE.md # Resizable panels This module follows the frozen upstream kit 0.7.1 Resizable group, panel, state and handle sources. Base owns sizing and interaction; components paint the theme's hairline and engagement indicator. It uses portable C11 and caller-owned bounded storage, with no platform types or allocation during layout/drag. ```c cui_resizable_slot slots[3]; cui_resizable_state state; cui_resizable_state_init(&state, slots, 3); /* once, outside rendering */ cui_resizable_panel panels[] = { {.id = 101, .has_initial_size = true, .initial_size = 240, .content = sidebar, .content_user = app}, {.id = 102, .content = main_content, .content_user = app}, }; cui_resizable_options options = cui_resizable_options_default(); options.now_seconds = now_seconds; /* monotonic host time */ options.reduced_motion = reduced_motion; /* Between begin_frame/end_frame, inside a sized parent: */ cui_resizable(ui, 100, &theme, &state, panels, 2, options); ``` `disabled` freezes handle input while panel content remains usable. Whole-subtree inert presentation can be selected through the normal group box option. The state and slots must remain valid through `cui_end_frame`, which writes retained group/panel bounds. Capacity is fixed on initialization, at most 1024. Configure core `max_elements`, command and frame capacities for the composed content as well: slot capacity does not reserve renderer/layout capacity. Slot fields and measured bounds are exposed for inspection, not arbitrary mutation. Reusing a state for unrelated simultaneously rendered groups is unsupported. Horizontal is the default sizing axis; Vertical stacks panes. `extent` sets the size along that axis, and `cross_size` sets the other dimension, matching the source group's cross-axis `size` option. Zero selects automatic parent sizing; box fixed-zero flags permit explicit collapsed dimensions. Group/panel box styles permit padding, colors and borders, while group direction/gap and panel axis size/min/max stay managed. Panel callbacks run inside their available content area and may compose further Resizable groups with distinct IDs and states. IDs are stable and unique across the UI; reserve the IDs returned by `cui_resizable_handle_id` for this group. Default ranges are 100 pixels to the largest float. Explicit initial preferences are used when a stable panel ID first appears; otherwise remaining space is shared by flexible panes. Automatic layout reads its actual first-frame panel bounds before settling the retained model, preserving a 240-pixel sidebar beside a flexible pane. Later container resizing preserves proportions subject to constraints, with no second-frame divider jump. Both axes, nested groups and first-frame full-cross-axis handle bands use real layout rather than root portals. `hidden` removes a pane's body and adjoining handle while retaining its slot for later reuse. Visible neighbors receive its available space. `cui_resizable_sync` is the pure model entry point. It validates declarations before mutation, preserves state through stable-ID reorder/replacement, and reports `CAPACITY`, `INVALID` or `INFEASIBLE`. Infeasible minima deliberately overflow; insufficient maxima deliberately leave unused space. Sizes still respect declared ranges; `fit_constraints` exposes whether the full extent can be filled. This is an improvement over the frozen source's unconstrained proportional scaling and recipient growth beyond its maximum. Core clipping is a caller policy. Dragging expands the preceding pane by borrowing from subsequent visible panes in order. Shrinking can cascade into earlier panes at their minima and distributes freed space to subsequent panes subject to maxima. Pointer capture continues when the pointer leaves the nine-pixel band; a hard constraint remains fixed until the pointer returns past that constraint. A primary drag release emits one completed resize via `state.on_resize`; Escape, cancellation, disabling or removing the active handle cancels ownership without a completion callback. Completion follows the initiating primary button, rather than the source's global any-mouse-up hook. The observer and userdata are borrowed, called synchronously, and must not replace state/storage or declarations during rendering. `cui_resizable_resize_panel` uses the same redistribution rules and emits a completion even when a valid request is constrained to the existing size. The last visible pane is driven through its previous sibling. Invalid indices/values are no-ops. `insert`, `remove`, `reset` and `clear` provide explicit lifecycle operations; keep the next rendered panel declarations in agreement with the state. Reset preserves size and the currently declared ranges while clearing motion and active ownership; it does not invalidate a collapsed pane's legal zero minimum. Lifecycle operations do not emit completed user-resize events. `save` writes sizes in current stable-ID order; store matching IDs alongside them in application preferences. `restore` validates the whole vector, applies current constraints/proportions and emits one completion. This is a portable snapshot boundary, not an implicit filesystem or JSON service. Pane IDs have passive Group semantics, with an optional `accessibility_label`. Handles are focusable Separators with the controlled pane ID, current size, reachable range, visual divider orientation and resize cursor hint. Native/browser cursor adapters are supplied by core. Horizontal handles accept Left/Right; Vertical handles accept Up/Down. The step defaults to ten pixels; Shift multiplies it by ten. Home collapses preceding panes as far as constraints permit; End grows the controlled pane as far as it can borrow. These keyboard alternatives are a C accessibility improvement: the frozen source implements pointer resizing only. `cui_base_resize_handle` submits semantics and consumes actual targeted events without painting; applications draw its band at the same ID. The styled divider is a one-pixel theme border line. Its three-pixel rounded pill has idle/hovered/pressed/dragging lengths 0/20/28/44 and opacities 0/.35/.6/.9. Supply monotonic `now_seconds`. The persistent indicator retargets from its current sample, including fade-out, and requests frames only during motion. Defaults match the source's 120ms cubic Bézier (.2,0,0,1). `duration_seconds` and `reduced_motion` are explicit host options because C Theme currently has no shared fast-duration/easing tokens. Use the constructor for source defaults; zero-initialized options select immediate motion. `appearance` may replace the paint and can decline to retain the default; its band uses -1 for a cross dimension that fills the current parent. It does not replace hit testing, cursor, constraints or ownership. `cui_resize_handle_rectangles` exposes source nine-pixel straddling and five-pixel leading/trailing bands with exact outermost-pixel seams. The reusable `cui_resize_handle_appearance` paints inside an application-owned open band. Unlike the source's deferred hugging-edge pill, this helper respects ancestor clipping; a host that needs the outer overhang may compose its own overlay appearance. Clipping a following panel also clips its straddling handle, as the frozen source's panel-style warning describes. Do not set panel clipping when that outside half must remain grabbable; group/ancestor clipping safely constrains the whole layout. Tracked boundaries: shared theme motion tokens and arbitrary native upstream drag payload objects are not built-ins here. Applications retain state and provide content/callbacks; durable preference storage is host-owned. This implementation provides substantive sizing, composition, painting and real input, not a claim of complete native API equivalence. The gallery demonstrates a small workspace with selectable files, a read-only code preview, contrasting pane backgrounds and live pane dimensions. Drag the divider or focus it and press arrow keys; the browser checks both the retained sizes and the visible pane widths/positions. The vertical mode demonstrates the same model with pane heights. Repeated release/regrab, DPR 1/2 desktop and 390 px touch dragging, keyboard sizing and responsive clamps are verified by the focused browser tests; see `docs/RESIZABLE_BROWSER_REAUDIT.md`. A pane already at its minimum/maximum cannot move farther in that direction. Keep the sum of visible minima at or below the available extent and the sum of maxima at or above it: an infeasible container cannot provide the requested resizing range. The current gallery uses a responsive maximum for its flexible editor pane. Native window/GPU interaction remains a separate audit. Select **Nested editor / console** in the gallery for a horizontal explorer/workspace split containing an independent vertical code/console split. Each group retains its own state, slots and IDs. The inner cross size uses the outer pane size after outer input reduction, so horizontal resizing updates both inner widths in the same frame. The existing two-pane example remains the default. Switching mode clears both models; the vertical-layout toggle applies only to the default example. The copied C example initializes both states once and documents the borrowed theme/content lifetimes. Both local and whole-preview disabled controls explicitly disable both groups. --- ## Resizable drag re-audit Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/RESIZABLE_BROWSER_REAUDIT.md # Resizable drag re-audit Audited source: `5da9acf8bb33344c4f2ad28f5a3870beab7ddb97`. No production regression was reproduced in a freshly built local WASM gallery. This records tested behavior on that source, not a claim about every deployed artifact, native window adapter or complete frozen-family parity. The earlier wide-layout failure was fixed by `3a81b7ae`: the editor's fixed 600 px maximum plus the explorer's 300 px maximum made wide containers infeasible. The current story uses a responsive editor maximum. No second fix is needed for that already-corrected case. The original reproduction and fix are recorded in `docs/RESIZABLE_DRAG_AUDIT.md`. | Proof | Actual coverage | | --- | --- | | `tests/web/test_resizable_repeated_drag.py` | Desktop DPR 1/2 and CDP touch at 390 px/DPR 2; both axes; six alternating release/regrab drags per axis; both pane sizes and positions and painted rectangles; min/max; Home/End/arrows; disabled input; viewport changes to 500/390/800 px followed by more dragging | | `tests/web/test_resizable_drag.py` | 24 mouse/touch cases across 390/1280/1920 px, both axes and comfortable/compact density; actual pane/content geometry, disabled state and keyboard resize | | Release `test_resizable` through `scripts/test_local.py` | Sizing, invalid declarations, constraints, persistence, targeted input, completion callbacks, paint/motion and nested groups | | WASI `resizable` suite | Same portable unit suite, including nested cross-axis growth and inner capture leaving the parent unchanged; this is not a browser nested-gallery test | All checks passed. The nested fixture lives in `tests/unit/test_resizable.c` (`nested_content` and `test_styled`), rather than pretending the two-pane gallery contains a nested example. Native window/GPU interaction remains unaudited here; native validation used the private-display wrapper only. Reproduce with a pinned tool environment, headless browsers and a home-cache temporary/build directory: ```sh python scripts/build_web.py --output /path/outside/source/web uv run --offline tests/web/test_resizable_repeated_drag.py --directory /path/outside/source/web uv run --offline tests/web/test_resizable_drag.py --directory /path/outside/source/web --output /path/outside/source/report python scripts/test_local.py --build-dir /path/outside/source/native -- -R '^resizable$' --output-on-failure uv run --offline scripts/test_wasi.py --build-dir /path/outside/source/wasi --suite resizable ``` The native build must first configure the source and build `test_resizable`. No dependencies were installed from the network and no desktop windows opened. ## Nested gallery follow-up `tests/web/test_resizable_nested_gallery.py` exercises the selectable explorer / code / console composition on desktop DPR 1/2 and CDP touch at 390 px/DPR 2. Both independent handles are dragged and released repeatedly. It checks actual pane and paint bounds, inner capture preserving the outer split, outer resizing updating both inner widths while preserving heights, pointer and keyboard bounds, local/global disabled policies and a route transition during capture followed by a fresh working nested split. The concrete default and nested copied C examples compile with strict C11 warnings. This closes the earlier browser-nesting test gap for this composition; native window/GPU and arbitrary consumer nesting remain separate validation scopes. --- ## Root Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/ROOT.md # Root `cui_root` is a caller-owned, per-window content and overlay host. Zero-initialize it before `cui_root_init`, and call `cui_root_dispose` before reinitializing. Base owns the root and its ordered plugin registry. Applications register plugins during initialization, then create one root and a separate plugin-instance array for each window. Registration uses an application-defined numeric key: registering the key again replaces its factory in place for future roots, while existing roots keep their snapshot and state. Factories receive a per-window pointer and return caller-owned state that must outlive the root. Each frame runs plugin `prepare` callbacks in registration order, then `style` callbacks, then applies an optional instance style refinement. Set the corresponding flag for each override field so unspecified plugin defaults remain intact. `decorate_begin` callbacks wrap the root in reverse registration order and matching `decorate_end` callbacks close the wrappers in registration order: the last plugin is outermost. Application content renders once; plugin overlays render once in registration order inside an absolute, full-root overlay host above it. Ordinary plugin children do not consume application layout space; they start at the root origin independently of root padding and follow outer decorators. Plugins may still open viewport portals for floating content. All callbacks run synchronously. Root requires a viewport starting at `(0, 0)` with positive finite dimensions. The plugin registry and root arrays have caller-specified capacities; invalid root capacity is rejected before any factory executes. If a later factory fails, Root calls each earlier plugin's optional `destroy` hook in reverse order and leaves the root uninitialized. `cui_root_dispose` calls those hooks for a completed root; factories that allocate resources must provide a matching hook. For a styled window, initialize and bind caller-owned Dialog slots and an initialized Notification state once with `cui_root_bind_facilities`. Pass a `cui_surface_state` initialized as a Dialog or Alert to `cui_root_dialog_open`, or a Sheet to `cui_root_sheet_open`; both accept a content callback. `cui_root_render` mounts the active Sheet, Dialog stack and Notifications after application content on every frame. The app content callback never needs to mount those layers. Dialogs keep their own focus scopes and Escape handling; nested dialogs paint above their parents. At most eight dialogs can be bound so all Dialog layers remain below the Notification layer. Notifications are laid out in the remaining window area outside the active Sheet, using its current size and edge. Closed Dialog slots are reclaimed on the next open. The root does not own the surfaces, notification entries, plugin state, strings or callbacks. For Base-only composition, call `cui_base_root_render` with application content and optional facility callback. It has no dependency on a styled plugin. A host can install `cui_root_set_copy_hook` to copy its current selection on an unconsumed Ctrl/Cmd-C event. The callback retrieves selected text and writes to the host clipboard; Root does not infer selection from widgets. Input and Textarea consume their own copy events before this fallback runs. This covers the source Root's per-window state, registry snapshots, render stages, instance style precedence and automatic Sheet/Dialog/Notification mounting. The source's entity observation, deferred notifications, OS window helper, platform window chrome, global text-selection scope, tooltip/native-menu/touch-selection hosts, and copy selection layer remain unimplemented in this module. Applications currently drive frame scheduling and window lifecycle explicitly; completing those facilities remains part of the parity target. This root does not yet establish complete upstream parity. --- ## Rust controlled Single/Range Slider Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/RUST_SLIDER_MODEL.md # Rust controlled Single/Range Slider Unreleased bridge-owned V1 subset, separate from `Kind::Slider` and its existing scalar float/autocommit/CHANGE behavior. This binds owned controlled values and receipts, not arbitrary direct C Styled style/motion records. Native numeric AT, typed SET/touch injection, V2 gradient adapters and vertical registered-scroll admission remain separate open work. Linux dynamic tests passed on Rust1.99.1: 14 actual UI tests, three private wire tests, 43 actual-old/provider processes, four authored example modes and four compile-fail thread/context checks. The current legacy/native suite also passed under private Xvfb with bundled Inter; separately gated historical fixture branches are not implied. Matching default bundled-static source closure also passed, with the static cfg actually compiled and no dynamic bridge dependency. MSRV1.85.1 remains a required follow-up. This is not a package publication claim. Read the [C authority](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_SLIDER_MODEL.md). ## Complete authored UI [Copy the complete Rust program](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/rust/examples/slider_model.rs). It authors a nested Row/Column control, heading/status labels, an acceptance button and an external Single/Range owner. Its restricted callback explicitly accepts whole pairs and then updates the owner and real status label. It focuses actual thumb bounds, queues a key and checks acceptance or rejection. Default execution is windowless; this is not a launcher-only example. Use existing [C11/CMake/Ninja prerequisites](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DEPENDENCIES.md), Rust 1.85.1 or newer and the dependency-free crate. From the repository root: ```sh cmake -S . -B build -G Ninja -DCUI_BUILD_NATIVE=OFF -DCUI_BUILD_BRIDGE=ON cmake --build build --target cui_bridge CUI_BRIDGE_LIB_DIR="$PWD/build" CARGO_BUILD_JOBS=1 cargo run --offline --locked --manifest-path bindings/rust/Cargo.toml --example slider_model CUI_BRIDGE_LIB_DIR="$PWD/build" CARGO_BUILD_JOBS=1 cargo run --offline --locked --manifest-path bindings/rust/Cargo.toml --example slider_model -- --reject --vertical CUI_BRIDGE_LIB_DIR="$PWD/build" CARGO_BUILD_JOBS=1 cargo run --offline --locked --manifest-path bindings/rust/Cargo.toml --example slider_model -- --single ``` The shared-library directory must be absolute. Without CUI_BRIDGE_LIB_DIR, the existing Linux source build compiles the matching bundled SDK. That path passed the same 14 UI/three wire/four example checks locally; it is not compatibility with arbitrary older static archives. Dynamic old libraries are supported through optional-symbol fallback. No command installs dependencies. Automated native tests must use the private `scripts/test_local.py` wrapper; physical display/GPU/AT proof is separate. ## Owned records and explicit authority `SliderValue::Single { end }` and `Range { start,end }` use f64 throughout. Config and domain are ordinary owned Copy records; `SliderConfig::default()` supplies one complete configuration. Public application records may be edited locally; submission validates and copies them atomically. Domains require finite bounds, finite nonnegative step and finite maximum-minus-minimum. Logarithmic domains require minimum > 0 and maximum > minimum. Parent layout ignores authored length and copies 0; malformed native parent length rejects rather than normalizing. `App::slider_model(parent,key,config,value)` requires an existing Row/Column parent. It validates before the C factory, which validates actual ancestry atomically. Rust has no retained unmounted typed node or implicit root. Invalid creation leaves previously authored UI intact. `configure_slider` replaces the whole config and pair; `set_slider_value` replaces only the current-kind pair. The corresponding owned getters are `slider_config` and `slider_value`. Use the existing `component_disabled` for this control; the legacy `disabled` method retains its Button-only contract. `supports_slider_model()` resolves the complete 16-symbol optional group, V1 bit and all five exact size queries. An incomplete/unsupported group returns false; new operations return Error(9), with no scalar emulation. Old operations do not enable or allocate the new queue. Call `enable_slider_requests(capacity)` before authoring controls, polling or registering callbacks; capacity 0 means 4096, maximum 4096. Reenabling does not silently resize or discard a backlog. `poll_slider_request()` returns one owned `Option` and invokes no callback. Every C uint64 stays u64, including frame/index absence sentinel, epoch/source/revision/sequence and pointer/device/accessibility IDs. Values and domains are never narrowed through f32. Only actual geometry uses f32. Unknown wire enums/masks and inconsistent unavailable evidence reject before publication. `SliderReceipt::clone()` preserves issued authority; `info()` returns only inert metadata. Private Rc namespace identity contains no App/native pointer and keeps receipts local, not Send/Sync. Copies remain readable after removal/App Drop; acceptance still expires in C. Keep receipts/handles within the matching App and loaded bridge image. This is not a security or process-global namespace promise. `accept_slider_request(&receipt,whole_pair)` is explicit; it may choose another valid pair. Update external owner storage only after success. Reading, polling, callback absence and rejection never autoaccept or emit CHANGE. Request current is the immutable submission entry, while requested intent evolves in original input order. Later errors never roll back effects already accepted by the owner. ## Restricted callbacks and teardown Register `on_slider_request(node,handler)` with: ```text for<'a> FnMut(&mut SliderRequestContext<'a>, SliderRequest) -> Result<()> + 'static ``` The context temporarily borrows the App and exposes only accept, configure, set/get value, get config, text, disabled, remove, queued pointer/key/text input, request_close and typed handler replacement/removal. There is no Deref/as-App, step/run/dispatch, owned destruction or App replacement escape. Mutating external owner state/userdata and enqueueing future work are allowed. Native buffers and callback-map borrows never span user code; each request is copied before calling the handler. Replacing/removing the current handler is supported. `step` only steps. `dispatch` drains the unchanged legacy FIFO first, then the independent typed FIFO if enabled. No cross-queue global order is invented. `dispatch_slider_requests` drains only the latter. Counts follow Rust's existing convention of callbacks actually invoked. Error or panic consumes the current entry and stops that drain; later entries remain queued. Its local guard resets on both paths. Manual panic propagates normally; native `run_with` retains its existing catch/resume boundary outside C. `request_close` in the context calls the existing request-only App::close. It records typed-local closing evidence, clears new handlers and stops before another typed poll. It does not destroy App or assume Python teardown semantics. Drop remains the owner of native destruction after the borrow ends. Successful remove releases new registrations for the removed node/subtree. Legacy callback registration policy stays unchanged. App remains !Send/!Sync through its existing Rc marker. Keep the creating OS thread alive through Drop and serialize calls. Part bounds return actual completed geometry or None; disabled track/fill remain, thumbs omit. Presentation returns copied status and absolute accumulated Core-time wake values, not physical render success, V2 support or an automatic Rust scheduler. ## Reproducible optional protocol proof Normal `cargo test` includes current-library UI and private wire-copy tests. Historical old-library/provider proof requires a separately supplied actual old module; no old binary is vendored or inferred from a successful current run. On Linux, with existing Cargo/C11 tools and reused build/target directories: ```sh python bindings/rust/tests/test_slider_protocol.py --build-dir build --target-dir /absolute/existing/cargo-target --old-library /absolute/pre-typed/libcui_bridge.so ``` The runner compiles only the Rust protocol test against that old library and 17 tiny providers, then runs each process through private Xvfb. The actual-old case has no preload; the other cases explicitly preload one optional-group provider while legacy entrypoints still come from the old module. All16 missing symbols, version/size rejection, malformed copied records and u64 extremes are separate cases. This synthetic evidence does not replace actual authored UI tests, prove another OS, or establish physical input/accessibility delivery. The same optional Linux protocol proof can be registered in the repository CTest suite with `-DCUI_RUST_SLIDER_OLD_LIBRARY=/absolute/path/libcui_bridge.so`. `CUI_RUST_SLIDER_TARGET_DIR` selects a reused Cargo target directory (default: `build/rust-slider-target`). It requires existing Cargo/C11 tools and cached prerequisites; the runner uses offline/locked builds, downloads no historical binary and runs through the private-display wrapper. This optional provider gate does not replace current authored UI, default-static or minimum-compiler checks. --- ## Scrollable content Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SCROLL.md # Scrollable content `cui_scrollable_begin`/`cui_scrollable_end` wrap caller content in a fixed-size clipped viewport with application-owned horizontal/vertical offsets. Content dimensions are explicit by default; the kit clamps offsets, translates children with fractional precision, and draws optional themed scrollbars. `cui_base_scrollable` performs the same reductions and semantic submission without drawing. Negative or nonfinite sizes use documented defaults (320×240 viewport, 10-pixel bars, 48-pixel wheel steps); axes not enabled remain at zero. Wheel events route to the innermost eligible clipped semantic scroll region under the pointer. A container at a boundary passes the event to an eligible parent based on the preceding frame's offsets. Higher interactive portals and unrelated modal scopes block background scrolling. Initial routing uses preceding-frame geometry. A child may explicitly defer an unconsumed scroll to an eligible layout ancestor with `cui_defer_scroll_event`. Prefer `cui_scrollable_end_ex` with mutable state: it handles deferred events after children and updates the current frame's viewport offset and scrollbar paint. Handled wheel events are consumed, so the finish phase does not replay begin-phase movement. The original const-state `cui_scrollable_end` remains a paint-only compatibility API and cannot process late deferrals. Custom base compositions can call `cui_base_scrollable_finish` and `cui_set_box_scroll_offset` after children. `hide_scrollbars` keeps the full viewport available without drawing tracks. `axis_lock` routes each event by its dominant axis (ties are vertical). `trap_horizontal` consumes horizontal-dominant movement even at the horizontal boundary, matching embedded table masks. Optional `gesture_lock` retains the initial precise-scroll axis across frames by stable semantic ID: a 28 ms quiet interval or an explicit gesture boundary starts a new gesture; a sufficiently strong perpendicular turn releases the lock. Ordinary line wheels remain unchanged. The persistent lock is disabled on WebAssembly to match the pinned upstream behavior. Routing filters only eligible, visible owners and supplies the filtered event to child/parent reducers consistently. Removing or disabling the owner clears its retained state. Scrollbars expose their controlled value, range, orientation and related content. Arrow keys step, PageUp/PageDown move one viewport, and Home/End select an endpoint. Clicking a track pages toward the click; captured thumb dragging preserves the initial grab offset across frames. Secondary-button events do not change primary dragging. Disabled scrolling preserves the caller's current offsets after clamping; callers independently control the disabled state of their children. `tests/unit/test_scroll.c` exercises both axes, wheel routing, translated row geometry and clipped hits, scrollbar keyboard and captured dragging, semantics, all four themes, invalid offsets and small content. A separate base-only executable links only core and the scroll reducer. Bare layout fixtures emit their own clip commands; a behavior-only frame proves the reducer paints nothing. Core tests independently cover nested boundary routing and higher-portal blocking. Grow-sized viewports, inertial/touch scrolling, auto-hidden/system-style bars, accessibility platform bridges, fractional DPI pixel snapping and exhaustive upstream integration remain unfinished. Existing virtual tree/table models can provide content dimensions and visible ranges; this container does not imply those models are rendered automatically. The browser gallery forwards pixel wheel deltas as precise CUI scroll events for Scrollable, Sidebar and VirtualList. Fractional deltas retain their distance rather than being multiplied by the widget's discrete wheel step. Native hosts can opt into the same contract with `cui_event.scroll_precise = true`; discrete wheel events continue to use the configured step. Sidebar's absolute content position follows its scroll model, while the scrollbar stays anchored in the viewport. Set `auto_measure_content` to measure ordinary laid-out children on enabled axes whose `content_width`/`content_height` is omitted (nonpositive or nonfinite). Explicit positive finite dimensions take precedence, including virtual content. The container retains the FIT content box extent through its stable owner ID and uses the preceding frame's layout for ranges, clamping, and scrollbar geometry. The first frame has zero range; additions, removals, and wrapped text changes update the range on the following frame. Width stays constrained to the viewport when only vertical measurement is enabled, so wrapped text contributes its laid-out height. Enable horizontal measurement for content that should fit its natural width. Out-of-flow absolute boxes and portals do not enlarge the FIT extent. The drawing-free base API continues to require explicit content dimensions. For low-level C compositions that need intrinsic first-frame sizing and current clamping, see [Core scroll-layout constraints](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SCROLL_LAYOUT.md). Those opt-in Core APIs leave this container and its previous-frame auto-measurement behavior unchanged; they are not new Dialog/Base/foreign-builder composition facades. --- ## Core intrinsic scroll-body layout Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SCROLL_LAYOUT.md # Core intrinsic scroll-body layout Development source only: these APIs were added after v0.1.0-alpha.3 and are absent from its published packages. Use matching headers and implementation. `cui_layout_scroll_body_v1` and `cui_layout_scroll_clamp_v1` are opt-in C Core constraints. Read their exact declarations in `include/cui/cui.h`. They do not change the existing Scrollable/Base/Dialog APIs or expose foreign-builder slots. Python, JavaScript, TypeScript, Go and Rust builder composition support remains future work; the C API does not establish full Dialog or component parity. ## Supported relationship A body registration names this exact current-frame chain, after all six boxes close: ```text Panel (fixed positive current width) Outer viewport (clip) Column (ordinary vertical flow, gaps and fixed siblings) Body frame (ordinary flow) Body viewport (absolute attachment, clip inherited from frame) Content (intrinsic flow or explicit content height) ``` Panel/Outer/Viewport each have exactly the named single flow child. Frame has no flow child; its attached viewport grows from the frame origin. Outer, Frame and Viewport have zero padding; Outer/Viewport align content from the top. Column is vertical and may contain headers, descriptions and footers alongside Frame. Compose these and all content once. The relationship allocates current intrinsic content height to the Body, capped by the panel's available height. No previous-frame extent or minimum readable spacer is used. AUTO chooses the smaller of natural demand and max_height, respecting min_height. EXPLICIT uses the validated requested_height. When fixed regions exceed the available height, the Body exposes its natural height and the whole column scrolls inside Outer. Both Y offsets clamp to the completed frame's ranges before final drawing, hits, semantics and caret geometry. Widths must be determined independently of the new Y allocation. Ordinary GROW children under a fixed/constrained ancestor are supported; every child need not have a literal fixed width. Hidden/overlay scrollbars preserve that width. Reserved-gutter feedback is outside V1. Core cannot infer an application's gutter policy; the caller must satisfy the width-independent contract. The adapter rejects aspect-ratio/percentage-height dependencies and foreign floating roots in the registered subtree, checks the stored-tree width fingerprint and final predicted ranges, and fails instead of iterating. Width independence comes from these structural constraints and stable provider/X inputs; equality of a 64-bit diagnostic fingerprint is not a proof of arbitrary constraint closure. This is not a general solver. Fixed-size absolute decorations, including caret boxes, may attach to their actual parent with inherited clipping. Canonical explicitly fixed-zero axes stay zero. Nested registered bodies solve inside-out. No portal/root fallback is inferred. Ordinary Core portals detach from their lexical parent and remain independent roots; they do not contribute intrinsic demand or inherit this clip relationship. The constraint does not certify or change those separate roots. A standalone clamp names a directly parented clipped viewport and its content, with a fixed positive viewport height. It changes Y translation only, preserves sizes and cannot contain a registered body. Standalone and body-owned identities cannot overlap. X/mixed axes are rejected, not ignored. The APIs create no semantic role or input handler: applications retain their existing behavior/scroll owners. For an existing matching scroll semantic, Core updates its completed range/value. Input routing continues to use the existing dispatch and preceding-frame geometry. ## Registration and ownership The 80-byte `cui_scroll_body_layout_v1` and 32-byte `cui_scroll_clamp_v1` records contain no pointers. Set struct_size to sizeof(record), version to CUI_SCROLL_LAYOUT_VERSION_1 and all reserved fields to zero. Heights and initial offsets must be finite; 0 <= min_height <= max_height and max_height > 0. AUTO requires requested_height = 0. EXPLICIT requires a positive request between min_height and max_height. Clamp axes must equal CUI_SCROLL_CLAMP_Y. ```c /* After composing/closing the six boxes, using stable application-owned IDs. */ cui_scroll_body_layout_v1 layout = { .struct_size = sizeof layout, .version = CUI_SCROLL_LAYOUT_VERSION_1, .mode = CUI_SCROLL_BODY_AUTO, .panel = panel_id, .outer_viewport = outer_id, .column = column_id, .body_frame = frame_id, .viewport = viewport_id, .content = content_id, .max_height = available_panel_height }; bool accepted = cui_layout_scroll_body_v1(ui, &layout, &model.outer_y, &model.body_y); ``` Records copy during registration and can leave scope. Borrowed writable floats must remain aligned, valid and stable through end_frame, including inside child callbacks. Distinct destinations cannot overlap each other, another constraint's destinations or retained tracked-bounds rectangles. Alias checks repeat after composition so later bounds registrations cannot evade the rule. Record storage may overlap a destination because its values have already copied; the destination itself must still outlive end_frame. Core cannot validate arbitrary C pointer lifetime. Register every frame; there are no persistent links or replacement semantics. Inert/layout-only ancestry receives effective geometry clamping without writing borrowed model scalars or publishing synthetic change events. At most 32 body links and 64 total clamps are accepted. Each body reserves two clamp slots atomically; standalone clamps use remaining slots. Repeated links, missing/ambiguous IDs, incorrect ancestry, open referenced boxes, conflicting identities and aliases reject the frame. No last-writer-wins or silent fallback. ## Errors and phase behavior Ordinary-composition registration opts the frame in even if it fails. Invalid records/topology report INVALID_ACTION; identity ambiguity reports DUPLICATE_ID; resource/link/clamp limits report CAPACITY; unresolved/unsupported final geometry reports LAYOUT. Wrong-phase calls retain existing lifecycle behavior and do not retroactively opt a frame in. The first sticky error remains until explicitly cleared. Clearing within a failed opt-in frame cannot salvage it: end_frame then reports LAYOUT if no earlier error remains, and returns an empty draw list. An erroneous opt-in frame has no valid draw, prepaint, tracked-bounds or semantic snapshot promise. Discarded trial geometry never reaches prepaint. All active borrowed offsets commit together only after every final constraint validates; failures before that commit preserve them. This transaction does not roll back application/input mutations or a successful commit followed by a later prepaint error. Clear the sticky error and rebuild on the next frame to recover. A frame with no opt-in attempt keeps the original layout, callbacks and error behavior. The adapter calls real Clay_EndLayout once, then one additional stored-tree calculation before Core prepaint/conversion. Public composition, input dispatch and prepaint do not repeat. Text measurement/shaping can repeat under their existing provider contracts. Vendored Clay is unchanged; the private adapter is pinned to the repository version and must be reviewed when that dependency moves. Storage is lazy within existing Core resource budgets: one 12856-byte payload on the measured LP64 build, plus an 8-byte opaque-context pointer even when idle and one shared immutable 16-byte failure header. The track extension adds 5640 bytes to the former 7216-byte layout payload, including for body/clamp-only opt-in users. Applications with exact custom resource-byte budgets must allow this increase. No public config or existing public struct grows. Other ABIs may have less padding; a compile-time 16 KiB payload bound and the same 32/64 capacities apply. No resource scan or extra calculation runs on a zero-opt-in legacy frame. Resource omission/collection follows the existing Core lifetime contract. Tests cover public APIs, fixed/narrow/wide/current-font, nested/empty/oversized regions, once-only callbacks, scroll/caret coherence, capacity/allocation failure, late aliases, context isolation and legacy behavior. ## Current-frame overlay track and thumb `cui_layout_scrollbar_track_v1` optionally attaches a real track and passive thumb to an already registered Y clamp. This C Core API does not install Base input handlers or add Dialog/binding composition. `cui_scrollbar_thumb_geometry` is the pure Core rectangle helper; the existing Base `cui_scrollbar_thumb_ex` forwards to it with the same ABI, normalization and arithmetic order. The copied pointer-free `cui_scrollbar_track_layout_v1` is 48 bytes: four uint32 fields (struct_size, version, flags, reserved), viewport/bar/thumb IDs at offsets 16/24/32 and thickness/minimum_thumb floats at 40/44. Use version 1, reserved zero, finite positive thickness/minimum_thumb and at most one track per clamp (64 total). The record may leave scope after registration. No new pointer lifetime is added; the clamp's distinct borrowed model float still lives through end_frame. Compose and close both named boxes before registering. Track must attach directly to viewport; thumb directly to track. Both are no-flow absolute boxes with inherited clipping, the parent's layer/focus scope, fixed width equal to thickness and fixed positive placeholder height (1 is sufficient). No padding, aspect ratio, maximum size caps or custom prepaint hook is admitted. Track has exactly one floating child (the passive thumb); neither has flow children. Their actual IDs must be distinct from registered structural identities, including folded collisions. No portal or row fallback is inferred. The active track semantic must be SCROLLBAR, vertical, with parent and controls equal to viewport; the thumb has no semantic. Under inert/layout-only ancestry the normally omitted semantics are accepted. Flags independently author VISIBLE (1) and INTERACTIVE (2); interactivity requires visibility. Visible disabled bars retain ordinary paint/shadows and a disabled semantic, with no capture/focus/input eligibility. INTERACTIVE is the authoritative bar enabled policy and may replace the submitted bar.disabled field (including a disabled range placeholder). To author a disabled bar, the caller MUST clear INTERACTIVE: bar.disabled alone does not override an explicit interactive request. Core cannot distinguish an arbitrary disabled bar field from a range placeholder. The track readonly flag, disabled/readonly owner or actual layout ancestors, inert and layout-only still exclude input. Callers must apply current eligibility before invoking their existing reducers; publication cannot retroactively undo earlier application/input mutations. Core does not provide a new dispatcher or replay events. Existing input uses the preceding completed hit snapshot; final current-frame paint/prepaint hits and published semantic geometry use the actual final boxes. Visible style and input policy remain caller owned. Hidden or zero-range tracks have zero effective height and no visible paint, shadow halo or published semantic. Alpha-zero commands may remain in the draw list. Inert ancestry keeps visible paint while suppressing semantics/input; layout-only suppresses paint and leaves model scalars untouched. Independent portals and existing modal eligibility retain their normal Core behavior. Before the existing second calculation, Core derives local Y-only track/thumb geometry from planned viewport height, range and staged offset. Width remains independent of Y; overlay bars reserve no gutter. Final real boxes, clipping, culling, paint/shadow identity and hit/semantic bounds then share one layout. All tracks validate before any borrowed offset commits; malformed records, aliases, unsupported topology, capacity and final failures invalidate the entire opt-in frame under the rules above. Register afresh next frame; omission/reuse retains no record or caller pointer. This adds no second resource, public config field or context pointer beyond the existing opt-in layout allocation. Tests compare 80000 direct-Core/Base results with a frozen independent legacy math oracle, and exercise current resize/shrink, shadows/clip/alpha, queued wheel, touch/drag, nested consumption, inert/layout-only/disabled/modal policies, record copying, aliases, resource/capacity failure and next-frame recovery. These are software/headless C oracles, not GPU, text raster or full component parity claims. Base page/key/CANCEL and full Dialog/Root/all-five facade composition remain separate followups. ## V2 source-style Content/Body peers and separate Footer `cui_layout_scroll_body_v2` is additive C Core, not Dialog/Base/facade composition. Its layout-record version2 is independent of draw ABI2/background negotiation. It works in ordinary `cui_begin_frame`/`cui_end_frame` frames with V1 draw lists, as the source/software oracles exercise. It requires no new renderer support and does not claim that a renderer supports draw ABI2. Read the144-byte `cui_scroll_body_layout_v2` and24-byte `cui_scroll_region_sizing_v1` in the same authoritative public header. The embedded base header is size144/version2; its height fields are the sole Panel sizing authority. Passing that record to the old V1 function is invalid. Existing V1 geometry, input, callbacks, memory allocation and resource slot budget remain. ```text Panel (fixed positive width; optional vertical padding/gap) Outer (clip, zero padding) Column (vertical, automatic gap0) fixed authored siblings / conditional fixed spacers Content region (optional, ordinary direct Column child) conditional fixed spacer only when Body is authored present BodyFrame -> attached clipped BodyViewport -> intrinsic BodyContent Footer (optional ordinary direct Panel child after Outer, fixed/FIT height) ``` All six internal base boxes remain, even for Body OMIT, and all referenced boxes must close before registration. Content ID0 iff its policy is OMIT. Footer0 means absent. Content must precede Frame; ordinary parent links, full/folded ID distinctness, inherited-clip floating rules and independent width restrictions remain. No row/root/portal fallback is inferred. Footer is the only optional second flow child of Panel. Column automatic gap must be0: explicit fixed spacer boxes between authored present regions preserve conditional omission exactly. Horizontal padding belongs in the content subtree; viewport zero-padding remains. FLEX1 has zero basis and shares available Y with the other FLEX1 peer, freezing against explicit/intrinsic minimum and maximum. It is not always equal halves. FIT takes clamped current intrinsic demand. FIXED takes finite positive requested height within min/max; FLEX1/FIT requested_height0. Non-OMIT min finite>=0, max finite>0, min<=max; use FLT_MAX for uncapped. Reserved0. OMIT is all-zero policy and receives0 allocation. For source Body omission, author an empty zero-height internal content subtree and no Body callback/semantic/input owner. An explicit empty FLEX1 Body remains a participating region and can receive positive height. Core does not infer omission from callback effects or remove caller semantics. AUTO is current intrinsic Panel demand, subject to its min/max; EXPLICIT is its validated height. Footer demand includes its actual children and retains that height outside Inner. Content minimum overflow is clipped by Inner; Outer range stays0. Oversized Footer can extend beyond Panel and is subject to ordinary ancestor/window clips, not a promise of full visibility or wheel reachability. There is no automatic whole-Outer scrolling exception. For example, the pinned independent engine/CUI software fixture with Panel260, padding16, gap16 and Footer400 gives Inner0 and FooterY32/bottom432. AUTO max600 with the short-body fixture fits Panel562 instead. This is geometry/software evidence, not upstream GPU raster or full Dialog input parity. Existing V1 reachable-Outer policy is unchanged. Public record/policies copy on registration; no caller record pointer is kept. Distinct aligned writable offsets and tracked bounds storage remain stable through end_frame. All shared32 bodies/64 clamps/64 tracks, late-alias checks, no-partial-commit and failed-frame recovery rules above apply. No third layout, application callback replay or new dispatcher. Text measurement may repeat. V1-only uses the EXACT existing base resource size/callback/key and one slot (LP6412856 bytes). V2 adds one2560-byte sidecar and one slot, shared across all V2 registrations: LP6415416 total, below16KiB. Other pointer-size targets retain their existing V1 base size plus the same2560 sidecar. No new opaque-context field, zero-opt-in allocation or resource scan. Cached slot access is checked and O(1); wrong/stale/missing V2 cache fails the opt-in frame, never falls back to V1. Sidecar/base collect independently at next begin. After V2 omission the sidecar retains the ordinary one-complete-frame resource history before destruction; this is explicit V2 history cost. Exact V1 byte/one-slot budgets still admit V1. V2 with one slot or one byte short fails ordinary CAPACITY, retains models, and can recover to V1 next frame after clearing the error. No public config grows. The28-row pinned Taffy reference is test-only/offline, not a CUI dependency. `dialog_flex_regions_native` and `_distribution` exercise public production APIs, software clip/overflow pixels, current prepaint/semantic/caret geometry, same-UI resize/omission and resource/alias/failure controls. Core V2 is a foundation; full Dialog slots/actions, Root/native-host and all five builders remain open. --- ## Unreleased SDL_Renderer V2 route Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SDL_V2.md # Unreleased SDL_Renderer V2 route Use matching development headers and implementation. The C SDL_Renderer adapter now has explicit `cui_sdl3_query_v2` and `cui_sdl3_render_v2` entry points in `cui/cui_sdl3.h`. The V1 renderer table and default render path stay unchanged. This is distinct from SDL_GPU; it does not add V2 foreign-language authoring, Canvas, Sokol or SDL_GPU support, or establish complete component styling parity. ## Opt in This fragment belongs inside an existing initialized CUI/SDL host frame loop; `backend`, `ui`, dimensions, `dt` and `clear` come from that host. Keep the same font provider for measurement and rendering. See [adapter setup](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/backends/sdl3/README.md) and [Core V2](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CORE_DRAW_V2.md) for the surrounding contracts. ```c cui_sdl3_v2_info info = {.size = sizeof(info)}; if (cui_sdl3_query_v2(backend, &info) != CUI_OK) return false; cui_frame_v2_options options = { .size = sizeof(options), .support = info.draw, .required_features = CUI_DRAW_V2_FEATURE_BACKGROUNDS }; if (!cui_begin_frame_v2(ui, logical_width, logical_height, dt, &options)) return false; /* Compose ordinary CUI elements; apply documented V2 backgrounds as needed. */ cui_draw_list_v2 list; if (!cui_end_frame_v2(ui, &list)) return false; return cui_sdl3_render_v2(backend, &list, clear, &info.defaults) == CUI_OK; ``` Query before composition and after resizing. Query is a snapshot, not a reservation; render checks current dimensions again. NULL render options choose fresh defaults. Explicit options require matching physical output dimensions and valid positive budgets no larger than queried limits. Defaults derive independent X/Y density from current logical/output dimensions. Never cast V2 commands to V1 or silently fall back after failed V2 admission. ## Painting and transfer The shared bounded CPU painter prepares the entire frame, including backgrounds, shadows, images, meshes and supported text. See [painting policy](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SOFTWARE_V2_PAINTING.md) for alpha, clipping, AREA shadows, gradients, text recording and precision. Composition and layout still run in full; this is not incremental repainting. Only the owned window backbuffer with supported sRGB output qualifies. HDR, texture targets and unsupported native formats are rejected. Prefer advertised RGBA32; BGRA32 uses an exact red/blue byte swap in the existing owned plane after painting. Green and alpha are preserved. No second CPU image or implicit SDL format conversion is used. Transfer uses a transient native texture, nearest sampling, white modulation, no blending, physical 1:1 drawing and checked flush. Query reports actual font/A8, contextual-text and tracking capability bits. Unsupported text/resource requests fail during preparation. It does not promise color fonts, every Unicode script, physical presentation or native codecs. ## Ownership, limits and failure Main thread only. Borrowed draw resources and the opaque font/provider graph must remain valid, stable and disjoint from the owner through synchronous return. Do not recursively render the same font. Owner APIs refuse while V2 is busy; void size/destroy calls are no-ops during dispatch, so retry destruction when idle. Counted transaction ceilings are 32 MiB CPU, 1 MiB metadata and 32 MiB each for texture/transfer, with the shared command, pixel and work limits. Dimensions are at most 16384 per side. A positive native maximum further restricts them; zero or an absent property means no reported native limit, not guaranteed allocation. Checked texture creation can still fail. Opaque SDL/driver/font allocations are outside these quotas. Inspect queried limits and the public header; ceilings are not simultaneous reservations and do not guarantee every 4K frame fits. Preparation failure frees transaction resources before native drawing. Once native submission starts, backbuffer effects cannot be rolled back. Logical presentation, scale, viewport, clip and color scale are restored after attempts; restoration failure faults the owner until idle destruction/recreation. Success means checked submission and a successful Present call, not physical display completion. ## Evidence and remaining acceptance Worker strict C11 compilation and two private-Xvfb tests pass, including actual SDL software BGRA upload/readback, independent channel/alpha checks, failure injection, reentry, restoration and immutable V1 compatibility. The root configured gate is tracked separately in validation receipts. Original failures are retained. Physical GPU, macOS/Windows runtime and broad installed-consumer acceptance remain separate. See [the reviewed contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SDL_V2_PUBLIC_ENTRY_CHECKPOINT.md) and [worker receipt](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/validation/sdl-v2-first-worker.json). --- ## Separator Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SEPARATOR.md # Separator `cui_separator_ex` composes a decorative horizontal or vertical one-pixel line. Use `cui_separator_defaults()` for a 160px horizontal solid line, then set the options for a dashed line, centered label or custom color. ```c #include void draw_login_divider(cui_context *ui, const cui_theme *theme) { cui_separator_options options = cui_separator_defaults(); options.length = 240; options.dashed = true; options.has_label = true; options.label = cui_string("Or continue with"); cui_separator_ex(ui, cui_id_from(ui, "login-divider"), theme, options); } ``` Dashes are 4px long with 2px gaps, starting at the beginning of the line and clipping the final dash to the explicit length. Set `vertical = true` to change the axis. The label sits at the center with the theme background behind it, muted text at 75% of the root font size, a root-font-sized line box, and horizontal/vertical padding of 8px/4px. `has_label` distinguishes no label from an explicitly empty label, which still paints the padded background. Labels and their background can extend past a short line. The default line uses the theme border. Set both `custom_color = true` and `color` to override it; explicit alpha zero remains transparent. Keep label bytes valid through renderer completion. There is no retained state, callback or keyboard stop: submit the separator in each frame where it should appear. Length zero selects 160px. Positive lengths up to 4096px are accepted. Negative/nonfinite/oversized lengths, missing label bytes, an invalid root font size or ID zero return false and submit nothing. Core retains its normal capacity-error behavior during valid submission. The length bound limits dashed geometry to at most 683 rectangles. The implementation follows the axis, color, 4/2 dash and padded-label contracts in the [frozen Separator source](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/crates/component/src/separator.rs). CUI takes an explicit resolved length rather than automatically inheriting the parent's full width/height. Arbitrary upstream style refinements and renderer-native dashed vector paths are not represented by this adapter; Core boxes provide explicit composition. The existing `cui_separator` preserves its earlier horizontal, unlabelled API and metrics. Headless tests check both axes and line styles, dash positions, themed centered labels including empty labels, and rejection without frame output. Separator is a reusable primitive; it does not add a 79th entry to the pinned component manifest. --- ## Settings Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SETTINGS.md # Settings Settings composes searchable pages, groups and editable fields with a resizable sidebar and a scrolling active page. It uses the existing Sidebar, Resizable, Switch, Checkbox, Input, NumberInput and Menu engines (with a legacy Select fallback). Custom callbacks can replace a field or an entire item, and receive the original page/group/item indices, size, layout and disabled state. ```c bool notifications = true; cui_setting_item items[] = {{ .title = {"Notifications", 13}, .kind = CUI_SETTING_SWITCH, .boolean = ¬ifications, .has_default = true, .default_boolean = false }}; cui_setting_group groups[] = {{ .title = {"General", 7}, .items = items, .count = 1 }}; cui_setting_page pages[] = {{ .title = {"Preferences", 11}, .icon = {"settings", 8}, .groups = groups, .count = 1 }}; cui_settings_page_state workspace[1]; cui_settings_state state; cui_settings_state_init(&state, workspace, 1, search_edit); cui_settings_options options = cui_settings_default(); options.width = 800; options.height = 500; /* Inside a frame: */ cui_settings_result result = cui_settings(ui, id, &theme, pages, 1, &state, options); ``` The caller owns descriptors, field values, editor handles and all state. Keep these alive through rendering; callbacks execute synchronously while building the frame. Use separate state for each Settings instance. The search editor is optional and must be single-line. Without it, `options.query` supplies a controlled filter. Search text is reduced before navigation and content, so text queued in the current frame filters both immediately. Editors and popup state must be initialized using their own module APIs. Text fields borrow an Input state; numeric fields borrow a Number state and editor; source dropdown fields borrow an initialized `cui_settings_dropdown_state`, persistent Menu state and scratch arrays, described below. Existing `popup` descriptors keep the Select fallback. Optional Switch state enables its existing retained motion. Filtering matches item titles, descriptions and keywords. Custom whole-item renderers match only keywords unless their `matches` hook supplies another policy. Page and group titles, group footers and title suffixes do not independently match. The default matcher folds ASCII case and preserves non-ASCII UTF-8 bytes; a host matching callback can provide Unicode lowercase matching. Filtered arrays retain original indices and IDs. A matching selected page/group remains selected; otherwise selection falls back to the first matching page and its page header. No-results filtering keeps selection but renders no stale page. Clearing search preserves the current selection. The sidebar starts at 250 pixels and resizes within 160–360 by default. Page trees start collapsed unless `default_open` is set. Groups become sidebar entries only when their titles exist and the page has more than one matching group. Page activation selects its header; group activation selects the group and reveals it after measurement. Layout switches to stacked items when the content panel is at most 480 pixels wide. A vertical item override also stacks that item. Text fields use 256 pixels horizontally; NumberInput uses the source 128 pixels. Both grow when stacked. Zero width defaults to 800; negative width grows using the previous measured bounds. Zero height uses a CUI fallback of 500 rather than an unconstrained host viewport. Medium is the default. Zero-initialized options select a page; set `default_group_selected` to select `default_group` initially. Switch, Checkbox, Input, NumberInput and dropdown triggers honor XS/S/M/L. Input and NumberInput frame heights are 20/24/32/44; the source Button trigger heights are 20/24/32/32. Text glyphs are centered inside their fixed line boxes. Settings forwards its size to custom callbacks. Source item typography uses 14-pixel labels, muted descriptions and centered 20-pixel Label line boxes (plain item descriptions use the inherited golden-ratio line height), scaled by `theme.font_size / 16`. Group surfaces support Normal, Fill and Outline, including a per-group override. Fill uses independently configurable `theme.group_box`; item titles use `theme.group_box_foreground`. Card padding is 16, item gap 16, title gap Normal16/card12 and footer gap 8 at that density. Footer callbacks receive a theme copy with small muted text defaults and render outside the surface. Disabled items paint at half opacity. Built-in controls receive disabled state; custom callbacks must honor `options.disabled` themselves. Reset appears only when the active page permits reset and a matching item is dirty. The icon uses the named Undo2 SVG and the theme asset provider. The reset icon has a delayed hover/focus tooltip using `reset_label`, with state retained in each page workspace; Escape suppresses it until hover/focus leaves. Reset applies to every matching reset-capable item, including disabled items and unchanged matching defaults. `has_default` enables typed defaults; custom dirty/reset hooks take precedence. `on_change` runs after a built-in mutation or successful reset. Number fields keep out-of-range draft text while the setting value is clamped to the configured bounds; blur commits the clamped draft. `cui_settings_reset_page` exposes the same filtered reset policy without rendering. Text reset replaces the whole range atomically, so undo restores the original text and selection. The state workspace capacity bounds page count to at most 4096. The current sidebar composition supports at most 256 groups per page; groups support at most 65,536 items, each with at most 4096 keywords. Invalid descriptors or nonfinite dimensions return `invalid`. Actual layout is also bounded by the core context capacity. Text edit errors are reported through `edit_error`. `cui_settings_part_id` provides deterministic IDs for headless routing; current navigation parts are page5/group6, field24, reset34 and search4. Resize and scroll controls use their owning modules' part-ID helpers. ## Checked Menu dropdown composition Use caller-owned, per-field workspace for the source outline Button and checked Menu: ```c cui_menu_entry menu_entries[3]; bool menu_checks[3]; cui_settings_dropdown_state menu_state; cui_settings_dropdown_init(&menu_state, popup_id, menu_entries, menu_checks, 3); /* On a dropdown item with three choices: */ item.dropdown_state = &menu_state; ``` All arrays and state remain alive across frames. Capacity must cover `choice_count`; missing arrays, an uninitialized popup or insufficient capacity returns `invalid` before rendering. Choice IDs remain globally unique Menu row IDs. The adapter reconstructs scratch descriptors and checks from the controlled `choice` each frame, reduces events once, then paints the selected label and ChevronDown SVG. The horizontal trigger fits its contents; a vertical trigger grows. The popup opens below the trigger aligned to its right edge, flips/clamps at the Settings viewport, uses source Medium 26-pixel Menu rows, skips disabled options during navigation and closes after activation. Selecting the current value closes without emitting a changed callback. External changes immediately update label and checks. Set `dropdown_scrollable` for the existing bounded wheel/touch-drag Menu window. `cui_menu_popup_paint` supports this composition for other custom triggers. Call the drawing-free `cui_base_menu_tree` once, paint the trigger independently, then call the popup painter with its anchor. The painter does not process events, submit a trigger or mutate action/check values; it registers visible popup row semantics and retains layout/window metrics. Settings uses the shared paint-only Button renderer to avoid duplicate registration. For old descriptors with only `item.popup`, the initialized Choice popup still renders the legacy Select. This fallback retains its prior list appearance and is not the source checked Menu. ## Remaining source gaps Oversized non-scrollable menus still use the bounded existing Menu window rather than the upstream unconstrained-height layout. The scrollable Menu window does not yet paint a source scrollbar. Tooltip overlay styling and slide/shared-tooltip grace motion remain those of the current Tooltip module. Numeric/string external settings are caller-controlled values/editors rather than retained getter/setter closures. String reset is one atomic range edit; undo restores both the original text and its pre-reset selection. This implementation renders every matching group rather than the upstream virtualized List. Extremely large pages should be bounded by application and core capacities. Grow-width layout and group jumps depend on prior measured geometry and can require another frame; filtering resets page scrolling. Arbitrary style refinements, Markdown descriptions, translated default labels and custom Icon objects are represented by callbacks or explicit strings rather than source object APIs. Named/path icons use the theme provider. These limitations remain explicit; this module does not establish complete upstream parity. --- ## Sidebar Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SIDEBAR.md # Sidebar The module follows the frozen upstream kit 0.7.1 `component/src/sidebar` family: Sidebar, SidebarHeader, SidebarFooter, SidebarGroup, SidebarMenu, SidebarMenuItem and SidebarToggleButton. There is no separate frozen base Sidebar; CUI separates its pure cache/motion model and event behavior from styled rendering. `cui_sidebar_state_init` attaches a caller-owned cache with capacity 1..1024. The cache and state must remain valid through `cui_end_frame`; they allocate no memory. Entries, menu descriptors and callbacks are borrowed for their render call. Each entry is a top-level virtual-list item with a unique wrapper ID, positive estimated height, revision, content callback and user pointer. Wrapper IDs must differ from the IDs of controls/components submitted by their callback. Cached fields are inspection-only. Change an entry revision when content outside the rendered range changes its height. Stable IDs retain measurements through reordering; changing list count resets scroll position, matching source list reset behavior. The virtual list renders the visible range plus 30% of host-window height on either side. Supply `viewport_height` for a sidebar inside a shorter pane; otherwise the sidebar height is the fallback. Unknown entries use declared estimates. Rendered entries receive actual measured heights after layout and schedule a follow-up frame only when retained bounds change. Tall custom entries can render their own inner virtual list. Header and footer stay outside the scrolling body; the body handles wheel, draggable scrollbar and scrollbar keyboard input through the existing Scroll primitives. First layout and changed header/footer/available extent use retained geometry for scroll metrics, then correct it in the measurement frame. The scrollbar's right edge follows parent layout immediately, including percentage widths. The application drives frames until `cui_needs_redraw` is false. Defaults are width 255, left side, expanded, Icon collapse mode and a 200ms cubic in-out transition. Icon collapse renders children at 48px immediately and animates only the surrounding clip width. Offcanvas renders at the expanded target width, clips/slides to 0, and removes children after the transition; their focus and activation remain available while closing, as in source. None ignores collapsed state. Left Offcanvas aligns the child to the end of its shrinking wrapper; right Offcanvas aligns it to the start. Icon mode reverses those alignments. Reopening during close cancels unmounting. Retargeting samples the current width to avoid discontinuities; the frozen source instead starts at the previous target. Reduced motion or duration 0 applies the target and unmount immediately. `now_seconds` is caller-owned; backward timestamps hold the last sample. There are no detached timers, and settled animation does not invalidate continuously. A negative width grows within its parent; `width_percent=true` uses a fraction in 0..1. These nonpixel widths skip width animation, matching source. Zero plain width means the 255px default. Height 0 fills the parent. `custom_box` supplies surface appearance; layout, collapse dimensions and padding remain controlled by Sidebar. Source clears root padding, so CUI does too. The default background, foreground, border and accent use the five Sidebar Theme tokens. The left side has a right border; the right side has a left border. Header/footer callbacks receive effective Icon-collapse state. The sidebar's outer header inset is top 12/horizontal 12 expanded,8 collapsed. Footer uses bottom 12/horizontal 12 expanded and top 8/horizontal 8/bottom 12 collapsed. Icon mode adds 8px between header/body/footer. `cui_sidebar_header` and `cui_sidebar_footer` provide the separate source 8px padded rounded hover/selected surface. Their content owns layout and decisions about hiding its labels. An optional `on_activate` is a pointer-only Group action for host dropdown/menu composition; it introduces no Tab stop. Descendant controls keep activation priority. Header/footer content gets a temporary Theme copy with `text` set to the inherited Sidebar foreground/accent foreground. Do not retain that pointer. `cui_sidebar_group` exposes a labelled Group and a 32px label row with font 12, horizontal 8 inset and 70% Sidebar foreground. Icon collapse omits that row. Group callbacks can compose `cui_sidebar_menu`; the menu uses 8px item gaps. Menu items expose TreeItem semantics with accessible-name override, controlled active selection, expanded/level/controls metadata, source 28px expanded rows, 8px padding/gap and rounded corners. Icon collapse centers the icon, omits label, suffix, caret and descendants, and preserves submenu state. Nested descriptors can retain their own collapsed flag; the top-level menu overrides it with the menu's collapsed argument, as in source. A submenu requires persistent `cui_sidebar_item_state`. `default_open` initializes it once when the item first has children. Removing and re-adding children retains that state. An optional `expanded` pointer supplies a controlled value; requests go to `on_expand` and the owner updates the pointed value. `click_to_open` takes precedence over `click_to_toggle`; neither is enabled by default. Row activation always invokes `on_activate`, while a caret toggles expansion without invoking the row callback. Validated queued activations are reduced in input order rather than collapsed to a single action. The source disabled flag suppresses only row activation and hover: the separate caret and suffix controls stay independently enabled. `disable_caret` is an explicit additional option. The submenu rule sits at 14px and children start at 25px, including its 1px border and 10px inset; children have 4px gaps and 2px vertical padding. For an account tree, retain one state per expandable account in your application struct. Initialize it to zero once, rather than resetting it in the frame loop: ```c typedef struct { cui_sidebar_item_state account; } mail_sidebar_state; void draw_accounts(cui_context *ui, const cui_theme *theme, mail_sidebar_state *state) { const cui_sidebar_menu_item folders[] = { {.id = cui_id_from(ui, "account/inbox"), .label = CUI_STR("Inbox"), .icon = CUI_STR("inbox")}, {.id = cui_id_from(ui, "account/archive"), .label = CUI_STR("Archive"), .icon = CUI_STR("archive")} }; const cui_sidebar_menu_item account = { .id = cui_id_from(ui, "account"), .label = CUI_STR("alice@example.com"), .state = &state->account, .default_open = true, .click_to_toggle = true, .children = folders, .child_count = sizeof folders / sizeof folders[0] }; cui_sidebar_menu(ui, cui_id_from(ui, "accounts"), theme, &account, 1, false); } ``` Add `on_activate` and `user` to folder descriptors to select a mailbox. Descriptor arrays may be rebuilt each frame; their state pointers must remain valid. Omitting `state` does not create context-owned expansion state. `CUI_STR("Inbox")` also works in a static descriptor initializer; runtime strings use `cui_string`. Named icons use the actual context-owned Icon resource helper; no text glyphs or rectangle placeholders represent them. The four panel toggle icons and ChevronRight are in the default embedded bundle. The caret is 16px and rotates 90 degrees when open. Menu named icons default 16px; `icon_content` supports an application-owned custom Icon/path/state/style. It receives the row foreground through the temporary Theme's `text`. `label_content` and `custom_label_box` bridge source label styling, with accessible text still supplied by the label or accessibility override. Suffix content gets the same inherited foreground. Callbacks own any further controls, loaders or persistent state they compose. The current text API does not expose font weight, so source active-item `font_medium` emphasis is represented by its accent colors, without fake bold. Collapsed icon items use the real delayed Tooltip primitive. Supply `tooltip_options.viewport` with the host viewport; the default side is Right, including a right-side Sidebar, as in source. Default open delay is 500ms. An item state is needed for this lifecycle; iconless items have no collapsed tooltip. `context` runs after the item and can compose the existing ContextMenu helper with application-owned menu state/actions. Header/footer host actions can open those menus or other popup components; the module does not invent a second menu manager. Popup helpers retain their own viewport/activation contracts. The toggle is a 24px Small ghost button with a 16px panel-left/right-open/close icon, controlled collapsed state and `on_change`. Supply an accessibility label: the source toggle has no implicit accessible name. Its owner updates the Sidebar's collapsed option. Ordinary Tab and Enter/Space activate item/caret controls in CUI; the source row only supplies pointer click behavior, so row keyboard activation is an explicit accessibility improvement. No invented roving arrow-key tree policy replaces the source's composition. Sidebar widths and row sizes follow source; it does not claim four selectable sizes where the frozen API has no Sizable interface. The browser gallery forwards pixel wheel deltas as precise CUI scroll events for Scrollable, Sidebar and VirtualList. Fractional deltas retain their distance rather than being multiplied by the widget's discrete wheel step. Native hosts can opt into the same contract with `cui_event.scroll_precise = true`; discrete wheel events continue to use the configured step. Sidebar's absolute content position follows its scroll model, while the scrollbar stays anchored in the viewport. --- ## Skeleton palette and fixed-size presentation Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SKELETON_PALETTE.md # Skeleton palette and fixed-size presentation Unreleased focused proof: strict native C11 and C/C++ headers, actual C38-preset oracle, software pixels, frozen compatibility/callback timing, and pinned WASM compilation passed. Responsive composition has a separate additive API; read [the responsive guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SKELETON_RESPONSIVE.md). Root strict integration build and 17 targeted private-Xvfb checks pass, including selective/umbrella distributions, C/C++ include orders and the actual 38-preset C oracle (four methods, zero skips). All 18 consumer-skill tests and canonical generated-file checks pass. This is not a whole-family, deployed-gallery or installed-package support claim. Include `cui/cui_skeleton_palette.h` for owned values and pure resolvers, and `cui/cui_content.h` for `cui_skeleton_with_palette`. The existing phase API and `cui_skeleton_ex` retain their prior behavior. None of their records grow. ```c cui_skeleton_palette palette; /* Explicit custom-theme fallback; never guesses a preset from theme bytes. */ if (!cui_skeleton_palette_from_theme(&theme, &palette)) return; /* Alternatively: explicit registry index, checked against existing preset count. */ if (!cui_skeleton_palette_preset_get(preset_index, &palette)) return; /* Application owns persistent state, separate for each independent placeholder. */ cui_skeleton_options options = cui_skeleton_options_default(); options.now_seconds = host_absolute_seconds; options.width = 180; options.height = 16; options.radius = 4; options.reduced_motion = application_reduced_motion; cui_loading_motion_result result; if (cui_skeleton_with_palette(ui, placeholder_id, &palette, &motion, options, &result)) { /* Schedule this absolute deadline in the SAME clock domain; zero means idle. */ next_wake_seconds = result.next_wake_seconds; } ``` The snippet belongs inside an existing admitted CUI frame; `motion` is initialized once to zero by the application, not recreated per frame. `theme`, clock, ID and host scheduling are application-owned. No new loader, clock or retained object. A palette is one owned RGBA8 color. `from_theme` copies `theme.secondary` exactly, including alpha0. Builtins use their actual CUI secondary token. `preset_get` uses the existing38-name preset order and pinned `skeleton.background`, falling back to raw source `secondary.background`. All four bytes are preserved. These are CUI encoded paint bytes, not a source floating shader/color-space identity guarantee. No global theme change or inference from preset-looking custom themes occurs. Custom color is simply `cui_skeleton_palette p = {{21,34,55,0}};`. Transparent color is authored, never an absent override. Source secondary multiplies alpha by .5; pulse opacity1→.5→1 then a single byte truncation matches existing ex. Parent opacity/clip remains the existing Core layer. Palette input is snapshotted before easing (unlike the preserved legacy ex post-callback theme read), and borrowed through submission only; copies need no source lifetime. Nulls/invalid index leave pure resolver output unchanged. Painter requires nonzero ID, positive finite dimensions<=4096, radius0..4096 and duration0..60 (zero uses2s). It reuses the existing bounded motion sampler: state/clock/easing rules and reduced motion behavior are unchanged. Failed prevalidation/sampling leaves state, result and paint unchanged; easing callback effects cannot be undone. State/result must not overlap inputs/each other. Submission success does not certify later layout, rendering or native/AT delivery. Caller checks the existing frame diagnostic. Omission keeps caller motion state; reset it explicitly to restart. This fixed-size API does not supply source full/fraction/flex root sizing or own-root Styled border/layout overrides; use the separate `cui_skeleton_present` route for those. Modern foreign options remain pending. Python, JS/TS, Go and Rust retain their existing legacy Skeleton constructors and timing; none exposes this new palette. Application-owned busy/status semantics remain as documented in [the semantic audit](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/ALERT_SKELETON_SEMANTICS_AUDIT.md). See [the parity checkpoint](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SKELETON_PARITY_CHECKPOINT.md) for remaining scope. Focused proof receipt: [skeleton-palette-first.json](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/validation/skeleton-palette-first.json). The initial omission test incorrectly assumed an animation started at zero; the corrected fixture preserves its actual first sample time. An initially skipped C-oracle method was corrected to check its optional dumper at runtime; the final run executed all four oracle methods with no skips. Logs retain both earlier failures/limitations rather than presenting those runs as complete proof. Integrated proof: [skeleton-palette-root.json](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/validation/skeleton-palette-root.json). --- ## Own-root responsive Skeleton presentation Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SKELETON_RESPONSIVE.md # Own-root responsive Skeleton presentation Unreleased focused proof: strict native C11, four C/C++ header-order consumers, real public responsive/contract tests, frozen legacy checks and pinned WASM compilation passed. Root strict/runtime/distribution acceptance also passes; modern five-binding authoring and publication remain pending. See the [worker receipt](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/validation/skeleton-responsive-first.json) and [root receipt](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/validation/skeleton-responsive-root.json). Include `cui/cui_skeleton_presentation.h`. This is a separate additive route; `cui_skeleton`, `cui_skeleton_ex` and `cui_skeleton_with_palette` are unchanged. ```c /* Persistent application-owned state, one per independent placeholder. */ cui_loading_motion motion = {0}; cui_skeleton_palette palette; /* In application setup: explicit custom-theme fallback, no preset inference. */ bool ready = cui_skeleton_palette_from_theme(&theme, &palette); /* In each admitted ordinary UI frame while loading: */ if (ready) { cui_skeleton_presentation p = cui_skeleton_presentation_default(); /* Default actual root: full parent width, height16, radius0, period2seconds. */ p.root.radius = 4; p.now_seconds = host_absolute_seconds; p.reduced_motion = application_reduced_motion; cui_loading_motion_result result; if (cui_skeleton_present(ui, placeholder_id, &palette, &motion, p, &result)) next_wake_seconds = result.next_wake_seconds; } ``` Setup and frame fragments are intentionally separated: do not reinitialize motion on each frame. For complete compilable authored Core composition, see [the public API fixture](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_skeleton_responsive.c), whose `main` creates the context/software renderer, composes and resizes the actual root, and exercises registered scrolling. [The contract fixture](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_skeleton_presentation_contract.c) contains real callback/config snapshots, grow/fraction/fixed sizing and failures. Build and run these examples headlessly from a configured repository: ```sh cmake --build build --target test_skeleton_responsive test_skeleton_presentation_contract python scripts/test_local.py --build-dir build -- -R '^skeleton_(responsive|presentation_contract)$' --output-on-failure ``` The painted own root receives `cui_box` layout directly. Defaults use percent width1, not a fixed160px child or a growing wrapper. Under a definite parent, set `p.root.width=.5f` for half width; choose grow with `width=-1,width_percent=false`, or fixed120 with `width=120,width_percent=false`. Core's existing fraction/fixed/ max precedence, explicit zero, FIT, padding, edges, corners, clip and offsets apply. No prior-frame bounds, input replay or second dispatcher. Full width under an unconstrained/FIT parent follows Core behavior; no implicit viewport-width guess. Height16 is a logical-pixel source default; application rem scaling is explicit. Source paint precedence is deliberate: 1. Start with the owned palette; secondary halves its alpha. 2. With `custom_background=true`, replace that base with `root.background` entirely, including alpha0. The custom replacement is unaffected by secondary. 3. After synchronous motion sampling, animation replaces root opacity. Caller `root.opacity` and `custom_opacity` are inactive, even with NaN/zero. Fade a group via its ancestor. Border and background both receive pulse and parent opacity. Presentation and palette values snapshot before custom easing. Userdata may mutate external application values; this call still paints its captured style. The callback runs once synchronously on admitted sampling and is never retained. Reduced motion skips easing and returns opacity1/no wake. Custom alpha0 never requests fallback. Encoded secondary alpha then Core root opacity may differ by one byte from the old fixed painter's single background-alpha truncation. This opt-in source-ordered route does not change or redefine old output. State and result are caller-owned disjoint writable objects; they must not overlap borrowed inputs. Invalid mandatory input/zero ID, duration or motion sampling fails without state/result/paint changes. Callback effects cannot be rolled back. Other root fields follow existing Core normalization. Success means component submission; inspect completed-frame diagnostics for later layout/capacity/render failures. Later Core errors do not undo state or callback effects. Submit during active ordinary composition, not from prepaint/input/easing callbacks into the same UI. Schedule the finite absolute `result.next_wake_seconds` in the same domain as `now_seconds`; zero is idle. Omission preserves motion state; reset to zero explicitly to restart. Layout-only/inert follows Core suppression, without implying motion rollback. Skeleton is decorative: applications own busy/status and content replacement. Registered Y bodies with fixed Skeleton height/full width passed the real public API first-frame/resize tests. Percentage HEIGHT remains rejected by existing registered scroll admission. A cleared diagnostic cannot make that failed geometry valid; rebuild a fresh healthy frame. No Core admission widening, GPU/browser/native accessibility or full Styled/platform parity is claimed. --- ## Typed Slider values and math (unreleased) Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SLIDER_MODEL_VALUES.md # Typed Slider values and math (unreleased) Include ``. This C-only slice implements owned value/domain records, validation, endpoint proposal constraints, visual mapping and state initialization. The separate [typed Base route](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BASE_SLIDER_MODEL.md), declared in ``, implements explicit-size UI submission and ordered requests/callbacks using these values. Styled typed presentation, bridge/binding APIs and native numeric accessibility delivery remain pending. The whole Slider family remains partial; the [typed model design](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SLIDER_MODEL_ABI_V1.md) describes those boundaries. Legacy float APIs are unchanged. ```c #include cui_slider_model_domain_v1 domain = {10, 1000, 5, CUI_SLIDER_MODEL_LOGARITHMIC, 0}; cui_slider_model_value_v1 confirmed = {CUI_SLIDER_MODEL_RANGE, 0, 100, 400}; cui_slider_model_value_v1 proposed; if (cui_slider_model_value_constrain_v1(domain, confirmed, CUI_SLIDER_MODEL_START, 453, &proposed)) { /* proposed.start is 400: the other endpoint limits the snapped proposal. Application acceptance is a separate decision; confirmed was not changed. */ } double fraction; cui_slider_model_to_fraction_v1(domain, confirmed.end, &fraction); cui_slider_model_state_v1 state; cui_slider_model_state_init_v1(sizeof state, &state); /* no UI/owner binding */ ``` All helpers are pure, allocation-free and synchronous. No context, theme, heap, callback or external lifetime is retained. Failed output-producing calls preserve all output bytes; inputs are passed by value, so output may alias original caller value storage. Domain/value nested records use exactly the named v1 schema; unknown tags and nonzero reserved fields reject. The state initializer alone has a versioned top-level record: exact sizeof(v1) is required, all bytes are initialized, version/size are set, active thumb is END and every other field is zero. State has no pointers. Pure helpers do not interpret capture/owner fields; the separate typed Base reducer owns their documented interaction lifecycle. SINGLE uses end only and ignores inactive start, including NaN; constrained output canonicalizes start to positive zero. RANGE requires two finite ordered endpoints inside the domain, never sorting or swapping. Current values need not lie on the step lattice. Domain requires finite minimum/maximum/step, minimum<=maximum, finite span and nonnegative step. Linear zero span is valid; logarithmic additionally requires 0 cui_slider_palette palette; if (cui_slider_palette_preset_get(0, &palette)) { /* Owned values for application inspection; no implicit paint mutation. */ bool valid = cui_slider_palette_valid(&palette); (void)valid; } ``` ## Sources and identity `cui_slider_palette_builtin_get` resolves four CUI skins (Light, Dark, High Contrast, Terminal). `cui_slider_palette_from_theme` uses any caller theme's `primary`, `on_primary`, `focus` as bar, solid thumb and ring. These are encoded sRGBA8 bytes: RGB uses the sRGB transfer decode, alpha remains straight. Other theme fields, including `dark`, do not infer source-preset identity. A custom Aurora-colored theme still produces a solid thumb. The 38 named presets use the same index/name order as `cui_theme_preset_get`, but resolve their original tokens independently of that byte-valued theme adaptation. Recognized `slider.background` falls back to resolved primary; the differently spelled `slider.bar.background` is ignored by the pinned source schema. Thumb falls back to primary foreground, ring to source base.blue. All pinned entries explicitly supply these fallback tokens. Source representative colors select the first stop when the token is a gradient. Aurora Light's thumb remains an owned LINEAR brush: 180 degrees, source projection, SRGB interpolation, stop positions 0/1, colors #FFFFFF and #F8FAFC. It is never flattened into a fallback byte color. ## Color and brush contract Colors are straight linear RGB and alpha in [0,1]. Hidden RGB survives alpha0. The source-HSLA constructor applies the pinned shader's normalized HSL formula, without sRGB transfer decoding or byte quantization. It bounds floating-point roundoff at unit-gamut edges; GPU-f32 bit identity is not promised. This is a different conversion from the encoded custom-theme byte constructor. SOLID validates only `solid`; inactive gradient fields may contain arbitrary values. LINEAR ignores `solid` and validates both owned stops, positions [0,1], angle [0,360], interpolation space and `CUI_SLIDER_BRUSH_SOURCE_038` projection. Equal/reversed positions retain their authored order; 360 aliases 0. SRGB means linear RGB to encoded sRGB, straight component interpolation, then transfer decode back to linear RGB; OKLAB means linear RGB to Oklab interpolation and back. Alpha interpolates independently; premultiplication follows evaluation. This differs from CSS premultiplied-stop interpolation. For a rectangle W,H, source projection uses d=(sin(angle),-cos(angle)), scales its Y by H/W when W>H, otherwise X by W/H, and computes `t=.5+dot(P-center,d)/(length(d)*(abs(dx)>abs(dy)?W:H))`. Stop positions then map and clamp that coordinate. This describes owned semantics for a future consumer; this slice implements no sampling, zero-size geometry handling or rendering. Constructed records zero inactive fields. Values contain no pointers, allocation, context, frame state or borrowed lifetime. Copies remain usable independently of the source theme. A valid value does not prove a currently painted part exists. Null outputs, invalid builtin/index (including SIZE_MAX) leave output untouched; invalid preset names are empty strings. Invalid source-HSLA inputs fail atomically. ## Evidence and scope Pinned source/schema/default/shader URLs, hashes and exact interpretation are in [the reviewed design](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SLIDER_PALETTE_VALUES.md) and [the whole-feature audit](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SLIDER_THEME_COMPLETION.md). The canonical raw palette SHA256 is `03de5a483daab83ed983495963a560d70f8ea7db3fd079bf4a69a4df0e2f77c0`. `generate_slider_palettes.py --check` verifies source pin, preset order and output freshness; unreviewed brush syntax fails rather than approximating it. `tests/unit/test_slider_palette.c` checks conversions, four builtins, custom identity, active/inactive validation and atomic failures. An independent oracle in `tests/test_slider_palette_oracle.py --probe PATH` parses pinned raw tokens without importing the generator and compares actual C values for all 38 entries, including every owned Aurora brush field. Selective and umbrella distribution fixtures check public-header implementation/linkage. These checks require no native window. All five focused tests passed under the private-display wrapper: pure C values, independent 38-preset runtime oracle, generation freshness, selective distribution and umbrella distribution. The build uses C11 with warnings treated as errors. --- ## Slider style values (unreleased) Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SLIDER_STYLE_VALUES.md # Slider style values (unreleased) Include `cui/cui_slider_style.h` for the pure C-only owned resolver. It has no context, allocation, callback or renderer dependency at runtime. Initialize the exact version1 record and choose a palette explicitly: ```c cui_slider_style_options_v1 options = { .version = 1, .struct_size = sizeof(cui_slider_style_options_v1), .layout = CUI_SLIDER_STYLE_PARENT, .rem = 16, .full_radius = 999 }; cui_slider_style_plan_v1 plan; if (cui_slider_palette_preset_get(0, &options.palette) && cui_slider_style_resolve_v1(&options, &plan)) { /* Owned values only: retain/copy plan, no frame/source lifetime required. */ } ``` `FIXED` requires positive finite length; `PARENT` ignores it and writes zero to `plan.length`. Parent sizing is a future presenter's composition policy, not a promise that every enclosing layout accepts it. The private source geometry path has ordinary-flow horizontal/vertical proof, including first-frame parent fill and resize; the registered Y-scroll validator still rejects the vertical path. The resolver does not validate a particular frame's layout admission. Rem sets hit cross extent1.5R, track .375R, outer thumb R and inner max(0,R−2). Padding1, axis offset−8, cross offset−5 and maximum pointer ring width3 are literal logical pixels. Do not replace the source offsets with half-thumb centering. The source vertical default120px must be selected explicitly for FIXED mode. Full radius0 expresses a square theme. Each active track-corner mask independently overrides its radius; fill/outer/inner keep full radius. Track uses bar alpha×.2 or×.4 when ACTIVE, outer uses×.5 and fill preserves bar alpha. DISABLED records visual omission policy while preserving these values and semantic geometry. There is no live activity detection or animation in this pure function. The entire input palette must be valid. Color override masks distinguish a transparent authored override from absence. Active overrides require finite linear RGB/alpha in[0,1]; inactive override bytes/corners are ignored. Unknown masks/modes/flags, nonzero reserved words, invalid version/size and invalid active fields reject without changing any output byte. The output is owned and contains no pointers; neither input nor output retains a palette/theme reference. The thumb is an owned `cui_background`, copied fieldwise without byte quantization. It preserves straight-linear hidden RGB at alpha0, source projection, interpolation space, angle, stop order/positions and independent alpha. Aurora Light stays a linear two-stop brush. A transparent solid override is deliberate and works even when the underlying preset thumb is a gradient. No byte representative, preset identity inference or gradient-to-solid fallback occurs. This is step2 toward a typed Styled presenter. The private Base seam changes no public Base ABI and public calls select the frozen NULL path. There is no public Styled widget, presentation state, spring, named decoration API, V1 conversion helper or new renderer/host support here. Current adapters do not advertise V2 background rendering; the value resolver does not make them support Aurora. Native numeric hosts and all five typed language builders also remain pending. For actual controlled Base interaction use the complete [example](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/slider_model_controlled.c) and [guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BASE_SLIDER_MODEL.md). --- ## Unreleased software V2 renderer Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SOFTWARE_V2.md # Unreleased software V2 renderer Development source only; use matching headers/implementation. The C software adapter has an explicit V2 query/render route in `cui/cui_software.h`; the V1 `cui_renderer` table and `cui_software_render` route remain unchanged. The separate unreleased C [SDL_Renderer route](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SDL_V2.md) uses the shared painter. SDL_GPU, Sokol GLCORE, Canvas wire and foreign authoring bindings remain pending. This does not establish all 78 component part/presentation coverage. Query the initialized target **before composition**, then use its actual support: ```c cui_software_v2_info info = {.size = sizeof(info)}; if (cui_software_query_v2(renderer, &info) != CUI_OK) return false; cui_frame_v2_options frame = {.size = sizeof(frame), .support = info.draw, .required_features = CUI_DRAW_V2_FEATURE_BACKGROUNDS}; if (!cui_begin_frame_v2(ui, logical_width, logical_height, dt, &frame)) return false; /* Submit ordinary boxes; cui_set_background/cui_element_set_background opt in. */ cui_draw_list_v2 list; if (!cui_end_frame_v2(ui, &list)) return false; return cui_software_render_v2(renderer, &list, clear, &info.defaults) == CUI_OK; ``` Do not cast V2 arrays to V1, fabricate consumer support, or fall back to V1 on an error. Query is an owned snapshot, not a reservation/token. Requery after resize; render independently checks current dimensions and limits. NULL render options select current defaults; explicit options require exact size/CENTER_V1 tag, matching target dimensions and positive ceilings no larger than queried ceilings. Independent scales range 1/65536..64, origins -1e6..1e6, viewport sides <= 16384. Default scale 1/origin 0; rendering transforms do not change logical input/layout. All ordinary V1 command kinds and owned solid/two-stop backgrounds are consumed in array order, with exact logical ancestor clips and straight RGBA8 source-over. Backgrounds use SRGBA8_CENTER_V1 once; shadows integrate unchanged quantized source profiles over the full physical pixel footprint (AREA), including partial support. This is CUI's documented policy, not a CSS exactness claim. Text uses owned GRAY256 coverage at q = max(1, scale_x, scale_y), q <= 64, and per-axis bilinear inverse-center sampling; exact integer isotropic phase preserves the native glyph grid. Gradients sample logical ink coordinates and alpha is truncated once. See [private painter details](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SOFTWARE_V2_PAINTING.md) for bounds/precision semantics. No intrinsic RGBA/color-font support or universal Unicode coverage is promised. `info.text_features` reports actual A8/font availability; CONTEXT additionally requires the compiled Bidi recorder; TRACKING requires letter-spacing capability. No-text/NULL-font rejects TEXT before reading its borrowed bytes. No-Bidi rejects contextual sources/spans before reading inactive raw text. Missing faces and unsupported bitmap modes fail before publication. Public scaled font APIs retain their separate <= 16 limit; the owned source recorder supports 64. Limits are ceilings, not simultaneous reservations: transaction CPU 32 MiB, metadata 1 MiB, texture/transfer 32 MiB each, aggregate background/shadow/glyph target rectangles 8M, background 4M each, shadow cells 1M/source taps 1M. Query commands are `min(16384, (CPU_limit - target_RGBA_bytes) / sizeof(cui_draw_command_v2), metadata_limit / sizeof(private_paint_descriptor))`; backgrounds = min(4096, commands). A target with no room for one command returns CAPACITY. Smaller explicit CPU/metadata recompute the count cap; final resource plans may still reject. The target's persistent pixels/font state are separate class 1; counted temporary payload/text blocks are class 2; opaque new FT/HB/Bidi/provider temporaries are class 3, outside these byte limits. Input/work ceilings do not bound opaque allocator bytes. Core composition storage is separate (default 16 MiB command/512 KiB owner/background). Query allocates nothing and leaves output unchanged on error. All active list, resource and transform validation, exact plans, background/shadow preparation and owned text recording precede scratch clear. Any failure leaves published target pixels unchanged, frees transaction blocks and allows retry; provider/font side effects cannot be rolled back. Known list/options/commands/text/context/span/stop/ image/mesh ranges are rejected when overlapping target pixels or renderer object. The whole opaque font graph/dependency storage must remain valid, stable and disjoint; that graph cannot be dynamically range-validated. All borrowed resources remain stable until synchronous return; copying commands does not deep-copy them. The constructor borrows the font and destroy never closes it. No concurrent or recursive rendering of the same font, including on another target. Busy V2 query/render returns LIFECYCLE; V1 render/resize returns false; void destroy is a no-op and must be retried after the active call. Read-only pixels/interface access remains valid. There are no retained V2 caches, uploads or asynchronous resources. The private guard grows the opaque renderer allocation by 8 bytes on measured native/WASM32 targets (one alignment unit); old field offsets, V1 function-table ABI, V1 allocation call counts and ordinary V1 pixels remain unchanged. --- ## Private transactional software painting Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SOFTWARE_V2_PAINTING.md # Private transactional software painting `backends/common/cui_cpu_v2_paint_internal.h` is the maintainer building block behind the explicit [public C software V2 entry](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SOFTWARE_V2.md). It has no V1 call site. The old `backends/software/cui_software_v2_*` private headers/names forward to the same implementation. Pure V1 bitmap/shape/mesh/shadow utilities remain unchanged; common headers temporarily include those private pure utilities without linking another adapter. The private owned-frame lifecycle below adds no SDL support. SDK source closures include `backends/common/`. It paints RECT, BORDER, IMAGE, MESH, explicit clips and owned BACKGROUND commands in array order at independent physical scales/origins. DROP/INSET shadows use bounded target-pixel AREA reconstruction of the unchanged source profile. The private with-font entry adds owned text recording and per-axis bilinear glyph reconstruction; the no-font wrapper still rejects TEXT before allocation. This does not complete any of the other four adapters, bindings or all78 parts. The private `cui_cpu_v2_frame_prepare` fully prepares and paints an unpublished, tightly packed RGBA image. A zero-initialized, address-stable frame owns its two workspace blocks and optional embedded counted text owner/session until release. Its control size is 120/808 bytes without/with text on measured native LP64, 64/412 on wasm32; the fixed guard is 2048 bytes. Request, bounded exclusion array, clip stack, scalar locals and dependency/compiler frames are additional stack storage, not heap-budget charges or a total stack bound. Prepare requires EMPTY and publishes READY only after the entire image is painted. It validates frame/request/owner and known source ranges before any control mutation or allocator callback. PREPARING and RELEASING reject nested prepare; release/init during either phase do nothing. READY release enters RELEASING before text/free callbacks and becomes EMPTY only after cleanup; copied live handles cannot release another handle's blocks. No operation clears the caller's owner-busy flag. Caller keeps borrowed inputs/font graphs stable through release, including cleanup callbacks. Failure before allocation preserves control bytes; failure after claiming preparation cleans to EMPTY without a partial READY view. No allocation/provider side effect is rolled back. The old target helper is prepare -> active-row copy -> release. It retains old signatures, allocation request/count/order, target padding, source exclusions and both target/optional enclosing-owner busy timing. An internal optional second busy pointer preserves that boundary without changing the measured request or frame layout; its scalar pointer and bounded exclusion entry add fixed local storage. Neither V1 rendering nor any public software ABI changes. See [the extraction checkpoint](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/CPU_V2_OWNED_FRAME_EXTRACTION.md). The private `cui_software_v2_paint(target,list,clear,options,allocate,release,user)` returns `cui_error`. The explicit target view supplies writable RGBA8 pixels, width/height, actual row stride/capacity and an initialized-false busy guard. Viewport must match nonzero target dimensions<=16384. Checked span is `(height-1)*stride+width*4`; rows/padding beyond those active bytes are untouched. Target pixels/view must be disjoint from list/options/command records and active bitmap/mesh resources and active text/paint/span bytes. Borrowed inputs, options and target fields stay stable through return, including allocation/release callbacks; callbacks cannot write published pixels. Reentrant paint on the same view rejects, including during free. The initialized software adapter owns an additional enclosing guard and its allocator; callers cannot fabricate public adapter support from this private helper. Whole-list active-field/clip/resource validation precedes allocation. A second bounded pass computes exact double logical clip intersections and outward float covers for shared background queries. The cover is culling only; each emitted physical center is checked against the exact original logical intersection. Copied command values, tightly packed scratch, background RGBA and shadow A8 planes charge CPU<=32MiB; aligned typed descriptors charge metadata<=1MiB. Aggregate prepared background plus shadow and glyph rectangle pixels<=8M (shadows additionally<=1M), per background<=4M, and packed background bytes also fit texture/transfer ceilings. Command copies do not own bitmap/mesh data. Exact nontext heap allocations are two distinct blocks (one for an empty list), with no retained capacity/cache or hidden V1 shadow allocation. Fixed bounded control stack (64 clips plus validator stack and scalar locals) is separate from these heap-allocation quotas; there is no total-stack/process/time guarantee. All background and shadow resources are prepared before clearing scratch. Shapes/images map each physical center back to logical coordinates, retaining original absolute binary64 near/far edges. Border far insets evaluate `(x+w)-right_edge` and `(y+h)-bottom_edge`; they never subtract a small inset from a huge float width. Clamped radius/edge values retain CUI rules, with double rationalized elliptical row arcs and left-inclusive/right-open horizontal spans. Logical circular corners become elliptical on unequal axes. Nearest image UVs use the closer absolute edge and compensated source-end addition before integer selection, preserving open source endpoints even for giant bounds or tiny source offsets/widths. Mesh XY projects in double per axis, while source ST stays unchanged; the existing top-left/curve-coverage triangle raster evaluates derivatives in physical space. Grayscale/tint/opacity and straight-byte source-over retain V1 byte arithmetic. V2 corrects admitted relative-float cancellation and uses the stated binary64 coverage/UV policy, so boundary pixels can intentionally differ from legacy float roundoff; this is not universal unit-scale pixel identity. V1 remains unchanged. The painter never groups/reorders commands or goes through logical-ceil images. Background covered cells blend their prepared CENTER_V1 bytes once, with no resampling or additional radius/opacity multiplication. The shared binary `cui_background_prepare_inside_internal` predicate skips uncovered cells at the same inverse center. This occupancy test distinguishes an uncovered corner from a covered alpha0 fill: uncovered pixels keep even hidden clear RGB; covered alpha0 onto alpha0 follows V1 canonical RGB0. Ancestor clip is applied once. Shadows use q=max(1,sx,sy) with reduced float source phases, the reviewed copied source geometry/kernel, and exact rectangular target-footprint overlap with byte-quantized source cells. The full footprint area remains the denominator when support clips source work. Layer alpha is rounded once after averaging source bytes; Core has already applied ancestor opacity. Hard ancestor clips use inverse pixel-center membership and do not shrink that footprint. Existing source radii/SDF/Gaussian/empty-hole rules are preserved, not fitted to an unsnapped reference or claimed CSS-exact. Output blends straight original RGB and prepared A8 once; outside-support cells skip, while inside alpha0 follows the existing canonicalizing blend. Source order remains unchanged. The entire transaction admits at most1,048,576 shadow rectangle cells and 1,048,576 source-cell evaluations, with no q reduction/fallback/cache. All plans are checked before kernel calls/allocations/pixel writes. CPU request is command copies + scratch RGBA + background RGBA + shadow A8. Metadata is existing per-command descriptors + checked alignment padding + copied shadow descriptors. Both exact requests fit the caller limits. Empty/transparent shadows are validated before skipping. The structural validator's shadow_bytes=0 is explicitly not a completed resource plan; the painter adds exact clipped A8/tap accounting. V1 raster-query allocation limits are not used to admit valid clipped large-q work. See [the transaction contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SOFTWARE_V2_SHADOW_TRANSACTION.md). The private `cui_software_v2_paint_with_font` additionally takes a borrowed font before allocator callbacks. It requires the actual text build; no-text builds reject TEXT without linking font dependencies. Actual contextual availability is checked separately from letter-spacing support. No-Bidi builds reject context (including empty non-NULL paragraphs), spans and tracking before borrowed reads. Font size<=4096 and line origins |x|,|y|<=1e6 are explicit V2 text limits. Text chooses q=max(1,sx,sy)<=64, shapes at logical size, and owns copied GRAY256 coverage at q. Each target center inverse-maps both axes independently; four source neighbors with zero outside the bitmap form bilinear coverage, rounded once. Positive-weight occupancy distinguishes zero coverage from a zero-weight halo. Solid uses selected command/cluster ink; resolved gradients sample logical coordinates. Alpha is ink.a*coverage/255 truncated once, then original source-over. Original command and callback glyph order stay intact; clips never alter weights. An aligned per-TEXT {first,last} range charges base metadata. A counted text owner receives the remaining CPU/metadata envelopes after exact base reservations. CUI shaping/layout/Bidi payloads, prefixes and glyph copies charge CPU; glyph records/prefixes charge metadata. Text frames have additional counted allocations, not the nontext two-block guarantee. Exact peaks are baseCPU+owner.cpu_peak and baseMetadata+owner.metadata_peak. Existing font runtime and newly opaque FT/HB/Sheen/provider work remain separate; no joint process-memory guarantee. All records, transformed covers and joint glyph-cell quotas are prepared before scratch clear. Session records release before base workspace, with busy held through every callback. Borrowed fonts, entire graphs/FT/HB storage and paint stops must stay stable and disjoint from target/workspace through return. No nested/concurrent rendering on the same font is allowed. The pointer-byte font overlap sentinel does not validate opaque graph allocation ranges; those are caller preconditions, unlike known active text/span/stop/image ranges checked explicitly. failure does not roll back dependency/provider side effects. Intrinsic RGBA/color-font glyph formats remain unsupported, distinct from span ink+A8. After complete preparation/painting, active scratch rows publish by memcpy once. Validation, budget or allocation failure leaves published bytes unchanged, releases acquired blocks and permits valid retry. This is pixel atomicity under the documented stable-input/allocator contract, not rollback of callback side effects. V1's structs, renderer object, allocations and output route are unchanged. Tests use independent scalar physical-center containment/UV/mesh/source-over formulas and the frozen original background sampler, plus the separately compiled immutable V1 software source for exact ordinary-only unit pixels. V1-only inactive bounds are canonicalized in its reference input, without changing active fields. Tests cover both gradient models/spaces, reversed SOURCE_038 stops, transparent stops/destination/hidden RGB, fractional unequal/extreme densities, nested clips, source order, padded targets, offscreen large extents, quotas, both allocation failures, malformed late commands, rejection/retry and callback reentrancy. Local receipt: focused test compiled strict C11 Release `-O3 -DNDEBUG -UNDEBUG -Wall -Wextra -Wpedantic -Werror` on CPU0/nice19, linking the preserved existing `build-shadow/libcui.a` SHA256 `96d40727c65d39de0accedf45edba34098a209ec41747bd05800d96362e1a137`. No engine archive was rebuilt or immutable expected output recaptured. New helper code is compiled into the focused test, with independently compiled frozen V1 software/sampler source. The first oracle run rejected inactive NaN bounds in V1; canonicalizing those inactive reference-only fields resolved it. Final private Xvfb checks passed4/4: new painter, existing validator, pure background preparation and frozen V1 current comparison. Installed-skill tests passed18/18; reference hashes2/2, clang-format23.1.2 and generated freshness passed. Integrator actual current-library CMake execution remains an independent gate; no native GPU proof. Precision regression receipt: the original075a60d4 helper SHA256 was `bb8c1d8c3b777207cff95cfa7f4cfcc5b73293092a5d10c974504bb598d9e55d`. Before modifying it, a strict O3 probe linked that helper and returned normal exit2 at the first hand-enumerated4x2 square case (x0,y0). The corrected helper passes eight tiny-target cases: negative1e8 X/Y, rounded corners, asymmetric right/bottom border insets, negative1e30 X and three source-cutout endpoint cases. Each case requests<2KiB per allocation; no giant raster is created. Additional nextafter left/right edges, inner-border endpoints and exact3-4-5 circle points verify horizontal half-open semantics. The expanded fixture, old-negative probe, validator, pure background preparation and preserved V1 compare passed5/5 under private Xvfb. All prior40 physical frames and frozen ordinary-unit fixture bytes still pass; an added tiny-offset UV expectation was corrected analytically to red at distance1.5/width and blue at .5/width around source integer1. The preserved old-negative executable SHA256 is `4fc87c0ba822e7d841295a7ca1dc51eea1c7cbfdeadc7a6e6387c60b0ef4dc5b`. Precision followup installed-skill tests passed18/18 in38.344s; final source format and canonical SDK/amalgamation/skill freshness checks passed. Private shadow checkpoint receipt: actual helper compilation links the integrator's current Effects-profile archive SHA256 `0535906e874ffda405e9c7b3cc0b0b2063b5bd0ef76e88294c236a38ada68f97`. Strict O3 and private-display checks passed3/3 in0.53s after correcting the mixed fixture to retain IMAGE alongside all other ordinary commands. The corrected 14-command fixture checks48 complete RGBA frames, plus8 large positive/negative source positions and3 exact/nextafter clip boundaries. An independent slow source-cell overlap oracle uses reviewed geometry and public pure Effects samples, without production plane/planning code. The actual private painter also matches4,608 frozen original-software unit pixels with layer alpha1/127/173, nonzero clear alpha, sigma0/positive and square/asymmetric corners. The separate 512-pixel legacy profile gate remains exact. No expected fixture was recaptured. Tests assert both allocation requests exactly for every interleaved background/A8 frame. A two-shadow example requests1,699 CPU bytes and720 metadata bytes for163 A8 cells/source evaluations. Exact/below tap, cell, joint prepared-pixel, CPU and metadata limits; first/second allocation failures; first/late private preparation failure; empty/transparent/invalid shadows; large-q visible work; reentrancy and retry all preserve the target/padding as specified. The preparation failure hook exists only as a private test instrumentation macro, with no public API/callback or default runtime behavior. See `docs/validation/software-v2-shadow-worker.json` for hashes/provenance. That shadow-only checkpoint preceded the now-supported public C software V2 entry and full transformed text described above; the other four adapters remain pending. --- ## Speech Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SPEECH.md # Speech The portable provider lifecycle, PCM level meter, SVG SpeechButton and waveform are implemented and tested. An optional SDL input-host example now implements the capture boundary with bounded PCM delivery; real-device operation and system recognizers remain unverified or unimplemented. The following audit records the frozen source contract and the remaining target. Reference: commit `87d10ae5e1299d1be18670a37570c5402f952e34`, `crates/component/src/speech/{state,recognizer,level,button,waveform,microphone}.rs`. The portable layer must model Idle, Connecting, Recording and Stopping. A session owns capture and recognition separately: start recognition first, then capture; stop capture before requesting recognition finish; tear down capture before recognition. Failed starts report an error and preserve the previous transcript. Every asynchronous delivery carries a session generation, and stale deliveries must be ignored. Synchronous provider callbacks must defer their changes until start/push/finish returns. Started precedes provider results. Partial replaces the current hypothesis; Phrase appends literally to committed text and clears the hypothesis. Final keeps the transcript, Cancel clears it, and session teardown clears waveform history. Stop defaults to a three-second timeout and returns the current transcript when it expires. Repeated start/stop/cancel calls must preserve their source no-op semantics. Providers consume interleaved signed 16-bit PCM, default 16 kHz mono. Recognition availability is distinct from provider presence. An active session stays stoppable if the provider becomes unavailable. Custom capture and recognizer providers are required APIs; platform microphone capture, resampling and system recognizers remain part of the complete target, not implied by a portable fake provider test. Windows system recognition may use an online service; explicit system fallback control must be preserved. Unsupported platforms must report unsupported without fabricating transcripts. The input meter retains 256 levels, one per 80 ms of audio, carrying partial intervals across pushes. RMS maps -50 dBFS to 0 and 0 dBFS to 1; mapped values below .06 are silence. Attack is .85 and release .3. The waveform clock follows arrivals with phase gain .1 and pace gain .01, bounded to .04–.16 seconds per level, lag 1.75 levels and maximum lead 3. It must remain stable across late/bunched audio deliveries and finite caller timestamps. SpeechButton is a ghost icon button: microphone at rest, selected stop square while capturing, spinner while Stopping. It hides without providers unless show-unsupported is enabled, then remains disabled. Sizes and accessible labels follow the existing Button APIs; use customizable SVG icons, never text substitutes. SpeechWaveform defaults to width 96 and heights 12/16/20/24. Its capsule width is rounded height/8, clamped 2–4; gap is rounded width times 2.5. Newest levels enter at the trailing edge, silence is a dot, short histories leave the leading edge empty. Clip partial bars and preserve subpixel movement; reduced motion disables between-level scrolling. Capturing uses the primary color, otherwise muted foreground. Required tests include provider start failure cleanup, synchronous callbacks during every lifecycle call, stale generation rejection, partial/phrase ordering, stop timeout and late final suppression, cancellation and transcript lifetime, PCM batching equivalence, RMS/smoothing thresholds, waveform clock/geometry, unsupported/unavailable button semantics, physical pointer and keyboard toggles, four sizes and reduced motion. Real platform capture/recognition needs separate platform evidence; model tests cannot establish it. ## Portable API and verified boundary Zero-initialize `cui_speech_state`, provide nonoverlapping caller-owned transcript, message and queue buffers in `cui_speech_workspace`, and call `cui_speech_init` with recognizer and input callbacks. Successful provider starts return non-null session tokens; `close` releases them. Failed starts may return a token for cleanup. All callbacks and reports run on one owner thread. Marshal background audio/recognition to that thread before reporting; these APIs are not a cross-thread queue. Keep state storage alive until every retained sink is retired. Provider sinks copy UTF-8 text and PCM into the bounded queue, including reports issued inside start/push/finish callbacks. `cui_speech_pump(state, now)` applies queued reports in order; call it when the host receives provider work and at the stopping deadline. One pump processes its initial queue length so a provider cannot recurse indefinitely. Queue overflow terminates an active session with Capacity; transcript overflow preserves the prior complete transcript. Malformed UTF-8 and stale-generation reports are rejected. Dispose invalidates sinks and preserves the generation counter across reinitialization. Completion listeners may start another session; disposal during pumping is ignored. Provider callbacks must only report through their sink, not invoke lifecycle functions. `cui_speech_button` uses existing themed SVG icon controls and four Button sizes. Localized start/stop/unavailable labels are accepted. `cui_speech_waveform` draws clipped capsule bars with floating-point positions, source size metrics, explicit dimensions/color and reduced-motion control. Both the per-waveform option and the Core host preference suppress continuous animation. Hosts own scheduling and call `cui_speech_pump`; rendering controls alone does not process asynchronous reports or implement a microphone. The provider-free button hides by default or renders disabled when requested. Tests cover lifecycle event order, PCM copying, synchronous callbacks, failed input cleanup, transcript preservation, stale delivery across both sessions and dispose/reinit, stop timeout, cancellation, reentrant completion/restart, bounded storage, UTF-8 rejection, meter batching/history/smoothing, waveform geometry/capacity, real SVG draw commands, four sizes, pointer activation, keyboard stopping despite provider unavailability, loading and unsupported semantics. Both standalone base and styled tests pass strict C11 and ASan/UBSan; the isolated worktree CTest run includes both new tests. Remaining parity work: real-device capture acceptance, platform recognizers and fallback policy, application event-loop/device-removal integration and automatic stop-deadline scheduling, button tooltip composition, inherited layout/style refinements, and live-device/browser verification. No fake transcript or deterministic provider test establishes any of these capabilities. ## Optional SDL input host The independently buildable [SDL input-host example](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/speech_sdl_input/README.md) supplies the existing input-provider interface. Its private SDL callback converts to requested signed interleaved PCM16 and writes a fixed-capacity C11 SPSC ring. The UI thread polls copied samples into CUI and pumps the existing Speech state. Audio callbacks never call CUI. Ring overflow and wake failure terminate the session explicitly; the bound covers host PCM storage, not SDL or operating-system buffers. ```sh cmake -S examples/speech_sdl_input -B /tmp/cui-speech-input-build -G Ninja cmake --build /tmp/cui-speech-input-build python scripts/test_local.py --build-dir /tmp/cui-speech-input-build ``` This requires CMake 3.20+, a C11 compiler, pkg-config and SDL3 development files (SDL >= 3.2). These commands run four offline Linux fixtures and never open a microphone. They test injected lifecycle/error handling, real unbound SDL conversion, intercepted SDL device operations and concurrent producer delivery. The example's CMake file records exact compiler and linker settings. It is an optional application-host example, not a new Core API or a built-in recognizer. For actual capture, the application supplies a recognizer and explicitly initializes SDL audio. See the example's integration section for start/poll/pump/shutdown ordering, timer and wake obligations, device-removal handling and OS permission limits. The host must outlive all provider callbacks; generation checks do not make reports safe after state storage is freed. macOS/Windows compilation, microphone hardware and recognition accuracy still require separate evidence. ## Optional macOS recognizer host The [macOS recognizer host guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/speech_macos_recognizer/README.md) provides a bounded C11 mailbox/lifetime layer and a private Objective-C Speech/AVFoundation transport. The C11 provider uses the existing Speech API; no platform types enter public headers. Actual Apple Debug/Release compilation and injected transport tests pass. It requires explicit application consent, on-device service availability and a separate PCM input provider. Live consent, microphone capture and recognition acceptance remain unverified. Windows/Linux system recognizers and full Speech family parity remain unfinished. --- ## Status components Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/STATUS_COMPONENTS.md # Status components Tag follows the frozen 0.7.1 Tag implementation: `cui_tag_options_default()` is secondary, medium, filled. Primary/danger/success/warning/info use semantic theme colors and readable foregrounds. Outline uses a transparent background and intent foreground. Secondary uses independent secondary/secondary_foreground theme tokens and muted outline text. Custom colors preserve all three application colors. Palette tags accept the exact 50/200/300/600/800/950 scale colors and explicit dark mode, so applications can supply their named palette without silently substituting a different palette. `cui_tag_named_palette` supplies all 21 named frozen palettes, including white and black, from the pinned default-colors.json six required scale colors. Small and extra-small use 10px text, 6px horizontal/2px vertical padding, and half theme radius; medium uses 12px text and 10px/4px padding; large uses 14px text. Typography scales with the theme font size (14px corresponds to a 16px root). Explicit radius zero is supported; pill rounding takes priority. Hover reduces paint alpha to 90 percent. Tags have no built-in click or keyboard action. `cui_tag` submits a passive label semantic and text. For arbitrary rich children, call `cui_begin_tag`, submit children using its returned style, then call `cui_end_tag` with the same ID/style. The style is a plain value owned by the caller; no callbacks or strings are retained. Begin failure must not be paired with end. The component style resolver allocates nothing and has no theme implementation function link dependency. Styled tags require core and status base defaults. Tag and Marker are implemented in this checkpoint. Marker accepts up to 32 ordered children: typed icon, typed text, rich content, and direct custom children. Callback IDs are reserved child IDs, not the enclosing slot ID. Callback/user/string lifetimes last through the render call. The retained `cui_marker_state` must remain alive through `cui_end_frame`, because tracked text bounds update after layout. Initialize it to zero. Explicit widths for custom children let separator/alignment geometry reserve their space; callback layouts remain application owned. Default width is 480; set it to the host container width. Plain and Border start-align by default; Separator centers. Explicit start/end alignment leaves only the divider on the opposite side. Border adds an 8px bottom inset and a single bottom edge. Typed icon slots suppress automatically inserted spinner loading; direct children do not. Typed text shimmer uses twelve nested clipped glyph overlays, matching the frozen source's twelve-layer feathered band. Relative spread defaults to 0.3 and clamps to 0.05–1; absolute spread clamps to at least 1px. Duration defaults to two seconds, with a minimum 1ms. Reverse and once are supported. The default highlight mixes 20% muted text with 80% of the light/dark theme endpoint in alpha-premultiplied Oklab. If the endpoint has similar HSL lightness, it switches to the opposite endpoint. Applications can override the highlight color. Rich-only content receives its 0.6–1 opacity pulse in the callback; apply it to that content's paint alpha. Direct children and icon slots receive opacity 1. Reduced motion paints static text and provides no animation wake deadline. The base plan returns the next absolute 60Hz host wake while animation runs; the host schedules and invalidates at that deadline. Passive Marker emits no semantic node by default; an explicit role/name creates a stable-ID node (for example Status). Status base now owns only theme-independent defaults/motion validation. Tag style resolution and palette choices live in components. Marker styled rendering adds existing `cui_content` spinner dependencies. The base links only math. Notification manager and rendering are implemented below. Text wrapping and inherited font refinements are bounded by the existing core text API; custom content can provide its own layout. ## Notification Initialize `cui_notification_state` with application-owned entry storage (1–128 entries), settings, and optional host hooks. Initialize each descriptor with `cui_notification_default`, assign a nonzero `{type,key}` ID, then push it with monotonic host seconds. Distinct keys can share an application type; exact-ID close and type-wide close are separate operations. Anonymous IDs are generated by the application. A repeated ID replaces its entry, moves it to newest, and restarts enter and timeout; replacement does not fire the old close callback. Capacity rejection and rejected host delivery leave the manager unchanged. Descriptors, strings, callback code, and callback users are borrowed. They remain valid while an entry is mounted, and while its system registry record remains registered. An auto-hidden in-app toast can still have an OS record, so its close callback does not by itself end these borrowed lifetimes. An explicit dismiss, clear, replacement, or registry aging ends the corresponding registry borrow. Do not initialize, push, or advance the same manager from a render callback; queue structural changes until `cui_end_frame` completes, so tracked retained bounds still refer to the same entries. Callbacks may request `cui_notification_dismiss`; action callbacks choose whether to dismiss. Custom rendering receives a reserved ID, font/color, and opacity; multiply custom paint alpha by that opacity. No callback or label is retained by core beyond its ordinary frame semantics. The pure base manager matches frozen lifecycle rules: 400ms enter, five seconds present for autohide, then 200ms exit. Each advance crosses at most one phase; excess time at a phase boundary is discarded. Present timers pause together when any stack is hovered or contains keyboard focus, including arbitrary custom children through core focus-scope ancestry. Enter/exit continue while paused. Window activity is not a pause input. Persistent-only settled stacks have no wake deadline. Close callbacks fire after exit removal, once. Manual dismissals remain mounted while ending; visible selection is the newest global `max_visible` active entries plus every ending entry. It is then grouped into separate stable stacks for all eight supported anchors. Render once per frame after application content with `cui_notifications`, a stable overlay ID, explicit viewport, and host seconds. Schedule the returned absolute wake deadline and invalidate at that deadline. Per-card placement can override global settings. Defaults are top right, width 382, ten visible active entries, margins 16, and top margin 48 (16 plus the reference 32px title bar); hosts without a title bar can set top margin 16. Auto height is measured through retained bounds and schedules a follow-up frame when it changes; fixed height is optional. Entry arrays and state must remain alive through frame end. Collapsed stacks show three layers, 14px peeks, and 5 percent width reduction per layer; expanded stacks use actual heights and 14px gaps. A taller rear card contributes to collapsed stack height. Stack height, item offset, width, and visibility use bounded critically damped springs with reference 400ms response, 0.1px geometry settling and 0.001 visibility settling. Enter/exit use the reference cubic Bezier curve and 16px directional slide. Reduced motion uses settled geometry and static transition paint while retaining lifecycle deadlines. Body clicks dismiss before calling the click handler. Close buttons appear on hover or expanded keyboard focus. Middle clicks require matching down/up inside the card; cancelled captures do not dismiss. Built-in action buttons keep their own focus and do not automatically dismiss. Titles, messages, custom content, custom action controls, typed intent icons and custom icon text compose together. Typed intent overrides custom icon, as in the reference. To use OS delivery, explicitly configure portable host `send`, `retract`, and `activate` callbacks and select System or Both delivery. No native OS adapters are provided by this module. A failed/missing send callback rejects the push. Host code owns OS availability, stable namespaced tags, activation, and cross-window ownership. Report OS responses through `cui_notification_system_click`; unknown or aged-out IDs are ignored. A separate registry retains the newest 100 system records, including records whose in-app toast auto-hid. Auto-hide does not retract OS delivery. Explicit exact/type/clear dismissal retracts it; response activates the host window, retracts, closes any in-app toast, and calls the click handler. Base status links only math; styled Notification additionally uses core, existing components buttons, content spinner, and status base. No allocation, platform, renderer, or default-theme implementation is required by the base. Renderer limits remain explicit: shadows are two bounded eight-layer rounded rect approximations of the reference blur/spread/offset, intent icons use portable text symbols and title font weight uses the current core font. Custom content can supply more specific icons/typography. Core text wrapping refinements remain limitations described above; this does not establish full native platform or renderer parity. Notification cards consume independent `theme.popover` and `theme.radius_lg` tokens for card fill, corners and shadow shape. Marker default highlight now uses the frozen perceptual blend and lightness fallback; exact custom highlight remains supported. Standalone Shimmer uses `cui_shimmer_text` with caller-owned retained bounds and `cui_shimmer_options_default`. It paints the unchanged base glyphs plus twelve clipped highlight layers, using the same alpha-aware perceptual highlight as Marker. Custom highlight alpha multiplies layer opacity. Duration, relative or absolute spread, reverse, once and reduced motion follow the frozen source; `cui_base_shimmer` returns the next absolute host deadline, or zero when settled. The host supplies elapsed animation seconds and schedules redraws. Explicit IDs allow identical sibling labels to animate independently. Font size/color may be set per instance; otherwise theme text styling is used. Optional maximum width clips the single line without changing glyph positions. Default Label semantics can be disabled with role None. State must live through `cui_end_frame`. Standalone Shimmer remains partial: inherited styled-text runs, wrapping, truncation/ellipsis and font weight depend on the future rich text pipeline. Reduced-motion text remains visible and settles without continuous redraw. --- ## Additive Stepper visual authoring through builders Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/STEPPER_BINDING_VISUAL_DESIGN.md # Additive Stepper visual authoring through builders The bridge keeps its existing selected Item and aggregate CHANGE event model. An opt-in `set_stepper_visual(enabled, vertical, density)` selects the existing C visual navigation renderer. Defaults remain the legacy renderer. Shared `design_size` becomes available on Stepper. Existing owned `image_rgba` storage also accepts Item children of Stepper as per-step icons; bytes are copied and replacement is transactional, bounded by the existing 16 MiB/2048-pixel limits. Removal follows existing node ownership teardown. No public C component, theme, state, or event architecture changes are required. The visual renderer receives a selected-index snapshot. Its requests are captured locally and reduced into the existing selected Item after rendering; the existing aggregate CHANGE is queued once only when the final requested selection differs. Applications observe the usual bridge dispatch phase, not C REQUEST callbacks. The opt-in frame paints the prior selection, and the next submission paints the accepted one. Legacy selection/render/callback behavior remains unchanged. Expose `stepper_visual` plus existing shared sizing and Item image methods through Python, JS/TS, Go and Rust builders. Density is md/xs/sm/lg, orientation is a bool; connectors belong to the current visual composition and have no independent foreign toggle. Keep the bridge's existing 64-Item limit (the C visual API allows 100). Missing icons use ordinals; XS hides icons/ordinals while still validating owned inputs. Existing Stepper disabled and Item disabled state applies. Verification covers legacy and visual mode switching, shared sizing/orientation, all densities, copied/replaced/removed icons, wrong-parent/invalid dimensions, public layout and software pixels, pointer/keyboard selection, same-selected suppression and exactly one CHANGE through the existing dispatch phase. Exercise actual headless language runtimes and compile TS authoring. Native tests use the private display wrapper; no desktop windows or dependency installation in offline policy tests. Update generated SDK sources and consumer skill resources. --- ## Application-controlled Stepper navigation Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/STEPPER_NAVIGATION.md # Application-controlled Stepper navigation Include `cui/cui_stepper_navigation.h` for `cui_stepper_navigation` and its unstyled Base sibling. They take a selected index by value and report a typed REQUEST for each accepted item activation. The application decides whether to update its own selection. The existing Stepper functions still mutate their selected-index pointer and the existing aggregate CHANGE observers retain their timing and meaning. This closes a specific frozen-source gap: upstream's controlled selected_index and on_click let the application decide navigation, including a click on the already selected step. Upstream has no built-in validator or next/back controller. The compiling [`examples/stepper_navigation/main.c`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/stepper_navigation/main.c) rejects a confirmation request while payment data is invalid, then accepts a later request after the application validates it. The callback receives captured `selected`, `requested` and `count`. A same-index activation is still a request. Several accepted activations produce several requests in event order, even when their final target equals the entry selection. All requests use the same captured selected value. The current call registers semantics and paints that captured selection throughout; owner updates become visible on the next submission. A rejected request simply leaves the owner's selection unchanged. There is no veto return, automatic selection, normalization, async validation, form ownership or automatic error-status mutation. `result.valid` means argument preflight succeeded, not completed layout or visible rendering. `request_count` counts accepted requests independently of a handler. A missing handler leaves selection untouched and still counts input. Preflight requires nonzero ID, count <=100, structurally valid title/description pairs and valid status enums. For nonempty steps selected must be in range; for empty steps it must be zero. Invalid input registers nothing and dispatches nothing. This is deliberately stricter than legacy clamping and upstream unchecked high indices; invalid-input equivalence is not claimed. Current semantics must successfully accept the activation. Current disabled or omitted items, cancellation, inert/layout-only work and rejected accessibility actions do not generate requests. Consumption follows Core's exact policy: consuming accessibility input cancels its acceptance; consuming an ordinary already generated Enter activation does not universally revoke it. This helper does not consume input. Each request freezes its genuine accepted activation snapshot before calling the application. Metadata targets the Stepper; the embedded activation targets its item. Frame, index and pointer/keyboard/ accessibility source are evidence, not inferred cause. Copied payloads remain usable after callback, frame and context lifetime. Handler/user, steps, strings and theme are borrowed through the call and never retained. Keep the borrowed array, strings and theme stable until return. The handler and by-value arguments are captured before callbacks. Store validation errors in separate owner fields, then rebuild step descriptors on the next submission; changing a borrowed status in a callback would mix old semantics with new paint and is unsupported. The example follows this owner pattern. The callback runs after current semantic registration and before styled painting. It may update unrelated application form/selection state. Do not mutate the borrowed descriptors or active input routing/options, recursively submit the component, destroy the UI/storage, or unwind a foreign exception. Updating the application owner cannot change this call's captured selection. Further callbacks still carry that captured value. Later mutation cannot rewrite a payload already delivered; future input acceptance is not promised to survive forbidden routing changes. Styled rendering reuses the legacy private paint path, including horizontal and vertical layout and explicit caller error/complete statuses. This legacy paint path does not add upstream icons, arbitrary children, sizing, checked separators, ListItem hierarchy or live AT announcements. The opt-in visual facade below adds a bounded connector/icon composition. There is no Python/Node/TypeScript/Go/Rust binding surface for these requests yet. Source and platform parity remain partial. ## Opt-in connectors and custom icons Include `cui/cui_stepper_visual.h` and call `cui_stepper_visual_navigation` to choose non-centered indicator/connector composition. The legacy functions above keep their previous button/status rendering and callback timing. This facade calls the same Base request reducer once; selection remains application-owned. It has no loading state. Decorations add no focusable or semantic targets. ```c #include "cui/cui_stepper_visual.h" void draw_steps(cui_context *ui, const cui_theme *theme, size_t selected, cui_stepper_navigation_handler handler) { const cui_step steps[] = { {.title = CUI_STR("Start")}, {.title = CUI_STR("Review"), .description = CUI_STR("Check details")}, {.title = CUI_STR("Finish")} }; (void)cui_stepper_visual_navigation(ui, 100, theme, steps, 3, selected, (cui_stepper_visual_options){.density = CUI_STEPPER_DENSITY_MD}, handler); } ``` Density selects indicator diameters8/18/24/32 for XS/SM/MD/LG and connector thickness1.5/2/2/3. A separator follows each item except the last. Passed connectors use primary when their index is less than selected; passed/current indicators use primary even when disabled. Caller COMPLETE/ERROR statuses do not determine passed color. ERROR retains a visible CUI-specific label. Other explicit status labels remain available through legacy rendering, not this source-style facade. Source pixels, theme sizes and general style refinements are not identical. To replace ordinals, pass an array of `cui_stepper_icon` with exactly one entry per step. Set `present` and a valid `cui_bitmap` on entries to replace. Unset entries use their ordinal. XS suppresses both icon and ordinal, but still validates all present bitmaps. Existing Icon state can rasterize an SVG before submission; the facade does not load/rasterize assets. Icons use foreground tint multiplied by source RGB and preserve source alpha; use white RGB for a monochrome alpha mask. All images are straight-alpha RGBA8 under `cui_bitmap_valid`: nonnull pixels, nonzero dimensions<=16384, stride>=width*4, and height*stride without overflow. This cannot validate the caller's allocation length; provide that full storage. Options, descriptor arrays, strings and theme are borrowed through return and must stay stable during callbacks. Bitmap metadata is copied into draw commands; no stack icon-descriptor pointer is retained. **Pixel bytes must remain valid through renderer completion**, and revision must change when they change. Invalid icons/count/density fail before semantic registration or callbacks. `valid` is argument preflight, not completed layout/resource-capacity or visibility proof. The returned request count and callback restrictions match the existing API. In this original visual entry, centered text/separators, responsive flex growth, arbitrary child content/style, exact source density and language builders remain unfinished. Follow-up slices should add independently tested centered geometry and then further theme/style controls without changing the request reducer. Native software tests cover this bounded composition and actual pointer/touch/keyboard requests. The WASM gallery fixture additionally covers desktop DPR1/2 and touch390 DPR2 for the bounded visual facade. Live assistive-technology acceptance remains untested. `options.design_size` accepts the existing shared XS/SM/BASE/MD/LG/XL/2XL..9XL scale. INHERIT (zero) leaves the source-density dimensions above unchanged. Explicit design sizing resolves shared metrics at `theme->font_size / 16`: source indicator diameter, separator thickness and connector lengths scale by `metrics.indicator_size / 16`; labels use shared font size and spacing uses shared gap. Thus `density` selects source proportions/suppression while `design_size` selects the app's shared scale. All tokens are tested, including9XL; invalid tokens or invalid resolved density fail before semantics/callbacks. These metrics do not claim frozen upstream pixel fidelity or responsive/centered layout completion. ## WASM gallery The Stepper story defaults to its original legacy button rendering and controlled validation demo. "Rendering" opts into indicators/connectors. Orientation applies to both renderers; source density, optional application-owned RGBA bitmap icons and shared design scale appear only for visual rendering. "Source density" in the design control keeps INHERIT; other choices use the public shared XS..9XL metrics. These are independent from the source-density proportions. Leaving the story hides and resets its controls; selection/validation remain application-owned. The Details confirmed checkbox gates later steps. Rejected requests still count; the current step stays unchanged. Same-index requests count too. Disabling the story suppresses interaction without erasing progress. The displayed module snippet tracks the chosen API/options and includes the controlled owner callback; the icon variant includes real static RGBA bytes with renderer-safe lifetime. The application must set `owner.confirmed` from its form before submission. `tests/web/test_stepper_visual_gallery.py` verifies actual WASM mouse, touch and keyboard requests, rejection/disabled behavior, connector geometry and Canvas pixel composites at DPR1/2 (including fractional strokes), image alpha/tint, source-density glyph suppression, one explicit shared design token and route reset. It compiles the exact displayed C snippets with strict C11 warnings. Desktop checks include both axes; touch390 uses vertical composition. Centered layout, automatic responsive flex growth, arbitrary styling and exact source pixel fidelity remain unfinished. The gallery does not establish live AT parity. ## Foreign builder visual authoring Python/JS/TS, Go and Rust now expose the existing non-centered visual composition through an opt-in builder method; see [binding builders](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BINDING_BUILDERS.md). They keep the legacy bridge selected Item and aggregate CHANGE model rather than exporting controlled C REQUEST callbacks. Icons are copied from owned RGBA bytes; bridge groups remain bounded at 64 Items. Examples are [`stepper_visual.py`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/python/examples/stepper_visual.py), [`stepper_visual.cjs`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/node/examples/stepper_visual.cjs), [`stepper_visual.ts`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/typescript/examples/stepper_visual.ts), [Go](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/go/examples/stepper_visual/main.go) and [Rust](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/rust/examples/stepper_visual.rs). ## Opt-in fill and indicator interaction Include `cui/cui_stepper_presentation.h` and call `cui_stepper_present` for non-centered fill layout and source-like indicator feedback. Existing navigation and visual APIs retain their pixels and ABI. For example, inside a growing parent: ```c cui_stepper_navigation_result result = cui_stepper_present( ui, id, theme, steps, count, selected, (cui_stepper_visual_options){.design_size = CUI_DESIGN_LG}, (cui_stepper_presentation_options){.layout = CUI_STEPPER_LAYOUT_FILL}, handler); ``` Width0 grows to parent available width; a positive width fixes that extent. Height0 stays intrinsic, including vertical layout; a positive height supplies an explicit vertical extent. The first non-last items grow; the last stays intrinsic. Horizontal fill centers unequal-height items on the root cross axis. Trigger buttons themselves stay intrinsic. Connectors are decorative zero-flow underlays inside their own items, clamped empty when space is insufficient. `CUI_STEPPER_LAYOUT_CONTENT` retains fixed spacer geometry and requires zero extents. Neither mode offers centered crossing connectors. All shared XS..9XL design sizes remain available; density selects source proportions. Intrinsic labels can still overflow an insufficient parent: no wrapping/compression parity is claimed. Calling the new entry opts into secondary/secondary_hover/secondary_foreground unchecked indicators and theme-radius behavior (zero radius makes square indicators). The pressed default is CUI's secondary **button** active color; upstream's global secondary_active can differ. Set `custom_palette=true` and all four palette fields to supply an exact application palette. Checked primary/on_primary wins even when disabled. No focus ring is added. Exact source typography and implicit engine active-state behavior remain partial. Only the indicator's currently visible, clipped, unoccluded area shows hover. Pressed feedback observes accepted trigger capture: pointer capture while visibly over the indicator, or Space capture regardless of pointer position. Label-origin press dragged onto the indicator follows that CUI policy too; this does not claim upstream drag/keyboard equivalence. Disabled/inert/occluded indicators suppress pointer feedback; decoration creates no new focusable targets or activation callbacks. Existing request ordering and owner-validation rules still apply, exactly once. Callback owner updates affect the next submission; selection/configuration used for painting are captured by value. Do not mutate borrowed steps/theme/icon arrays inside callbacks. Arrays are borrowed through return, bitmap bytes through renderer completion. No new retained application state is required. Language builders do not expose this typed presentation API; use a C-authored UI for these options. --- ## Typed Styled Slider (unreleased, C only) Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/STYLED_SLIDER_MODEL.md # Typed Styled Slider (unreleased, C only) Include `cui/cui_styled_slider_model.h`. This additive facade uses the existing controlled [Base model](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BASE_SLIDER_MODEL.md) and the owned [style resolver](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SLIDER_STYLE_VALUES.md). Legacy float/double Slider APIs and all old records remain unchanged. Full family closure is still open: visible Aurora Light gradients need actual V2 adapters, vertical registered-scroll layout is still rejected and native numeric hosts remain pending; the [Python controlled bridge subset](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PYTHON_SLIDER_MODEL.md) is available unreleased. Start with the complete, windowless [controlled application](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/styled_slider_model_controlled.c). It contains real application storage, checked init/default construction, callback, composition and main; accepts two ordered key proposals externally, demonstrates actual hover motion and advances the Core clock to a settled idle deadline. Reuse callback and compose in your own native/browser host. This example does not create a window, install a renderer or expose the direct C style/motion structs through bindings. The separate Python and Node/TypeScript bridge subsets use their own owned records and narrower options. From the repository root, with a C11 compiler, CMake≥3.20, Ninja and Python3 ([dependency guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DEPENDENCIES.md)), build and run only this example: ```sh cmake -S . -B build -G Ninja -DCUI_BUILD_NATIVE=OFF cmake --build build --target test_styled_slider_example --parallel 1 ./build/test_styled_slider_example ``` On Windows the Ninja executable has the `.exe` suffix. Expected output is `Selection [0.250, 0.500]; accepted 2 requests`. It is windowless, so direct execution is safe; other native automated tests still use the private-display `python scripts/test_local.py --build-dir build` wrapper. Native dependencies, a font and a display are unnecessary for this target. ```c cui_theme theme = cui_theme_light(); cui_styled_slider_model_options_v1 style; cui_styled_slider_model_state_v1 presentation; if (!cui_styled_slider_model_options_from_theme_v1( &theme, 16, CUI_SLIDER_MODEL_HORIZONTAL, &style) || !cui_styled_slider_model_state_init_v1(sizeof presentation, &presentation)) { /* Application handles invalid construction. */ } ``` The constructor copies custom-theme palette values (no preset inference), full radius0 for a square theme or9999 otherwise, and spring_control. Horizontal defaults to parent fill; vertical to fixed120px. The axis argument selects defaults only; the existing Base options remain orientation authority. Rem16 gives a24px hit cross extent,6px track,16px outer thumb and14px inner surface. Padding1, axis offset−8, cross offset−5 and maximum pointer-ring width3 are literal pixels. They deliberately remain uncentered at other rem values. Select a named palette explicitly with `cui_slider_palette_preset_get`; do not infer it from theme bytes. Options and presentation state are owned, pointer-free exact version1/sizeof records. Wrong tags/sizes, unknown flags/masks, nonzero reserved words or invalid active values reject before input/state/UI/callbacks. Nested style.flags must be0: the facade derives ACTIVE from admitted own drag and DISABLED from Base options. The independent pure resolver still accepts explicitly authored style flags. Inactive fields follow their respective style/support contracts. Spring response and damping are finite/nonnegative, epsilon finite/positive; travel=false or response0 snaps. Initialize reducer state separately with its existing helper. Reinitialize both states when recreating a context; IDs and frame counts are local. The existing Base handler is synchronous and retains all original-order typed Single/Range/double/domain/input evidence. It never accepts owner values for you. `current` stays the entry snapshot; `requested` intent evolves across events. Callback/userdata may update external owner state and enqueue application work, but must not mutate active UI/reducer/presentation/options/string storage or recursively submit. Paint uses ongoing drag preview and otherwise confirmed entry; external acceptance appears on the next submission. CANCEL may carry an old kind/domain and must not be blindly accepted. Styled does not change Base's pointer-down proposal, keyboard, touch cancellation or request-phase policies; source behavior exceptions remain in the linked Base contracts. `cui_styled_slider_model_part_id_v1(owner, thumb, part)` returns pure identity for SURFACE, POINTER_RING or FOCUS_RING, deriving through the Base thumb helper. Root/track/fill/outer thumb IDs keep the existing Base getter. Nonzero identity does not establish presence: Single omits START, disabled omits visual thumb children, zero inner extent omits surface, zero pointer-ring width omits its box, and unfocused/hidden focus omits focus decoration. Decorative boxes add no semantics, capture or input consumption. Track corners can override independently; fill/outer/inner retain full radius. Disabled keeps transparent outer semantic geometry, while track/fill preserve their palette. Readonly/handlerless/zero-span retain visible thumb and eligible hover/focus but never fabricate drag proposals. Actual clipped/occluded prior-thumb hover or the final admitted logical own drag retargets its interruptible pointer-ring spring. Track hover alone does not. Same batch up/cancel cannot leave pressed stuck. Visible progress clamps to[0,1] while internal motion can overshoot. The ring is a fractional outward border of width3p; its alpha is REPLACED by .5p, not multiplied by authored ring alpha. Core applies ancestor opacity once. Existing Core truncates the resulting alpha byte after that multiplication; the facade does not apply or round it again. Keyboard-visible focus gets a separate2px border with2px gap, using the authored ring alpha; HIDE_FOCUS suppresses it. It does not animate the pointer ring. REDUCED_MOTION or Core reduced motion snaps motion to target. Scheduling uses `result.next_wake_seconds`, an absolute accumulated Core clock deadline, zero when idle. Wait until that deadline in your host's frame scheduler and supply actual elapsed dt to the next begin. The facade does not spin an unconditional invalidate loop. Only use draw/deadline after successful end_frame. Initial geometry, inert/layout-only, modal-blocked or recovery-only calls return no wake and do not advance presentation state. Sequence0 is never converted to an invented generation. Omission/owner/recovery gaps reset cold; Single clears START, which initializes cold on returning to Range. Admitted disabled calls reset cold; nonadmitted calls preserve state. Clock reversal never integrates negatively. SOLID_V1 encodes straight-linear RGB to sRGBA8 with independent half-up alpha quantization. Visible LINEAR thumbs return UNSUPPORTED before Base submission, state changes, input consumption or callbacks. An explicitly masked solid override is allowed, including transparent. Disabled/layout-only/zero-inner-area geometry needs no invisible gradient rendering. No gradient is flattened to a byte color. BACKGROUND_V2 requires a copied declaration from an actual initialized consumer queried before begin and a matching feature-admitted Core V2 frame. The facade checks known size/ABI/output/features/budgets, then uses the checked Core setter inside each inner surface. It cannot inspect remaining frame capacity or verify a host's claim through a fictional Core capability query. Current software/SDL/ GPU/Sokol/Canvas adapters do not support this transport; tests with fabricated support prove Core transport only. A lying host or later capacity/layout/renderer failure can occur after callbacks: no already delivered request/input/owner effect is rolled back. CORE_FAILURE returns no wake and does not publish staged motion; a later end failure cannot roll back earlier state. Rebuild from a healthy frame. ## Browser gallery authoring The Slider gallery uses this controlled facade for Single/Range, horizontal or vertical, reverse and linear/log input. The owner policy control explicitly accepts or rejects UPDATE proposals; the preview shows confirmed owner and copied current/requested/phase. Mode/domain/axis changes synchronize the demo owner, retain the reducer for captured CANCEL delivery and reset only presentation. CANCEL is not blindly accepted. Progress retains its independent legacy route. The copy panel is a complete C initialization/callback/composition example: `web/modules/slider_usage.js`. Keep the application record across frames, render the completed draw list, then schedule its absolute Core-clock deadline. The browser maps that deadline to its monotonic host clock and coalesces it with other wakes; reduced motion and settled state return zero. No manual animation loop is required. V1 reports unsupported only when actual resolved visible paint is linear; a theme name alone never selects gradient capability. This gallery migration does not implement native numeric delivery, V2 gradient adapters or vertical registered-scroll admission. The separate Python and Node/TypeScript bridge subsets do not expose arbitrary C Styled style/state objects. The [Rust subset](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/RUST_SLIDER_MODEL.md) uses copied bridge records with the same limitation; dynamic and matching bundled-static Linux1.99.1 checks passed, with MSRV1.85.1 pending. The separate [Node/TypeScript bridge-owned controlled subset](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NODE_SLIDER_MODEL.md) also supplies copied requests and explicit full-pair receipt acceptance; it does not bind direct C custom Styled style or motion records. --- ## Dialog, AlertDialog, Sheet and composed Popover surfaces Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SURFACES.md # Dialog, AlertDialog, Sheet and composed Popover surfaces `cui_surface.h` adds application-owned surface state, drawing-free reducers and paired styled composition. A surface ID and its derived close, confirm, cancel and title IDs must be unique within the UI. Applications call `cui_surface_open` with a valid trigger, submit open surfaces every frame, and consume explicit outcomes with `cui_surface_take_result`. `cui_surface_request_close` queues a programmatic close safely between frames and applies the decision policy once on the next submission. `on_close` runs after state changes and focus restoration, including direct child-action closure. Call `cui_surface_close` during an active frame; if begin succeeded, its matching end remains required even after closing from a child action. Dialogs, alerts and sheets trap focus. Popovers are nonmodal by default, with an explicit modal option. Already-consumed events are ignored by the reducer. Escape and outside primary pointer presses can dismiss an open surface; the options disable either policy independently. Alerts suppress outside dismissal and their header close button by default. A decision callback can reject confirm, cancel or close before state changes. Closing withdraws current scoped semantics and restores an enabled trigger, including when a nested dialog closes back into its parent. The styled begin/end accepts arbitrary CUI children. `cui_surface_footer_begin` ends the body and opens a fixed footer row, keeping its controls visible even when the body contains oversized content; the regular surface end closes that footer. The body measures its own content through completed-layout bounds tracking, routes wheel events to its clipped viewport and clamps retained scroll when content shrinks. Changed geometry schedules correction frames and unchanged surfaces return to idle. Custom base layouts use parts 6/7 for the viewport/content and submit body semantics with `cui_base_surface_submit_body`. It draws a backdrop, title, optional description, close button and clipped body as viewport portals. `cui_alert_dialog` composes destructive confirm and outline cancel buttons. Alert title, description and actions share one vertically centered content block when it fits the panel. Overflowing alert content switches to a clipped, scrollable layout starting at the top, so the full content remains reachable. Each alert has an alertdialog semantic role; other surfaces use dialog, with a copied description and stable title relationship. A caller can compose its own alert actions using the documented derived IDs. Results persist until consumed or the surface is opened again. Dialog dimensions clamp within an explicit viewport and optional uniform margin. Sheets support left, right, top and bottom placement with explicit width/height. Their inner edge has a captured pointer resize control, directional arrow sizing, Home/End limits and semantic size/range. Resize is enabled by default; options disable it or configure minimum/maximum extents. The application-owned `sheet_size` retains user sizing; set it to zero to return to option sizing. `cui_surface_current_geometry` includes that retained size. Custom base-only layouts submit the resize semantic inside its own box using `cui_base_surface_submit_resize`; the helper draws nothing. Popovers use the existing side-based flip/clamp popup geometry. Nested surfaces require distinct IDs and explicitly increasing layers (default 100); the root does not yet provide an automatic overlay stack. `test_surface` exercises actual styled confirmation buttons, rejected acceptance, pointer cancellation, all four themes, all four sheet edges, header close, Escape, outside dismissal, nested focus isolation/restoration and portal escape from an ancestor clip. The same behavior fixtures also run as `surface_base_only`, linking only core, models, overlay and surface base sources. Those fixtures emit only their own clipping commands, demonstrating no theme or component dependency in surface behavior. This is partial upstream kit 0.7.1 parity. Remaining upstream scope includes automatic Root overlay management, custom title/header parts and styling options, body scrollbar chrome and keyboard focus reveal, configurable backdrop appearance, default viewport margins and top offsets, animated transitions and the complete Popover anchor/offset/arrow positioning contract. Existing popover flip behavior differs from upstream's anchored clamp-only default. Native platform accessibility and IME behavior remain separate unfinished requirements. For a child such as a command palette that handles Escape first, set `no_escape_dismiss` on its surface. Let the child consume Escape while clearing its query; on its empty-query cancel callback, call `cui_surface_request_close`. The next submission applies the decision callback and restores focus before registering modal content. Begin-phase dismissal cannot inspect event consumption that occurs later in child rendering. ## Sheet motion Set `options.sheet_animation_seconds = 0.22f` to slide a sheet in and out from its configured edge. The default zero keeps immediate behavior. Motion reads `cui_frame_time(ui)`, which advances from the delta passed to `cui_begin_frame`; continue scheduling invalidated frames. `cui_surface_current_geometry` reports the moving bounds. Resize controls appear once entry completes. With animation enabled, closing keeps the modal mounted during its exit and consumes input events. Focus returns to the trigger, `on_close` fires, and a result becomes available only when the exit completes. `state.sheet_closing` exposes this phase to application composition. Calling open during exit reverses toward the open position. Pass `options.reduced_motion = true` to snap directly to the destination; changing it during exit completes the close in the next submitted frame. Duration is finite, positive and capped at ten seconds; invalid values disable animation. Dialog/AlertDialog/Popover behavior remains immediate. AlertDialog with unspecified/nonpositive finite height fits its measured title, wrapped description and action row plus theme padding. The first frame measures content; the next invalidated frame settles its height. Viewport margins still cap the dialog, and overflowing content remains scrollable. Explicit positive heights retain the fixed viewport contract. Resize, font or content changes can require another measured frame. ## Independent Popover geometry `cui_popover_position_resolve` calculates an anchor-mode rectangle without opening a surface or modifying state. It supports eight anchors named for the popup's own edge, signed explicit offsets, nonzero viewport origins and no-flip/no-shrink clamping. Set `reference_rem` from application root sizing; zero selects 16 logical pixels. The default gap is one quarter rem; enabling the arrow adds three eighths rem. `cui_popover_arrow_resolve` calculates the triangle and border join patch for the final clamped rectangle. Read `cui_surface.h` for finite-input, overflow and output-preservation rules. Geometry remains fractional; host pixel snapping is separate. Use `cui_popover_begin` to apply this positioning and paint an optional arrow, then balance a successful begin with `cui_surface_end`. Existing `cui_surface_begin` retains legacy placement. See [Popover anchors](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/POPOVER_ANCHORS.md) for ownership, failure, rendering and adapter limits. SDL3 and browser mesh adapters have bounded analytic coverage; exact reference raster antialiasing remains unfinished. This is scoped C support, not complete family or language-builder parity. ## Additive intrinsic Dialog composition The separate C Base/Styled six-slot route is documented in [DIALOG_COMPOSITION.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DIALOG_COMPOSITION.md). It resolves current-frame intrinsic sizing, independent Header/Title/Description, Content/Body allocation and Footer ownership using Core layout V2. The legacy helpers documented above keep their fixed or previous-measurement behavior. Retain the new layout storage through end_frame and use its open helper for each new lifetime. Existing held input capture behavior remains; this is not a universal input cancellation API. Root/host and all five foreign slot builders remain separate work. --- ## NanoSVG transform validation patch Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SVG_TRANSFORM_VALIDATION.md # NanoSVG transform validation patch The pinned parser previously left `nsvg__parseMatrix` output unchanged when fewer than six arguments were present. Its caller then multiplied an uninitialized local matrix, or reused a prior transform. Translate, scale and skew read missing arguments directly; rotate read an absent angle or a missing second center coordinate when given two arguments. These are genuine undefined reads, beyond GCC's optimized maybe-uninitialized warning. The local patch preserves the pinned upstream revision. Rejected matrix, translate, scale, rotate and skew argument counts now initialize output to identity. Missing parentheses and excess arguments take the same safe branch. A failed operation therefore leaves the accumulated transform unchanged, while subsequent valid operations remain effective. Numeric overflow to infinity is rejected in argument parsing. Identity fallback is consistent with the parser's tolerant handling of unsupported or malformed transform text; it does not create a new public status API. The patch does not claim strict SVG grammar validation. The existing scanner can skip arbitrary nonnumeric text, and finite matrices can still overflow when composed. General SVG validation remains the icon adapter's responsibility. Valid matrix values, one/two-argument translate/scale, one/three-argument rotate, one-argument skew and transform-list composition retain their geometry. A separate explicit size_t cast for the existing ftell error sentinel fixes a preexisting signed-comparison diagnostic found by whole-header strict compilation. There are no warning suppressions or dependency bumps. `third_party/nanosvg/PIN.md` records original/patched hashes and patch provenance. The integrator updates the manifest hash and regenerates the generated icon header outside this worker's scope. Private `tests/unit/test_svg_transform_validation.c` directly includes the pinned implementation. It checks every malformed helper, missing delimiters, excess or missing arguments, malformed center rotation, overflow arguments, valid transforms, valid-invalid-valid composition (no stale transform reuse), and parsed SVG path bounds. Assertions remain active under compilers that define NDEBUG for -O3. Validation commands (all tests headless): ```sh cc -std=c11 -O3 -Wall -Wextra -Wpedantic -Werror tests/unit/test_svg_transform_validation.c -lm -o /tmp/test-svg-transform-gcc /tmp/test-svg-transform-gcc zig cc -std=c11 -O3 -Wall -Wextra -Wpedantic -Werror tests/unit/test_svg_transform_validation.c -lm -o /tmp/test-svg-transform-zig /tmp/test-svg-transform-zig cc -std=c11 -O1 -g -Wall -Wextra -Wpedantic -Werror -fsanitize=address,undefined -fno-omit-frame-pointer tests/unit/test_svg_transform_validation.c -lm -o /tmp/test-svg-transform-sanitize /tmp/test-svg-transform-sanitize cmake -S . -B build -G Ninja cmake --build build python scripts/test_local.py --build-dir build ``` The Clang-family optimized check uses pinned Zig 0.16.0 `zig cc`, not a system Clang installation. Integrator must register the private test in CMake. --- ## Table and DataTable Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TABLE.md # Table and DataTable The frozen upstream kit 0.7.1 Table is a stateless composition of sections, rows and cells. DataTable adds a data delegate, scrolling, selection and column management. This module provides both composition primitives and a retained data model, with portable C11 public types and independent base behavior. `cui_table_begin`, `cui_table_begin_row`, `cui_table_begin_cell` and `cui_table_end` compose a themed table containing arbitrary caller content. Every begin requires a matching end. These register passive table, row and cell roles; callers can set semantic parent and descriptive details using core setters. Head-cell, header/body/footer section and caption helpers preserve that composition. Validated cell-span helpers sum explicit column widths; failed validation does not begin a box. Callers place captions after their sections and provide accessible head-cell names. There are no implicit data cell labels. `cui_table_column_default(key, label)` supplies a 100-pixel, resizable, movable column with a 20-pixel minimum and optional sorting disabled. `cui_table_options_default()` enables border and scrollbars with row selection and no stripes, matching the supported reference defaults. Zero initialization remains available for applications choosing their own configuration. Widths remain bounded by CUI's 65,536-pixel safety limit. Create `cui_table_model` with a bounded row capacity, then bind borrowed rows and mutable columns. Rows and columns need nonzero unique keys within each dimension. Binding rejects invalid labels, duplicate keys, excessive counts, invalid widths and invalid width limits transactionally. Maximum capacity is one million rows and 128 columns. The model allocates two row-key hash banks once at creation; rendering, navigation, resize and movement do not allocate. Caller metadata stays valid until a successful bind. Rebind after changing row ordering or keys; the caller implements sorting/filtering and may keep selection keyed through both. Columns may be mutated through resize and move functions between frames. Columns marked fixed_left must form a contiguous prefix. Their header and cells remain fixed horizontally, with separate clip scopes preventing scrolling cells from receiving input beneath pinned cells. Column movement cannot cross the pinned boundary. Keep the total pinned width below the viewport width to leave space for scrolling columns. The column viewport describes the scrolling suffix; fixed columns are available through dedicated count/width accessors. `cui_table_state` is caller controlled: selected row/column, keyboard cursor, sort column/direction, horizontal/vertical scroll and transient resize gesture. Row, column and cell selection use the same state; zero keys mean no selection. The reducer returns change flags and activated keys. Sort activation cycles default, ascending and descending; a newly activated column starts ascending. Sorting is requested by the result, without rearranging caller data automatically. On `sort_changed`, sort your application records, reorder the borrowed row array, then call `cui_table_bind` and invalidate the UI. Resolve cell labels from the newly ordered row keys, rather than from the original position. The gallery demonstrates ascending/descending/default ordering for Name and numeric Size, with stable key order for equal Status values. The pure base API separates input reduction from semantic submission. A custom renderer can call `cui_table_reduce`, submit the root outside clip scopes, submit headers inside their pane clips, and submit body semantics inside its translated body clip. Per-column/row/cell submission helpers support distinct pinned and scrolling clip scopes. Lay out the public stable header, resize, row and cell IDs. The `cui_base_data_table` convenience registers all semantics without drawing; it links only core and table base. `cui_data_table` performs that separation and paints the fixed header and virtual rows using theme tokens. Sortable headers show SVG indicators for unsorted/ascending/descending states, with centered labels and a pointer cursor. The icons use the theme icon loader, so applications can replace their SVGs. A label callback supplies borrowed accessible cell names. An optional render callback runs inside each clipped cell and can draw arbitrary content; the application must govern interactive children and disabled behavior consistently. Up/Down skip disabled rows, Left/Right skip disabled columns, and Home/End move to the first/last enabled row in row mode, or the first/last enabled column in the current row in cell/column mode. Escape clears controlled selection and range anchors while retaining the keyboard cursor; disabled/loading tables ignore it. PageUp/PageDown move a viewport of physical rows and skip disabled destinations. Navigation does not wrap unless requested. Multiple events in one frame operate in queue order. Roving cell Tab focus follows the cursor; the header cursor is a separate Tab stop, with Left/Right/Home/End navigation skipping disabled columns. Headers support Enter or pointer sort activation, and Ctrl+Left/Right moves movable columns without crossing an immovable column. Primary pointer dragging past four pixels reorders at header midpoints on drop; it respects pinned regions and immovable columns, suppresses sort activation, and cancels on Escape/cancel or release outside the header. Resize grips accept pointer dragging and Left/Right in eight pixel increments. Secondary clicks return a contextual row/column request without changing selection; the application composes and controls the menu. Widths clamp to configured bounds; secondary button gestures do not resize. Manual selection moves the cursor without changing selection. Disabled state prevents reducer mutation. Enabled movable column headers opt into touch drag priority: a primary touch starting on the header reorders rather than handing off to ancestor scrolling. Nonmovable headers and body content retain pan behavior. Touch drop admission uses that UP event's coordinates and the prior clipped/modal-eligible semantic region, so a later mouse sample in the same batch cannot change its result. Mouse routing and callback timing remain unchanged. See [indexed pointer-region admission](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/EVENT_HOVER.md) for the Core query contract and occlusion rules. The body uses fixed row heights, fractional scroll offsets, bounded row and column overscan and real ancestor clipping. The header remains fixed vertically and shares horizontal scroll with the body. Width-aware horizontal column virtualization includes partial edge columns. An optional pinned row-number header selects whole rows and navigates enabled rows. Its result requests ROW selection mode; the caller applies that request to the controlled options. Row headers continue working when all data columns are disabled. Result fields report actual visible row/column windows (without overscan), changes to those windows, and an opt-in load-more request near the end. Load requests fire once per threshold entry or changed row count; applications append rows and rebind. They are suppressed while disabled. Both grid and body expose scroll extents for core wheel routing and boundary bubbling. Wheel scrolling can move the cursor offscreen without forcing it back into view; keyboard navigation reveals the cursor again. Grid, row, column-header and grid-cell semantics include hierarchy, selection, row and column indices, and total grid counts. Indices are one based data indices and exclude the header. IDs are stable keyed hashes; applications must avoid hash/ID collisions with other controls as required by the core. Custom leaf-header, group-header, row-header, whole-row and trailing-column render hooks use option userdata. Group headers accept up to sixteen levels of bounded spans. Every level must cover all data columns exactly, and no group may cross the fixed-column boundary; `cui_table_group_headers_valid` lets applications validate a configuration before rendering. Group cells expose column-header semantics at their first column; the callback receives the complete span. Whole-row callbacks run only for virtualized rows and can add row-level decoration or content before the cells. The optional trailing column uses a caller-selected width (12 logical pixels by default) and participates in horizontal scroll extent; its callback runs for each header level, the leaf header and visible rows. Loading replaces body rows with a busy status and suppresses input/load requests; empty and loading placeholders have optional render hooks and accessible default labels. Set `scrollbars` to reserve scrollbar gutters only when an axis overflows. `bar_thickness` controls their logical thickness. The drawing-free reducer delegates keyboard, track and thumb behavior to the reusable Scroll base primitive, while the styled table paints the same scrollbar state. The grid and scrollbar semantics share the table as their scroll owner. Applications that build a custom renderer can use `cui_table_scroll_layout` to obtain the reduced viewport and scroll maxima. Tests cover four-theme static sections/spans/caption geometry, multi-level group geometry and semantics, virtual whole-row and trailing-column callbacks, row-header selection mode requests, drag reorder/cancellation, empty/loading/custom hooks, bounded row/column/cell ranges, toggles, capacity rejection, and transactional validation, keyed lookup in 10,000 rows, fractional viewport arithmetic, clipped overscan, callback count and accessible labels, fixed header geometry, pinned header/cell geometry and clipping/hit behavior, horizontal clipping/virtualization, load request deduplication, ordered keyboard events, disabled skipping, manual selection, sorting, column reorder, keyboard/pointer resize, width clamps, secondary gestures, wheel/focus interaction, scrollbar keyboard/thumb behavior and semantic hierarchy. The same behavior tests run with a base-only core link; sanitizer validation instruments both layout and reducer. This is not full upstream family parity. Remaining features include composed menus, cell Tab traversal, double-click events, per-column padding/default sort configuration, and variable row heights. Selection defaults to a single controlled keyed item in each dimension. An opt-in multiple-selection mode uses a caller-provided buffer of at most 4096 keyed items, with Ctrl/Meta toggles and Shift row/column/rectangular ranges. Disabled rows and columns are excluded from ranges. Capacity failures preserve the prior selection and keep the table rendered; callers may enlarge the buffer and retry. The anchor and buffer are controlled state, and callers must retain unique normalized keys in the buffer. Caller sorting/filtering is supported but this module does not provide a comparator or filter engine. Native accessibility adapters must map the portable grid roles. --- ## Segmented Tabs: opt-in source shadow branches Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TABS_SOURCE_SHADOWS.md # Segmented Tabs: opt-in source shadow branches This bounded appearance slice uses upstream kit 0.7.1 commit `87d10ae5e1299d1be18670a37570c5402f952e34`: [TabBar indicator](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/crates/component/src/tab/tab_bar.rs#L195), [Tab branches](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/crates/component/src/tab/tab.rs#L650), and [private raised helper](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/crates/component/src/styled.rs#L114). It does not complete Tabs/TabBar or certify upstream GPU AA/kernel/color identity. Prior actual CUI draw-list evidence in `docs/validation/shadow-consumers-next33.md` showed no DROP layers in measured/static segmented paths. Append `shadow_policy` to `cui_tabs_options`: | Policy | Segmented behavior | | --- | --- | | LEGACY=0 | Existing paint, no added shadows; zero initialization remains compatible. | | SOURCE_TAB=1 | Standalone-like selected enabled inner cell uses public XS; no shared indicator, even if animation supplied. | | SOURCE_BAR=2 | Requires caller-owned animation and horizontal orientation. Before measurement, selected enabled inner cell uses public SM. Once measured, the shared indicator uses the private raised pair. | SOURCE_TAB is a styling mode on the existing CUI tab-list API, not a new claim that the standalone upstream Tab composition/semantics are fully implemented. SOURCE_BAR explicitly requires the existing retained state instead of hiding an allocation; source retains its indicator through window-keyed state automatically. Other variants ignore valid policies and retain their paint/animation behavior. Invalid policy or unsupported SOURCE_BAR configuration returns false before Base reduction or content/render callbacks; `cui_tabs_shadow_policy_valid` offers an explicit check because the existing widget return is a changed flag. Ordered tuples are `(x,y,sigma,spread,black alpha)` in logical pixels: * Standalone XS: `(0,1,2,0,13)`. * First-measure SM: `(0,1,3,0,26)`, then `(0,1,2,-1,26)`. * Measured private raised: `(0,1,1.5,0,26)`, then `(0,1,1,-1,26)`. Public SM/XS are used only where source calls those presets. The measured pair is not substituted with either public preset. Its caster is the spring-resolved inner indicator, never the text label or entire trough. Background is theme background; inner height and radius follow the applicable tab metrics. Source four-size radius selection follows the size enum independently of density. CUI's expanded design sizes use the existing inner-height radius mapping as an explicit extension. Core applies inherited opacity once (half opacity gives alpha6 for XS and13 for SM/private). The inner surface follows the shadows. Disabled standalone/first-measure tabs have no shadow, matching source `TabStyle.shadow=false`. Source TabBar's shared indicator admission does not reject a disabled selected index: CUI preserves the externally controlled disabled selection and emits the measured indicator, while keeping disabled tab appearance, inert interaction and absence of its panel. The disabled outer background can cover parts of the indicator; tests must compose that background rather than compare shadows alone to white. No disabled activation or implicit selection repair is introduced. The initial measurement requests a follow-up frame. Existing caller spring/transition behavior remains in use. Keep `cui_tab_animation` alive through `cui_end_frame`, since existing bounds tracking writes there; give each retained tab-list owner its own state and reset it on rebinding as before. The new prepaint payload contains only copied geometry/radius/color, never a pointer into that state. It emits two DROP commands plus the surface, with an explicit five-command budget including Core's two clip commands. Layout masks/modal/opacity and bounded frame storage follow Core's existing contract. Invalid policy is a pre-reduction failure; a later global Core frame/resource failure is not a rollback promise for already accepted widget events or callback side effects. Renderers still prepare their resources before clearing targets. Existing CUI scrolling clips both axes, whereas the pinned source wrapper specifically hides horizontal overflow. This slice preserves the scrolling API and documents possible vertical-tail clipping. Vertical SOURCE_BAR is unsupported atomically; SOURCE_TAB can style CUI's vertical extension. Generic Source StyleRefinement, standalone composition API, all TabBar lifecycle/animation/scroll differences and full family parity remain outside this appearance slice. ## Review and registration receipt Root registers new tests and regenerates distribution; this worker changes no global configuration/gallery/backend files. * `tests/unit/test_tabs_source_shadows.c`: actual composed Core commands for all four source sizes, both themes, exact tuples/order/caster/radius/opacity, genuine first measure, measured disabled selection, real pointer enable/disable behavior, controlled selection changes, scroll caster translation/stability, immutable paint-copy lifetime, unchanged nonsegmented/legacy paint, invalid policy/missing state/vertical failure before callbacks or retained-state changes. * `tests/integration/tabs_source_shadows_fixture.h` and `test_tabs_source_shadows_native.c`: copy actual component draw payloads then destroy the originating context; omit TEXT identically in each consumer for geometry/alpha proof without a hardcoded font. Software, SDL Renderer, SDL GPU and Sokol agree at straight interior/outside samples within three byte levels for40 frames: five branches × light/dark × opaque/translucent × DPR1/2. The historical worker run used a desktop display and constrained utility GPU window; that is not a permitted current automated-test workflow. Current Linux automation must use `python scripts/test_local.py --build-dir build`, with private Xvfb; GPU checks unsupported there remain deferred. The current headless gate does not re-establish the historical physical-GPU result. Link cui_software/cui_sdl3/cui_sdl_gpu/cui_sokol and their native dependencies; define GL_GLEXT_PROTOTYPES. No wrapper symbols needed. * `uv run tests/web/test_tabs_source_shadows.py --output OUTPUT --chromium PATH`: pinned Playwright1.58, Zig0.16 WASI reactor and actual composed Core/Components fixture. Chromium1208 passes40 frames, exact branch tuples plus Canvas/WASM pixels against ordered surface/clip/shadow compositing. Initial oracle omitted the retained disabled outer background and failed; corrected reference preserves the exact byte-tolerance assertion. This is standalone proof, not Gallery wiring. Strict native warning build passes. Full CTest166/167 fails only stale generated `distribution`; Root regenerates. Scoped ASan/UBSan/leak checking passes. Actual Wasmtime49 WASI headless tests pass. Native proof `/tmp/cui-tabs-source-native.log`; browser proof `/tmp/cui-tabs-source-browser-corrected.log`; CTest `/tmp/cui-tabs-source-final-ctest.log`; sanitizer `/tmp/cui-tabs-source-asan-final.log`; WASI `/tmp/cui-tabs-source-wasi-final.log`. New tests are not yet part of the isolated baseline CTest count. No native font pixel or physical screen-reader claim is made. --- ## Ordered focus traversal Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TAB_ORDER.md # Ordered focus traversal Reference: upstream-component commit `87d10ae5e1299d1be18670a37570c5402f952e34`. Its Cargo.lock pins registry `upstream-pre` 0.3.8, checksum `d7f0bc3ebba070f8981b3f8e905a12f47d27794a30d029e59cdb9edf7a4b3360`. Source evidence: `crates/base/src/button.rs` defaults index 0 / stop true and passes both independently; `crates/component/src/button/button.rs` does likewise. Pinned upstream `src/tab_stop.rs` defines a signed path of group indices plus leaf index, lexicographic comparison, then insertion order. Prefixes precede longer paths. Negative indices are ordered values, not automatic exclusion. Nonstop handles remain traversal anchors. `src/window.rs` focus_next/focus_prev use the rendered frame map and wrap at either end. These files were inspected locally in `/tmp/cui-upstream-reference` and `/tmp/upstream-pre-0.3.8`. Use `cui_set_tab_index` after registering behavior to opt into signed ordering. Use `cui_set_tab_stop` independently to enable or disable traversal eligibility. Use `cui_begin_tab_group` / `cui_end_tab_group` around child submissions for hierarchical prefixes. Equal complete paths retain semantic submission order. Groups are independent of focus scopes: scopes constrain eligibility, while ordered groups constrain ordering. Tab uses the previous published snapshot; `cui_focus_step_within` uses the current submitted controls within its scope. Disabled and no-focus controls remain ineligible. Programmatic focus on an eligible non-stop control anchors the next/previous search at that control's path. Zero-initialized legacy semantics retain submission order. Legacy set_tab_stop continues exposing index 0/-1, and legacy negative tab_index remains excluded. Calling set_tab_index explicitly allows every signed int, including -1, as an ordered stop. Index and stop setters do not overwrite each other's choice once signed ordering is enabled. Storage is bounded to 32 group levels, captured by value in each semantic snapshot. An overflow begin fails atomically; callers must end only successful begins. Index range is portable C int (upstream uses platform isize). This is source ordering parity, not all upstream focus-handle lifecycle, retained paint replay, or accessibility platform parity. Component option mapping is separate work. --- ## Styled text and font faces Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TEXT.md # Styled text and font faces `cui_text_ex` and `cui_measure_text_ex` take `cui_text_style`: Normal, Medium, Semibold or Bold weight, plus independent italic and monospace flags and an application-defined `uint32_t family` ID. Family zero selects the default; nonzero IDs identify separately registered families. `cui_text_ex` also accepts an optional logical line height. The older `cui_text`, `cui_text_with_line_height` and `cui_measure_text` APIs use regular text. The style travels through Clay measurement and the draw list to the software, SDL3, SDL_GPU and Sokol renderers. Set `cui_config.measure_styled = cui_font_measure_styled` and `measure_user = font` when creating a context with a native `cui_font`. These native callbacks take `void *` and match the Core callback signatures directly; do not cast function pointers. If `measure_user` points to an application host struct, extract its font inside correctly typed wrappers; see the complete [typography example](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TYPOGRAPHY.md). The renderer must use the same font object. The legacy `measure` callback remains available; if `measure_styled` is absent, layout uses that callback for every style. Native selection uses the exact family/style registration first, then that named family's registered regular face, then the default family's matching style, then the opened regular face. Measurement, font metrics, and drawing use the same selection. CUI does not synthesize bold, italic or monospace glyphs from a regular face. Use `cui_font_register_style(font, style, path)` to open an actual family or variant face owned by the regular font. Registrations are keyed by family, weight, italic, and monospace. A nonzero family can register its regular style; the default family's regular face remains the one opened by `cui_font_open`. A failed path leaves the previous registration intact; replacing a variant or closing the regular font releases the owned face. `cui_font_set_style(font, style, variant)` borrows a face opened by the caller. Keep borrowed faces alive through every frame that uses them, then close them separately. Call `cui_text_metrics_changed(ui)` between frames after changing registrations so Clay remeasures cached text. The gallery registers Noto Sans Medium, Semibold, Bold and Italic plus Noto Sans Mono only when the selected regular font is the known Noto Sans path. A custom `--font` or `CUI_FONT_PATH` retains its chosen family and uses regular fallback until the application registers matching variants. The renderer swap demos configure styled measurement with their selected font; they do not assume matching variant paths for custom fonts. `cui_measure_font_metrics(ui, size, style, &metrics)` queries the actual selected face's ascent, nonnegative descent and renderer line height in logical pixels. Set `cui_config.font_metrics = cui_font_get_metrics` with the same `measure_user = font` for the FreeType adapter. Custom hosts supply the optional `cui_font_metrics_fn` callback; it shares the measurement user pointer and receives the complete text style. A missing provider, invalid input or malformed callback result returns false and preserves the output. This API deliberately supplies no guessed baseline from string height. Line spacing can be smaller than ascent plus descent, and callers must account for leading when positioning inline content. The native gallery and renderer swap examples register the provider. Core tests cover unavailable providers, style and fractional-size forwarding, live metric changes, invalid results and output preservation; native tests compare selected variants to their underlying faces and check metric scaling against measured line height. This is infrastructure for inline-object layout; it does not by itself implement TextView's mixed text/image flow or complete shaping-aware selection. For example, choose a stable application ID such as `7`, register its regular face with `(cui_text_style){.family = 7}`, and register its bold face with `(cui_text_style){.family = 7, .weight = CUI_TEXT_WEIGHT_BOLD}`. Pass those styles to both measurement and drawing. Missing variants remain in the named family when a regular face is registered; CUI does not synthesize variants. Family IDs are opaque keys, not operating-system font names or automatic font discovery. The native registry allocates sparse entries for registered IDs and supports the full nonzero `uint32_t` range. Removing a family's regular registration leaves its separately registered variants intact. Removing an absent style succeeds. One caller-opened face can be borrowed by several registrations. Replacing or removing a borrowed registration does not close that face, and closing the registration owner leaves borrowed faces alive. Path registration opens an independent owned face; replacement, removal, and owner close release it. Keep borrowed faces alive while any measurement or draw can use them, and close them once separately. Face operations remain confined to the UI thread. Never retain an owned face pointer beyond its registration lifetime. Core style interning includes family alongside size, line height, weight, italic, and monospace, so equal text at equal size in different families has distinct layout cache keys. After changing any registration, call `cui_text_metrics_changed(ui)` between frames for every context using the font. A custom styled measurement provider receives the family unchanged; a legacy measurement provider may use one fallback face for all families. A custom renderer or browser host must apply the same family mapping used for measurement. Zero-initialized styles keep default-family behavior; rebuild consumers after changing public headers because the style structure has gained a member. `tests/integration/test_text.c` compares actual proportional and monospace faces across measurement, font metrics, glyph raster coverage, core layout, fallback, registration failure, replacement, aliases, and owned/borrowed close lifetimes. Set `CUI_TEST_FONT` and `CUI_TEST_FAMILY_FONT` to distinct font files when system fixtures are unavailable. The test returns 77 when no fixture pair is found. The native integration test also configures Core through wrappers whose shared user pointer is a host struct containing the font. It checks styled family forwarding against actual layout/raster output and routes the Core font-metrics query through that same host. A wrapper's first parameter must remain `void *`; a function taking `cui_font *` directly is a different C function-pointer type, even though object pointers can be converted inside the wrapper. `cui_text`, `cui_text_with_line_height`, and `cui_text_ex` all word-wrap to the available width of their layout parent. Give the parent a constrained width (for example, `(cui_box){.width = 240, .fixed_width = true}`) to lay out a paragraph; a content-sized parent has no narrower width to wrap against. Explicit line height and font style do not change wrapping. `cui_text_line` preserves a caller-laid-out line and may overflow its parent, so use a clipping ancestor when overflow must remain hidden. For strict UTF-8 paragraphs with explicit hard breaks and optional color spans, `cui_text_paragraph_colored` selects word wrapping with its `wrap` argument. ## Embed fonts in a native executable `cui_font_open_memory(const void *data, size_t size)` opens the first face in an in-memory font using the native `cui_text` adapter. It performs no font file I/O and does not copy the bytes. This supports fonts compiled directly into an executable, with no font files to install beside it. For example, generate a C header from a font you have permission to redistribute: ```sh python3 - <<'PYFONT' from pathlib import Path font = Path("assets/App-Regular.ttf").read_bytes() with Path("app_font.h").open("w") as out: out.write("static const unsigned char app_font[] = {\n") for start in range(0, len(font), 16): out.write(",".join(str(b) for b in font[start:start + 16]) + ",\n") out.write("};\n") PYFONT ``` Include the generated header in one C source file: ```c #include "cui/cui_text.h" #include "app_font.h" /* During application initialization: */ cui_font *font = cui_font_open_memory(app_font, sizeof app_font); if (!font) { /* Report initialization failure. */ return 1; } /* Use font for native measurement and rendering as with cui_font_open(). */ /* After destroying the UI and any retained text layouts: */ cui_font_close(font); ``` The buffer is borrowed and must stay immutable and valid until the actual face is released. A layout can retain a face after `cui_font_close`, so a dynamically allocated buffer must also outlive those layouts. A `static const` array stays valid for the entire process and needs no separate cleanup. NULL, zero-length, oversized, or invalid font data returns NULL. Embed bold, italic, and fallback fonts as separate arrays, open each with `cui_font_open_memory`, and register their handles with `cui_font_set_style` or `cui_font_set_fallbacks`. These registrations borrow handles; keep the faces alive while registered and close them separately after use. File-based and memory-based faces can be mixed. Embedding increases executable size; large multilingual fallback sets may be better shipped separately. Check each font's redistribution and embedding license. Embedding assets is independent of static linking: link CUI and its native dependencies statically as well if your distribution requires that. This API concerns native fonts; browser font loading continues to use the web host. ## Native letter spacing See [Letter spacing](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/LETTER_SPACING.md) for the opt-in cluster tracking API, provider capability checks, ABI rebuild requirement, negative-spacing policy, and renderer/binding limitations. Canvas and GPU tracking are not implemented. --- ## Textarea Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TEXTAREA.md # Textarea `cui_textarea` is a bounded multiline editor with measured soft wrapping, pointer selection, vertical keyboard navigation, selection highlights, caret painting and a scrolling viewport. It uses a caller-owned multiline `cui_edit` for text, selection and undo history. It is independent of the single-line Input renderer. ```c char text[4096] = "First line\nSecond line"; cui_edit *edit = cui_edit_create((cui_edit_config){ .buffer = text, .capacity = sizeof(text), .multiline = true, .history_bytes = 8192, .max_history_steps = 64 }); cui_textarea_line rows[256]; cui_textarea_state state; cui_textarea_state_init(&state, rows, 256); /* Each frame, inside an open layout box: */ cui_textarea_result result = cui_textarea(ui, id, &theme, cui_string("Description"), edit, &state, (cui_textarea_options){.width = 320, .rows = 4, .placeholder = cui_string("Write a description"), .clipboard = platform}); ``` Keep the editor, row workspace and state alive across frames. Each widget needs its own state. Text buffers must remain valid and unchanged until the draw list has been rendered. Destroy the editor when finished. No Textarea allocation or hidden cache is used. Text is limited to 65,536 bytes and the row workspace to 65,536 entries. Invalid inputs return `CUI_TEXTAREA_INVALID`; insufficient measured-row capacity returns `CUI_TEXTAREA_CAPACITY` and suppresses partial painting. An edit may succeed before exhausting visual-row capacity; expand the workspace rather than treating this error as a text rollback. Text-buffer capacity errors are reported separately through `edit_error`. The zero-initialized options use the source Medium metrics: font 14, line height 20, horizontal padding 10, vertical padding 8, one row, appearance and border enabled. Preset metrics scale by `theme.font_size / 16`. XS/S/M/L fonts are 12/14/14/16; horizontal padding is 4/8/10/12 and vertical padding 0/2/8/10. Custom size uses font `custom_size * .875` and horizontal/vertical padding 8/2 at the same density. Width zero selects the CUI fallback 280; a negative width grows. Positive height overrides row height. Auto-grow defaults to one through ten rows and can be bounded explicitly. It is an optional CUI policy, not the upstream initial mode. Soft wrapping preserves every byte and prefers whitespace boundaries. LF, CRLF and CR split hard lines; a final newline creates an empty final row. A cursor at a soft boundary has upstream/downstream affinity, so Left/Right can move between the two visual positions without changing the byte offset. Up/Down and Page Up/Down preserve a measured horizontal target; Home/End operate on the visual row, and command Home/End on the whole buffer. Movement reveals the caret. Pointer dragging and Shift navigation extend selection. Clipboard copy/cut/paste use the supplied synchronous platform callbacks; read-only fields retain navigation, selection and copy. Disabled fields reject interaction. External `cui_edit` mutations are detected through revision and selection changes, without reporting them as edits performed by the widget. Enter inserts a newline and reports `pressed_enter`, `enter_secondary` and `enter_shift`. With `submit_on_enter`, ordinary or secondary Enter reports submission without insertion; Shift-Enter still inserts. These fields describe the last handled Enter in a frame. Read-only and disabled fields do not report submission. Editable Textarea consumes Tab and Shift-Tab for indentation by default, including repeated key events. `tab_size` defaults to two spaces; `hard_tabs` inserts one tab byte instead. A collapsed Tab inserts at the cursor. A selection indents every touched hard line, including a line where the selection ends at its start. Shift-Tab removes only an exact matching prefix at each line start. An unchanged outdent creates no history step. Each successful operation is one undo step that restores the original selection; redo restores the mapped endpoints. Capacity failure leaves text, history and selection unchanged. Set `no_indent` to use normal Tab focus traversal. Read-only and disabled fields also retain normal focus traversal. The semantic node carries a Textbox role, multiline, read-only, required, invalid, disabled and selection/scroll details. `name` labels the semantic node; it is not a visible label. A custom role and removal from Tab stops are available. The theme's input background/border, text, muted, selection and independent caret tokens are consumed. Reduced motion gives a steady caret. Otherwise focused fields invalidate for caret blinking. ## Remaining source gaps This is a scalar UTF-8 editor, not the upstream shaped editor. Grapheme-aware movement, word navigation, bidi shaping and cluster hit testing, IME preedit, inline atomic tokens, multiple cursors, language/editor features, rich paste interception and native context menus remain unsupported. Numeric Tab ordering and external accessibility IDs also require shared APIs. No parity claim is made for these behaviors. Grow-width wrapping uses the previous tracked viewport, with a 280-pixel initial fallback; same-frame intrinsic width changes can therefore require another frame. Placeholder painting uses the core text renderer rather than an independently measured multiline placeholder workspace. There is no source focus shadow or independently configured line-height option. Explicitly sized fields avoid the initial grow-width measurement limitation. Keyboard events marked `ime_composing` or `prefer_character_input` are left unconsumed by Input, the edit engine's routed event helper, and Textarea. They cannot navigate, edit, invoke clipboard shortcuts, submit or insert a newline. Committed `CUI_EVENT_TEXT` still inserts normally, and ordinary keyboard navigation resumes afterward. This protects host composition ownership; rendering preedit text and candidate windows remains a host integration gap. Vertical and horizontal scroll offsets are applied to the clipped viewport, so virtual row culling and paint translation agree. Repeated Down at the final line keeps that line visible; Ctrl+Home returns to the first line. The caret model and the text drawing positions are tested together. --- ## Private counted text preparation Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TEXT_PREPARATION.md # Private counted text preparation `src/text/cui_text_prepare_internal.h` is a maintainer-only recording seam, not a public font API or renderer. Its private software with-font consumer is described in `SOFTWARE_V2_PAINTING.md` and is used by the unreleased [public C software V2 adapter](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SOFTWARE_V2.md). The other four adapters and bindings remain pending. Initialize a zero `cui_text_owner_internal` with malloc-compatible aligned, distinct-block allocation/free callbacks and the **remaining** transaction CPU and metadata envelope; create `cui_text_prepare_session` with that owner. Call `cui_text_prepare_line(session,font,TEXT_command,source_density)` synchronously. Owned density is explicit1..64; public/NULL-owner scaled APIs retain their1..16 limit. The software adapter chooses q from target axes; recording at64 alone does not advertise other adapter support. The private contextual-availability query reports the actual compiled Bidi recorder. Nonempty owned glyphs require256-level FreeType GRAY coverage, including hot-cache reads; other bitmap formats reject without changing legacy raster behavior. Checked source sizes and origins reject unrepresentable FreeType/integer coordinates before conversion. This records original source-grid positions, color/paint and tightly packed owned glyph coverage. It does not perform bilinear resampling or target blending. CUI layout/Bidi wrapper arrays, allocation prefixes and glyph coverage charge CPU; glyph descriptors charge separate metadata. Every request is checked before its allocator callback. No new CUI glyph-cache insertion occurs on cold V2 raster; existing hot entries may be read. NULL-owner internal paths retain legacy public allocation, cache insertion and fallback behavior. Font and Bidi public headers, opaque object ABI and V1 renderer routes are unchanged. Existing font state and newly allocated opaque FT/HB/Sheen/provider temporaries are explicitly separate: no joint32MiB/process/RSS or arbitrary-provider time promise. See [accounting decision](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SOFTWARE_V2_FONT_SESSION.md) and the public options comment. Every selected face/reference, layout, buffer and paragraph is released through its original or counted owner on failure. No global allocator swap, dependency replacement or application input/measure callback is involved. Frame work limits:64KiB/full paragraph,256KiB aggregate repeated paragraph input, 64 faces,8192 shaping attempts,4096 segments (an empty line consumes one),65536 shaped glyphs,8M copied coverage pixels; each bitmap <=4096/side and4M pixels. Native font size retains its existing 4096 logical limit. Opaque operations may allocate before output-dependent limits can be checked. CUI budget failures and admission are sticky in the owner; use a fresh owner for a new transaction after releasing the failed one. Failure appends no partial glyphs for that command; earlier records remain only for teardown after a sticky error. End releases owned records, not borrowed paint-stop arrays. Borrowed font graphs and source resources must stay stable through session end/render completion. Glyph callback rows are copied before return, including checked negative pitch. Allocation/release callback reentrancy cannot prepare or end the active session. Provider/dependency state side effects are not rolled back; only future published target pixels are transactional. Tests compile frozen original CUI text/Bidi/software source into separately prefixed types/functions with their own fonts. Same-runtime old/new legacy output and recorded glyph pixels compare exact active fields, coverage and RGBA bytes; no pointer/padding/hash-only oracle. Bundled Inter tests include multiline/soft breaks, tracking, contextual colors/gradient paint, Bold selection and16x source raster; legacy cache/density/shaping tests supplement these. Every CUI allocation and explicit dependency failure step is swept; budgets, alias/lifetime and retry checks run headlessly. Bidi-disabled source is tested separately. The private V2 no-Bidi recorder rejects contextual paragraph pointers (including empty context) and color spans before reading borrowed strings or allocating. It does not use the public legacy no-Bidi raw-text fallback; that route remains unchanged. Frozen pre-refactor byte files additionally pin the captured toolchain, archive, source, flags and font hashes. They are not universal FT raster goldens. Set `CUI_TEXT_FROZEN_EXACT=1` only for that compatible dependency build; version numbers alone do not prove matching hinting configuration. Other hosts must still pass the independently compiled original-source comparison. The Python reference contract always verifies immutable source/font/fixture hashes; never refresh expected bytes from candidate code. Optional `--compare-reject` runs a real mutated-byte negative check under the private-display test wrapper on the captured toolchain. Local verification: strict C11/O2 with all warnings as errors compiled both Bidi and no-Bidi candidate/original-source test pairs. Private-Xvfb focused tests passed 6/6 (recording pairs, legacy cache/density/shaping, real mutated-byte rejection); `CUI_TEXT_FROZEN_EXACT=1` used the pinned bundled Inter files. An initial legacy density invocation lacked the font environment and skipped; the complete rerun with the explicit bundled font passed. The reference hash tests passed2/2 and installed-skill tests passed18/18. Full current native CMake integration and other host dependency builds remain integrator/CI gates. Failure injection covers every CUI request and explicit dependency-call boundary, not opaque internal malloc. Followup verification compiled Bidi and no-Bidi fixtures with actual Release `-O3 -DNDEBUG -UNDEBUG -fPIE -Wall -Wextra -Wpedantic -Werror` flags. Seven focused private-Xvfb checks passed. Poisoned pointers derive from volatile address1 to preserve invalid-read detection without GCC constant-propagation array-bounds diagnostics in deliberately rejected inputs; warnings remain enabled. The no-Bidi context/span rejection tests assert zero allocator calls, dependency calls, input admission and published records. Integrator CMake/runtime verification is separate. --- ## TextView Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TEXT_VIEW.md # TextView This module implements a bounded document model and selectable styled presentation against the frozen upstream 0.7.1 TextView contract. It is a substantive first slice; the remaining source features below are not implemented. The application supplies `cui_text_view_workspace`: separate source and rendered UTF-8 buffers, byte mappings, spans, blocks, glyph geometry, and optional highlight storage. Keep this storage and state alive while the view is submitted. The parser allocates no memory. Source and rendered buffers include a terminating zero byte; capacities therefore include that byte. Documents are limited to 65,536 bytes and 8,192 nodes. Glyph capacity must cover rendered byte length. Insufficient parser capacity and malformed UTF-8 leave the previous document intact. Initialize with `cui_text_view_init`, update with `cui_text_view_set_text`, and render with `cui_text_view(ui, id, theme, &state, cui_text_view_default())`. The defaults select text, fit content without a scrollbar, use theme text/link/selection/code colors, and leave streaming fades disabled. Set a positive width for deterministic first-frame wrapping. Grow dimensions use retained bounds and a first-frame estimate (320 by 240); bounds changes schedule a follow-up measurement frame. Markdown handles headings, emphasis, strikethrough, inline/fenced code, links, entities, escaped punctuation, bounded nested lists and passive task checkboxes with source starting numbers and consecutive numbering, rules, pipe tables and block images. Soft paragraph breaks join with spaces; two-space hard breaks retain line breaks. HTML handles the corresponding safe presentation tags and strips script/style bodies; it never executes markup or loads resources itself. Each rendered scalar maps to its original source bytes, including entity atoms, while block separators have no source mapping. Markdown range highlights accept rendered byte ranges; source range conversion excludes syntax. HTML source mapping/highlights return unsupported, matching the frozen source restriction. Selection endpoints must be UTF-8 boundaries. `cui_text_view_select` reports whether selection changed. Selection supports separate-frame pointer dragging, Shift plus arrow/Home/End, select all, Escape clearing and copy through the optional portable clipboard interface. It is read-only. Links remain independently focusable; primary and secondary activation forward the original event to `on_link`. A selection drag suppresses link activation. An installed callback consumes activation; otherwise an explicit host `open_url` callback handles primary activation. URLs are decoded temporary slices valid during the callback and must be copied for deferred use. Image loaders return borrowed straight RGBA bitmaps; pixels must survive renderer completion. Image callbacks run during submission and may report not ready until a later frame. The application schedules invalidation when asynchronous work completes. Actual bitmap drawing uses Core clipping and the renderer adapters. Code and table action callbacks receive a unique action container ID and compose real controls. Code actions overlay the top right with 8px insets and a fitting opaque background, after document text paints. They do not enlarge code blocks. Table actions occupy a full-width footer separated by 4px. Callback heights are explicit; callbacks must not end the owning container. Interactive action controls keep their own pointer gestures and do not start document selection. The optional code highlighter supplies foreground colors per code byte. Scrollable views compose the real Scroll component, including scrollbars and consumed-event handling. Reveal requests retain only the latest range, expire after one second, follow unchanged source edits, and reveal the nearest line in the view's own scroll area. Fit views report window line bounds through an explicit host callback. Max-lines fit mode clips oversized content and drops ordinary lines that straddle the cap. Streaming append fades last 350 ms; replacement is immediate and reduced motion disables animation. Ordered highlights paint in request order, then selection above them. Unchanged source prefixes/suffixes retain highlights through edits. A replacement inside a table drops highlights from the edited row and subsequent rows because their cell positions may change; earlier unchanged rows and tables shifted as an unchanged suffix retain highlights. Nested HTML emphasis preserves outer styles after an inner close. `src/base/cui_text_view.c` links with the C math library only. Styled presentation requires Core, Theme and Scroll (base and components), the components checkmark drawing helper, plus portable platform clipboard declarations. Styled text uses real weight/italic/monospace measurement and drawing; register matching native faces for the desired typography. The regular face remains the renderer fallback. No Content rich-text parser existed to reuse. Remaining frozen-source gaps are tracked explicitly: complete CommonMark/HTML5 and complete nested-list/quote structure, MDX/plugins/YAML front matter, image error UI, complete shared-window selection identity, touch selection menus and handles, grapheme/BiDi shaping, inherited parent foreground palettes, fully configurable table/action refinements, automatic enclosing-list reveal, background syntax styles, cached/asynchronous parsing and layout. Default wrap tables use capped text-length column proportions (5 to 150 characters) and 64px minimum columns. Narrow wrap tables clip at the document edge; opt-in adaptive horizontal table scrolling is available through `table_mode`. These limitations must not be presented as full source parity. Headless tests cover transactional bounded parsing and randomized syntax, Unicode mapping/selection, edit tracking, entities, safe HTML, tables, clipping, fade state, composed action geometry and clicks, fence lengths and code content, real styled draw commands, separate-frame selection and focus, primary/secondary link callbacks, drag suppression, bitmap drawing and invalid geometry. Source-format copy uses `cui_text_view_copy_selection` with a separate caller-owned output buffer. It reconstructs partial inline emphasis, links, code, headings, quotes, lists, aligned table rows and fenced code. Table selections preserve all table rows, emit blank unselected cells and retain the delimiter alignment row. Select-all returns the original Markdown verbatim; HTML and plain documents use rendered text. Capacity queries report required bytes without writing output, and insufficient capacity preserves existing output. For Ctrl+C, provide `options.copy_buffer/copy_capacity` and set `copy_format` to Source. Scrollable views copy plain text, matching the frozen source's effective format. Insufficient output capacity leaves the clipboard unchanged. Default table cells use 8px horizontal and 4px vertical padding, normal inherited text weight, clipped content, and one border at each shared edge. Header backgrounds use the code background, body cells use the theme surface. TextView links follow the frozen text style's primary color mapping rather than the general link token. The pure layout API additionally exposes `table_mode` (`WRAP` by default, `ADAPTIVE`, or `NOWRAP`). Adaptive columns measure each trimmed cell line using its styled spans, retain a 48px minimum, and shrink to content-dependent floors between 160px and 480px (never above the measured content). Nowrap columns keep single-line content widths. Both account for 16px horizontal padding, shared 1px column borders, and the 2px outer frame. Extra viewport space grows columns in proportion to measured widths. The styled component uses the same mode and composes actual axis-locked horizontal Scroll owners with hidden bars. Borders stay fixed while cell content moves; links and selection use translated coordinates. Each first table cell owns its scroll state, retained across append/edit parsing when its block ordinal and source start remain stable. Reveal requests bring the target cell text into the horizontal viewport. Changing a table's source start or block ordinal resets its scroll state. Window-shared selection, touch and horizontal selection edge autoscroll remain separate limitations. Task list markers (`[ ]`, `[x]`, `[X]`) are source metadata rather than selectable text. Partial Source copy reconstructs them after the list marker. Presentation uses a 14px foreground border box, a foreground fill when checked, and the shared 10px checkmark drawing helper; the indicator has no interactive semantics. The checkmark chooses black or white contrast against the supplied foreground, which preserves the source defaults while also supporting custom palettes. Continuations after nested child blocks and nested non-list blocks remain parser limitations. `cui_text_view_decode_resource` decodes the bounded parser entity subset and Markdown ASCII punctuation escapes into a separate caller buffer. HTML attribute backslashes and Plain format bytes remain literal. Link, opener and image callbacks receive decoded, zero-terminated URI bytes borrowed only for the callback; asynchronous loaders must copy them. No URL fetching or URI policy is implicit. Source copy retains original source spelling. Complete HTML5 named entity and URI normalization behavior remains part of the full parser gap. Resource callbacks use at most 64KiB of temporary stack storage, reused across images; entity lookup scans no more than 17 bytes per candidate. List prefix spacing follows measured text, including the trailing space from the source prefix helper. Ordinary markers reserve their full measured prefix width; they do not impose a synthetic minimum or extra gap. Task indicators retain their separate 14px box plus 6px gap. Prefix bytes live in the caller block workspace so draw-command text remains valid through renderer completion. Horizontal table routing consumes horizontal wheel input at an edge or without overflow. Native precise gestures retain their initial axis until an end phase, a 28ms quiet interval, or a strong axis change. The frozen source disables this persistent gesture locking on WASM; ordinary vertical chaining is preserved. Host adapters must provide precise gesture phase metadata explicitly. Markdown list item nesting is tracked with parent block indices, source starts, and independent per-level ordered counters. Nested ordered markers use uppercase letters at depth one and lowercase at deeper levels; zero-start lists retain numeric prefixes. Bullet shapes vary across five depths. Each rendered nesting level adds 16px, while partial Source copy uses parent marker widths to indent children and includes empty ancestor markers for a selection confined to children. The parser supports at most 32 list levels and rejects deeper input transactionally. Nested-child continuations reconnect to their enclosing list item. The first paragraph after a nested list repeats the parent marker or passive task indicator; later paragraphs use the continuation indent. Source copy groups an item's selected paragraphs before its nested lists, while plain copy and selection retain paint order. The bounded serialization order uses at most 8192 16-bit block indices and may take quadratic time in that fixed node bound. Fenced code following an existing list paragraph retains parent membership and removes the opening indentation from content while keeping original byte mappings. It renders in the list continuation column with working code action callbacks. Fences written directly after a list marker are real code blocks with independent list-item metadata: the marker or passive task indicator occupies a separate column, outside the code background. Such code blocks own nested-list ancestry and keep exact source mappings for literal backslashes and subsequent lines. Loose-list spacing and multi-paragraph quote containers are not yet a complete list AST. First-child headings and single-paragraph quotes use real block styles with a separate normal-size list marker column. Following indented headings and quotes remain children of the enclosing item. List ordering is independent of heading level, preserving bullet versus decimal prefixes and subsequent counters. Ordinary list paragraphs join lazy continuation lines with spaces and preserve two-space hard breaks. A following indented paragraph stays attached to its list item, paints at a 16px continuation indent, and does not repeat a task indicator or marker. Partial Source copy prefixes the first selected item paragraph and indents subsequent paragraphs and hard-break lines under its marker. Continuations after nested child lists follow the separate row and copy rules above. Setext headings recognize one or more equals signs or hyphens after a paragraph, including joined paragraph lines. Leading indentation is limited to three spaces. Without an opt-in frontmatter parser, a leading horizontal rule followed by a Setext heading retains Markdown meaning; YAML frontmatter plugins remain absent. Prepared glyph lines use core's explicit no-wrap text leaf so Clay cannot wrap a measured line a second time because of fractional font measurements. Consecutive explicitly prefixed quote lines form one paragraph, with soft lines joined and two-space hard breaks preserved. This works for root quotes, first list-item quotes and indented list continuation quotes. Partial Source copy repeats the quote prefix after a hard break and keeps any surrounding list indent. Blank quote paragraphs, lazy unprefixed quote continuation, and nested quote containers remain outside this bounded paragraph representation. Markdown images in list items retain parent ancestry, ordered counters and Source copy grouping. Standalone Markdown images now use the same one-byte paragraph object flow as mixed images, including default inline sizing, loaded/unloaded slots and list continuation marker rules. Their ranges cover complete image syntax, rather than the former alt-text ranges. Bare root HTML images also use a separate paragraph with an atomic image slot. Exact source inline image flow requires styled font ascent, descent and baseline metrics. In frozen `inline_flow.rs`, each line starts with the body's baseline and descent. An image baseline is clamped to its height from `height / 2 + body_baseline - line_height / 2`; line ascent and descent expand with that baseline, and the image paints at `line_y + line_ascent - baseline`. The optional core font metrics provider now supplies actual body ascent and descent. The body baseline is `(line_height - ascent - descent) / 2 + ascent`. Ready standalone images use this formula and retain a separate logical row extent for list prefixes and following blocks. Pure layout accepts validated optional body metrics. Without a valid provider, images retain top alignment; no size-derived baseline is synthesized. Mixed Markdown images now occupy atomic one-byte span slots. Their host bitmaps reserve horizontal space among text runs and wrap at object boundaries. Default inline height is 75% of the logical line height, with loaded aspect ratio or a square unloaded slot, matching the frozen source. Selection maps each slot to the entire image source syntax, and Source copy preserves that syntax. Title tooltips, standalone-image dimensions and custom object renderers remain unimplemented. Bare root HTML image blocks still retain their earlier alt-text ranges. Tables following existing list content retain parent membership and paint in the 16px continuation column. Column sizing, horizontal viewport clipping and footer action widths use the remaining column width. Source copy emits the table among the parent item's own blocks, indents every table row beneath its marker, and keeps nested child lists after that content. Tables within a list omit inter-block paragraph space; the list still separates from following root content. A final root table also omits trailing paragraph space, matching the document's last-block rule. First-child tables introduced directly by a list marker preserve list-item metadata on the first cell. Other cells and nested children retain that item as their parent. The separate marker column stays outside the horizontal mask and does not move when the table scrolls; table-body snapshots preserve its scroll offset when appending rows. Inline image slots use a single space byte in the rendered selection coordinate space; Plain copy omits that slot, while Source copy writes the original image syntax. No unloaded bitmap is fabricated. Removing the host loader restores a compact square slot without discarding surrounding text or retaining stale pixels. Layout may provide a font-metrics callback keyed by each block's actual font size and style flags. The styled component uses the core provider, so a semibold heading image uses heading metrics rather than regular body metrics. The callback supersedes fixed body metrics and may decline measurement; unavailable or invalid callback metrics use top alignment. Host bitmap validity follows the shared core contract, and invalid loader output becomes an unloaded slot instead of a malformed draw. Each mixed image line expands its logical ascent and descent from the actual body baseline and image baseline. Wrapped following lines begin after that complete logical extent, including fonts whose ascent or descent exceeds the requested line height. Text-only lines retain their requested logical height. Bounded balanced brackets and parentheses recognize linked Markdown images and parenthesized destinations. Quoted titles and angle-delimited destinations no longer become part of the host image URI. A linked image uses its alt source as its link label, activates the host link callback through ordinary capture, and Source copy preserves its enclosing link. The frozen renderer itself ignores the image title (`image_element` takes `_title`), so no image-title tooltip is required. This delimiter parser is not a complete CommonMark grammar. Images inside HTML paragraph, heading and table-cell containers now share the atomic inline flow with neighboring styled text. Linked HTML images also use the ordinary link callback. Missing `src` images inside these containers are skipped. Bare root HTML images use the same sizing rules in their own paragraph. HTML source-range/copy support remains unfinished. HTML container tracking is bounded and does not replace a repairing HTML5 tree parser. Inline HTML image dimensions support finite nonnegative numbers, `px`, and `%`, with width/height attributes taking precedence over matching CSS declarations. Percentages use the logical line height as their base, matching frozen `inline_flow.rs`, rather than viewport width. A single loaded dimension preserves intrinsic aspect ratio; an unloaded width-only image uses the line height, and an unloaded height-only image uses a square. Both dimensions are independent when specified. Invalid declarations fall back to valid CSS or default dimensions. Numeric tokens are bounded to 64 bytes, exponents to ±38, and dimensions to 10,000,000 logical pixels. Zero-sized images retain their selection slot and paint no bitmap. Caller-provided NaN/negative/nonfinite dimensions are rejected before layout mutation. Tall image rows retain their logical origin separately from shifted text bounds, so aligned table cells move all runs together. Both Markdown and HTML standalone images now use one-byte image slots and source default sizing rather than alt-text ranges or unscaled intrinsic pixels. Bare root HTML images retain separate paragraph boundaries and accept the same explicit dimensions as paragraph images. Missing root `src` images are skipped. HTML tag boundaries respect quoted `>` characters and HTML attribute whitespace. HTML `` tags embedded in Markdown use the same atomic run model, decoded URI, explicit dimensions, baseline and enclosing Markdown link behavior. This includes the frozen linked HTML image after a soft newline regression. Missing `src` tags are skipped. Other embedded HTML tags and multiline HTML grammar remain outside this targeted inline-image handling. Plain copy and Ctrl+C omit image slots, matching source paragraph text output. Copying only an image in Plain mode produces no text and leaves the clipboard unchanged. The raw `selected_text` accessor remains a borrowed coordinate slice of `workspace.rendered`, including object slots, valid until the next text mutation; use `copy_document_selection(PLAIN)` for styled presentation or clipboard text. Default Plain clipboard output uses bounded temporary storage when no caller buffer is supplied. Ordinary Source-format Ctrl+C continues to require caller output storage. The frozen implementation selects shared text runs around images and includes images in Source copy when selection spans the adjacent run boundaries. CUI still retains atomic image slots in its low-level coordinate API. Styled pointer selection projects text glyphs instead of independently selecting those slots; full shared-window selection identity remains tracked. Markdown Source copy and selected source ranges include consecutive images at a paragraph boundary when selection begins at the first text byte after leading images or ends at the last text byte before trailing images. Selecting only a middle portion of that text does not include the boundary images. This follows the frozen paragraph's pending-image rule while leaving Plain output and raw selection coordinates unchanged. Optional shared selection uses an application-owned `cui_text_view_selection` and a fixed `cui_text_view_selection_member` array. Initialize the manager, then register each live state with its unique view ID, nonzero scope, stable logical `document_order`, table mode and enabled flag. Registration order does not control copy order. Duplicate state ownership and replacement of a live ID with a different state are rejected. Remove a member **before** destroying its state or workspace; removal clears its selection and removes the retained pointer. The array and manager must also outlive all uses. Re-registering the same ID/state updates its options; disabling the owner clears the active shared selection. For each frame, open the application's nonmodal focus scope matching the member scope, call `cui_text_view_selection_update` once before painting any members, then submit those views with `options.shared_selection` set to the manager and close the application scope. This preserves one event reduction and lets every member paint the same projection. Initial hit testing uses the previous clipped semantic ownership; member geometry becomes available after its first submitted frame. Do not update a scope before its modal/ancestor guards have been submitted. Registration does not create UI or make a disabled member selectable. A cross-view drag retains window anchor/cursor points and projects their row band through each member's retained viewport, vertical scroll and horizontal table scroll. Glyph midpoints follow the frozen window selection band rule. Image slots are not independently selected by this shared projection; text on both sides can still select their Source syntax. Other scopes are not projected. Ctrl+C joins nonempty selected participants with a newline in document order; Source copy uses each document's existing reconstruction. Caller copy storage is recommended for large multi-view selections; capacity failure leaves the clipboard unchanged. Standalone views retain their existing behavior when the manager is absent. Remaining shared-selection gaps include touch handles, comprehensive multi-click coverage across every block kind, content-key resolution across dynamic renderers, cross-view automatic scrolling, and individual image-separated text-run ranges within a paragraph. Projection retains a range for each block/table cell and clips to its viewport, rather than maintaining the source window manager's full inline-run state. Applications must refresh registration enabled flags and call the update before painting; there is no implicit window registry or stale-participant eviction. Styled Ctrl+C and shared copy use `cui_text_view_copy_document_selection`, which serializes selected blocks. Partial Plain Paragraph, Heading and Code selections include the source block's trailing newline. Table cells join with spaces, rows with newlines, and the table adds a final newline. Shared selection joins these participant strings with another newline in document order, preserving the frozen output (two selected one-line paragraphs copy as `first\n\nsecond\n`). Source mode retains Markdown reconstruction without those Plain terminators. `copy_selection(PLAIN)` remains a low-level coordinate slice copy with image slots omitted; it does not serialize document structure. `selected_text` is a borrowed bounding coordinate view and may include unselected gaps in a shared projection. Use document selection copy for source-equivalent styled text output. Shared projection stores separate ranges for wrapped table cells. Selection of one visual row therefore does not pull later wrapped text from a different cell into its copy or highlight. Within one paragraph, separate image-delimited text runs still share one block range; exact per-inline-run state remains tracked. Re-registering an existing member under a different scope or table mode clears its old projection; if it owns the active drag, the manager clears that drag. Changing text discards glyph geometry and projected ranges. Such a member cannot start a shared gesture until it has submitted fresh geometry; retained viewport coordinates alone are insufficient. Ordinary pointer drags now use the same window-point projection as shared selection. Dragging within an image selects no text and copies no Source syntax; a tap on a linked image still activates its link, while a drag cancels that release activation. Reverse text-image-text drags retain their direction and include image syntax in Source copy when adjacent text boundaries are selected. Programmatic `cui_text_view_select` remains the explicit low-level coordinate API and can select an image slot by itself; that does not describe the styled pointer behavior. HTML Source fallback to Plain and unavailable HTML source offsets match the frozen implementation's `effective_format` contract and html5ever's absent source spans; they are not missing HTML reconstruction features promised by that source. Mouse multi-click selection now uses the pinned source character classes and 128-scalar word boundary limit. Double-click selects a word without splitting UTF-8 or crossing image runs; triple-click selects an ordinary paragraph or the visual row in an image-flow paragraph. Higher counts use logical-line boundaries. Plain multi-click copy preserves the chosen text override while Source copy retains Markdown markup. Shared selection clears other members, retains focus ownership and preserves the selection after release. Headless tests cover bounded long words, UTF-8 offsets, whitespace/punctuation, image boundaries, paragraph/row copy, text mutation and shared view ownership. Touch gesture selection and complete coverage of every block/run kind remain unfinished. The website's Markdown example starts with a visible fenced C code block, then shows emphasis, a link, lists, a quote and a table. Select **Scrollable** to constrain the document viewport, or switch **TextView format** to HTML or plain text. Fenced code is parsed and rendered in monospace with the theme's code background; it is separate from the website's copyable C usage excerpt. ## Stream motion policy The frozen `crates/base/src/text/stream_fade.rs` at commit `87d10ae5e1299d1be18670a37570c5402f952e34` defines words with their trailing whitespace as reveal units, or individual Chinese/Japanese/Korean scalars. CUI now exposes this timing through `cui_text_view_motion`, `cui_text_view_set_motion`, and styled `options.custom_motion/options.motion`. The default remains 350 ms, no stagger, ease-out cubic. Linear and ease-in-out cubic are also supported; arbitrary user-defined easing functions are not. Configure state **before** applying an appended document update. Initial document loading normally precedes enabling streaming so existing text appears immediately: This complete headless C11 program needs Core and the TextView components, with no browser or native font adapter. Its assertions verify stagger timing and reduced motion; a real host adds event delivery and draw-list painting: ```c #include "cui/cui_text_view.h" /* Keep this executable verification example active in release builds too. */ #ifdef NDEBUG #undef NDEBUG #endif #include #include int main(void) { static char source[1024], rendered[1024]; static cui_text_view_mapping mapping[1024]; static cui_text_view_span spans[256]; static cui_text_view_block blocks[128]; static cui_text_view_glyph glyphs[1024]; cui_text_view_workspace workspace = { .source = source, .source_capacity = sizeof source, .rendered = rendered, .rendered_capacity = sizeof rendered, .mapping = mapping, .mapping_capacity = 1024, .spans = spans, .span_capacity = 256, .blocks = blocks, .block_capacity = 128, .glyphs = glyphs, .glyph_capacity = 1024 }; cui_text_view_state state; assert(cui_text_view_init(&state, workspace, CUI_TEXT_VIEW_MARKDOWN)); assert(cui_text_view_set_text(&state, cui_string("Before")) == CUI_TEXT_VIEW_OK); cui_context *ui = cui_create((cui_config){0}); assert(ui); cui_text_view_motion motion = { .duration = 1, .stagger = .2f, .easing = CUI_TEXT_VIEW_FADE_LINEAR }; assert(cui_text_view_set_motion(&state, motion)); state.stream_fade = true; /* A real host sets the context preference from its platform settings. */ state.reduced_motion = cui_reduced_motion(ui); assert(cui_text_view_set_text(&state, cui_string("Before one two")) == CUI_TEXT_VIEW_OK); assert(cui_text_view_stream_opacity(&state, 7) == 0); assert(cui_text_view_stream_opacity(&state, 11) == 0); cui_text_view_options options = cui_text_view_default(); options.width = 300; options.stream_fade = true; options.custom_motion = true; options.motion = motion; options.reduced_motion = state.reduced_motion; options.dt = .3f; cui_theme theme = cui_theme_light(); assert(cui_begin_frame(ui, 400, 240, .3f)); assert(cui_text_view(ui, 77, &theme, &state, options)); cui_draw_list draws = cui_end_frame(ui); assert(draws.count && cui_last_error(ui) == CUI_OK); /* The component paints first, then advances its clock for the next frame. */ assert(fabsf(cui_text_view_stream_opacity(&state, 7) - .3f) < .00001f); assert(fabsf(cui_text_view_stream_opacity(&state, 11) - .1f) < .00001f); cui_set_reduced_motion(ui, true); state.reduced_motion = cui_reduced_motion(ui); /* Before the next text update. */ options.reduced_motion = state.reduced_motion; /* Also forward every frame. */ assert(cui_text_view_set_text(&state, cui_string("Before one two three")) == CUI_TEXT_VIEW_OK); assert(cui_text_view_stream_opacity(&state, 7) == 1); assert(cui_text_view_stream_opacity(&state, 15) == 1); assert(!cui_text_view_advance(&state, 0)); assert(cui_begin_frame(ui, 400, 240, .3f)); assert(cui_text_view(ui, 77, &theme, &state, options)); cui_end_frame(ui); cui_destroy(ui); return 0; } ``` Save the complete program as `textview_motion.c`, build the library, then run: ```sh cc -std=c11 -Wall -Wextra -Wpedantic -Werror -Iinclude textview_motion.c build/libcui.a -lm -o textview_motion ./textview_motion ``` Each changed contiguous run within a paragraph/code/table-cell leaf starts its own word timing. Unicode whitespace follows the preceding word; leading whitespace joins the first word. CJK ranges match the pinned source: Hiragana/Katakana, CJK Extension A/unified/compatibility ideographs, Hangul syllables, and ideograph extensions U+20000–U+2FA1F. Every byte of a UTF-8 scalar receives the same birth time. Staggering spans inline formatting within a leaf; it restarts at block and table-cell boundaries. If the last unit would start later than the fade duration, the entire changed run fades as one chunk. CUI uses its existing rendered-byte/format comparison, rather than introducing a full source leaf-identity tracker; more complex reparses can have different chunk boundaries from the frozen implementation. `cui_text_view_stream_opacity` samples the current alpha multiplier without painting. `cui_text_view_advance` continues to request frames until the last delayed unit reaches full opacity. A disabled fade, zero duration, replacement, or reduced motion paints immediately. Replacing text clears unfinished fades in unchanged prefixes too. Invalid negative/nonfinite durations or stagger and unknown easing values fail without changing the state. A zero duration clears pending fades; other policy changes update durations/easing of active fades but do not reschedule already recorded stagger birth times. Set a policy before `set_text` for deterministic new-chunk timing. TextView's state clock is advanced by `options.dt` at the end of component submission, after painting. Supply the elapsed interval once per frame; do not also call `cui_text_view_advance` for that same interval. The pure model API may instead advance explicitly when used without the styled component. `cui_begin_frame`'s dt alone does not advance this model clock. TextView does not implicitly copy `cui_reduced_motion(ui)` into its state/options. Forward the host preference to `state.reduced_motion` before a text update and to `options.reduced_motion` on each submission. This prevents new fade birth times while reduced motion is active and immediately suppresses existing fades. A zero-duration motion clears pending birth times; merely suppressing a fade does not clear them, so unfinished text may resume fading if the preference is turned off before its stored deadline. The styled custom policy is validated before image, link, or composition callbacks run. Headless tests exercise overlapping word timing, delayed animation completion, Latin/CJK/Unicode-whitespace scalar boundaries, oversized chunks, easing values, zero/invalid policies, replacement and reduced motion, Markdown completion, independent table-cell timings, transactional failed parses, and actual text command alpha. Complete parser/plugins, touch selection, shaping and other gaps listed above remain outside this change. ## Callback ownership and timing `on_link(url, event, link_user)` runs synchronously while the matching link is painted. It overrides `open_url`; it does not run in addition to the opener. The event is consumed after callback return. The fallback opener's boolean is currently ignored: returning false still consumes the invocation and does not produce a confirmed navigation result. Primary activation and secondary release are distinct supported paths; selection dragging suppresses link activation. No callback return cancels a transaction or proves an external URL was opened. Decoded URI bytes and the event pointer are borrowed only during the callback. Copy URI bytes into bounded application storage before returning, checking `url.length` against capacity before copying and adding a terminator if needed. Do not retain `url.data`; copying `cui_event` alone does not own optional text data. For example, with a caller-owned `char saved[256]`, accept only `url.length < sizeof saved`, then `memcpy(saved, url.data, url.length)` and `saved[url.length] = 0`. Handle oversize input explicitly; never silently truncate an actionable URI. Copies survive later frames/document replacement independently of the borrowed workspace. `cui_text_view_reveal` queues a programmatic range. In scrollable mode submission adjusts internal scroll and clears the pending request without calling `on_reveal`. In non-scrollable mode a located range calls `on_reveal(window_line, reveal_user)` after layout/reduction and before viewport paint, then clears `reveal_pending`. The callback sees pending=true. Its rectangle uses the retained viewport origin plus the located current line bounds; it is a host scrolling request, not evidence that a parent scrolled. Disabled views and inert/layout parent scopes do not cancel this programmatic service callback. Do not set a replacement reveal from inside that callback: the outer operation clears pending after return. Callbacks may copy payloads and set unrelated application flags. Keep the active view, workspace, shared-selection registrations and context alive; do not reparse, rebind, destroy or recursively submit them during a callback. Apply document replacement or omission only after the outer call and renderer consumption. The view's boolean reports submission success, not link dispatch or selection change. Selection is already applied to caller-owned offsets; no rejectable selection event is implied. Bridge factories do not currently wire these C link/reveal callback hooks. `test_callback_contracts` in `tests/unit/test_text_view.c` covers reveal timing and coordinates, internal-scroll silence, disabled/programmatic parent scopes, link-over-opener precedence, false opener consumption, bounded decoded URI copy surviving reparse, and deferred omission. This is headless source/command coverage; it does not prove native URL opening or completion of host scrolling. --- ## Named theme presets Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/THEME_PRESETS.md # Named theme presets CUI includes 38 named palette adaptations from the pinned upstream kit theme sources: 12 light and 26 dark. The source colors, author metadata, license and revision are retained in `third_party/gpui_themes/`. ```c cui_theme theme; size_t index = 0; if (cui_theme_preset_get(index, &theme)) { cui_str name = cui_theme_preset_name(index); bool dark = cui_theme_preset_is_dark(index); /* Use theme when rendering components. */ (void)name; (void)dark; } ``` Enumerate indices below `cui_theme_preset_count()`. Invalid indices return an empty name and `false`; a failed `get` leaves the output untouched. Returned names have static lifetime. Presets initialize a complete theme, including default metrics and motion settings. Apply application overrides, including an SVG icon loader, after loading a preset. System appearance is a host preference: select the light or dark default when it changes. Named presets are explicit choices and should remain selected across system appearance changes. Persist names rather than indices if preferences must survive catalog reordering. These are adaptations to CUI's semantic color tokens, not a claim of complete upstream theme rendering parity. Missing source tokens use derived colors; button interaction colors are derived where necessary. Font and syntax-highlighting themes are not included. Aurora's unsupported gradient brushes use their first color stop; the generated JSON records affected tokens in `adaptations`. `python scripts/theme_presets.py` regenerates both the portable C table and website JSON from the same pinned palette data. `make lint` checks that these outputs remain synchronized. --- ## Localized TimeField widget (unreleased) Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TIME_FIELD_LOCALIZED.md # Localized TimeField widget (unreleased) The additive C route has passed focused headless interaction/pixel and portable compile checks; it remains unreleased. Legacy TimeField is unchanged. See the [complete Base/Styled program](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TIME_FIELD_LOCALIZED_EXAMPLE.md) and [verification receipt](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/validation/time-field-localized.json). Include `cui/cui_time_field_v1.h` for the new caller-owned state/options route. Use [pure text values](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TIME_FIELD_TEXT.md) for the exact locale grammar and bounds. Initialize options, configure text locale/cycle/precision and inclusive same-day bounds, then initialize one state per widget/context. Keep state and time alive between frames. Options, locale tokens, names, theme and observer are borrowed only through each synchronous call. Change nonzero edit_generation when changing locale/name/domain bytes in place. Mode/value changes reset unfinished input; identical owner echo preserves it. Minute precision requires second0 explicitly. Owner values outside bounds render invalid without being clamped. ```c #include typedef struct { cui_time value; cui_time_field_state_v1 state; cui_time_field_options_v1 options; unsigned notifications; } reminder; static void reminder_changed(void *user, const cui_time_change *event) { reminder *owner = user; /* External application bookkeeping is allowed; active value/state/options * remain borrowed until composition returns. Copy event if retaining it. */ if (event->value.hour >= 9) ++owner->notifications; } static bool reminder_init(reminder *owner) { owner->value = (cui_time){9, 30, 0}; owner->notifications = 0; if (cui_time_field_options_init_v1(&owner->options) != CUI_TIME_TEXT_OK) return false; owner->options.text.flags = CUI_TIME_TEXT_HAS_MINIMUM_V1; owner->options.text.minimum = (cui_time){9, 0, 0}; return cui_time_field_state_init_v1(&owner->state, owner->value, &owner->options) == CUI_TIME_TEXT_OK; } static cui_time_field_result_v1 reminder_compose( cui_context *ui, const cui_theme *theme, reminder *owner) { return cui_time_field_v1(ui, 20, theme, cui_string("Reminder"), &owner->state, &owner->value, &owner->options, (cui_time_handler){reminder_changed, owner}); } ``` Call compose during an ordinary frame. First/gap/recovery submissions establish geometry without applying queued edits. Disabled, readonly, inert and layout-only submissions freeze edits and notifications. Editing uses original-order targeted Core events, copied UTF-8 text payloads, token prefixes across TEXT events and atomic full formatted paste up to160bytes. Preedit/composition and host clipboard shortcuts are not implemented by this widget. No input dispatcher is added. `changed` reports entry-to-final value difference independently of a handler. `change_count` counts actual aggregate callbacks0/1, **not accepted edits**. A net-zero event batch, pending draft, rejected value or focus-only change never notifies. The callback runs after final semantics or complete Styled submission; it receives copied previous/value and UNKNOWN aggregate cause. It cannot mutate active UI/model/state/options/theme/token resources or recursively submit. Validation rejects user candidates without clamping. Inspect result.validation or state.validation; rejected_count counts original rejected events, not digits. A valid edit clears transient validation. Explicit `cui_time_field_clear_validation_v1` clears only that transient state; OWNER_INVALID and an out-of-domain current owner still paint a danger border. Unset OWNER_INVALID only when the application's separate validation clears. All visible segments are ordinary global Tab stops. Forward/backward navigation exits at boundaries; the widget does not consume Tab or trap focus. This differs from the upstream one-root focus/selection-retaining behavior, which remains unfinished. Full source size/focus-ring styling, localized DateTimePicker, IME, physical native accessibility and Python/JS/TS/Go/Rust options/events remain open. Old scalar bindings and old by-value options/aggregate callbacks retain their existing behavior. See [design and test contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/TIME_FIELD_LOCALIZED_WIDGET_V1.md). The gallery's TimeField source uses this route by default with Arabic token, 12-hour/seconds, inclusive-bound, readonly and invalid-appearance controls, plus live value/change/validation labels. Its C translation unit has been compiled; actual combined WASM rendering and browser interaction are integrator validation, not established by this worker's native proof. Choose one side-effect path: observe the copied aggregate through `cui_time_handler`, or branch on result.changed after submission. Doing both should not apply the same application side effect twice. The widget has already mutated the time through its pointer; do not reapply the callback payload. Check result.status for operation errors and result.validation for rejected-edit state. This does not imply uniform typed observer support in foreign bindings. --- ## Complete localized TimeField composition example Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TIME_FIELD_LOCALIZED_EXAMPLE.md # Complete localized TimeField composition example **Unreleased C example, compile-tested and run headlessly in Base/Styled modes.** The exact code below is also [examples/time_field_localized.c](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/time_field_localized.c). Focused checks use the new widget translation units with the current cached engine, without rebuilding the engine. This does not establish release, browser or foreign-language support. See [widget contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/TIME_FIELD_LOCALIZED_WIDGET_V1.md), [widget usage](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TIME_FIELD_LOCALIZED.md) and [pure text helpers](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TIME_FIELD_TEXT.md). The complete C program below creates a real Core UI, authors either Base semantics with explicit boxes or Styled paint, configures localized parsing and inclusive bounds, and processes a queued edit. It has no native window/runner. A host can use the same compose function inside its ordinary frame and render the returned draw list. It must keep the context, model and borrowed resources alive through synchronous composition/rendering. ```c #include #include #include typedef struct { cui_time value; cui_time_locale_v1 locale; cui_time_field_options_v1 options; cui_time_field_state_v1 state; unsigned notifications; cui_time_change last_change; } reminder; static void changed(void *user, const cui_time_change *change) { reminder *owner = user; /* External owner bookkeeping is allowed. The active value/state/options, * theme, token storage and UI remain borrowed until compose returns. */ ++owner->notifications; owner->last_change = *change; /* Owned scalar copy, no borrowed text view. */ } static bool initialize(reminder *owner) { memset(owner, 0, sizeof(*owner)); if (cui_time_locale_init_v1(&owner->locale) != CUI_TIME_TEXT_OK || cui_time_field_options_init_v1(&owner->options) != CUI_TIME_TEXT_OK) return false; static const char *digits[10] = {"٠", "١", "٢", "٣", "٤", "٥", "٦", "٧", "٨", "٩"}; for (unsigned i = 0; i < 10; ++i) owner->locale.digits[i] = cui_string(digits[i]); owner->locale.separator = cui_string("·"); owner->locale.am = cui_string("ص"); owner->locale.pm = cui_string("م"); /* The initializer's exact period separator is one ASCII space. All14 * tokens are nonempty, <=16 UTF-8 bytes and pairwise prefix-free. */ owner->options.text.locale = &owner->locale; owner->options.text.cycle = CUI_TIME_TEXT_H12; owner->options.text.precision = CUI_TIME_TEXT_SECOND; owner->options.text.flags = CUI_TIME_TEXT_HAS_MINIMUM_V1 | CUI_TIME_TEXT_HAS_MAXIMUM_V1; owner->options.text.minimum = (cui_time){9, 0, 0}; owner->options.text.maximum = (cui_time){17, 30, 0}; owner->options.segment_names[0] = cui_string("ساعة"); owner->options.segment_names[1] = cui_string("دقيقة"); owner->options.segment_names[2] = cui_string("ثانية"); owner->options.segment_names[3] = cui_string("فترة"); /* Pure parsing is explicit: no ASCII fallback, case folding or OS locale. */ if (cui_time_parse_v1(cui_string("٠٩·٣٠·٠٠ ص"), &owner->options.text, &owner->value) != CUI_TIME_TEXT_OK) return false; return cui_time_field_state_init_v1(&owner->state, owner->value, &owner->options) == CUI_TIME_TEXT_OK; } static void base_boxes(cui_context *ui) { /* Base submits semantics only. The application supplies actual boxes with * the same root/part IDs; this example displays all four configured parts. */ cui_begin_box(ui, 20, (cui_box){.row = true, .gap = 4}); for (unsigned i = 0; i < 4; ++i) { cui_begin_box(ui, cui_time_segment_id(20, i), (cui_box){.width = 60, .height = 32}); cui_end_box(ui); } cui_end_box(ui); } static cui_time_field_result_v1 compose(cui_context *ui, const cui_theme *theme, reminder *owner, bool styled) { cui_time_handler observer = {changed, owner}; if (styled) return cui_time_field_v1(ui, 20, theme, cui_string("Reminder"), &owner->state, &owner->value, &owner->options, observer); cui_time_field_result_v1 result = cui_base_time_field_v1( ui, 20, cui_string("Reminder"), &owner->state, &owner->value, &owner->options, observer); if (result.status == CUI_TIME_TEXT_OK) base_boxes(ui); return result; } static bool frame(cui_context *ui, const cui_theme *theme, reminder *owner, bool styled, cui_time_field_result_v1 *result) { if (!cui_begin_frame(ui, 640, 200, .016f)) return false; cui_begin_box(ui, 100, (cui_box){.padding = 12}); *result = compose(ui, theme, owner, styled); cui_end_box(ui); cui_draw_list draw = cui_end_frame(ui); /* A real host renders draw synchronously here. Base boxes intentionally * have no product styling; Styled supplies visible text/background/border. */ (void)draw; return result->status == CUI_TIME_TEXT_OK && cui_last_error(ui) == CUI_OK; } int main(int argc, char **argv) { bool styled = !(argc > 1 && strcmp(argv[1], "base") == 0); reminder owner; if (!initialize(&owner)) return 1; cui_context *ui = cui_create((cui_config){.width = 640, .height = 200}); if (!ui) return 1; cui_theme theme = cui_theme_light(); cui_time_field_result_v1 result; /* First submission establishes geometry; the next ordinary frame admits * input. Never invent a frame generation or replay the first input. */ bool ok = frame(ui, &theme, &owner, styled, &result) && frame(ui, &theme, &owner, styled, &result); if (ok) { cui_focus(ui, cui_time_segment_id(20, CUI_TIME_FIELD_MINUTE_V1)); ok = cui_queue_event(ui, (cui_event){.type = CUI_EVENT_KEY_DOWN, .key = CUI_KEY_UP}) && frame(ui, &theme, &owner, styled, &result); } if (ok) { printf("%02u:%02u:%02u changed=%d callbacks=%zu validation=%u\n", owner.value.hour, owner.value.minute, owner.value.second, result.changed ? 1 : 0, result.change_count, (unsigned)result.validation); } cui_destroy(ui); return ok ? 0 : 1; } ``` To reproduce after the matching implementation is integrated, save the code as `time_field_example.c` in a consumer directory. A C11 compiler, CMake and Ninja are prerequisites; see [dependencies](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DEPENDENCIES.md). With `CUI_ROOT` pointing to the matching CUI source checkout, the intended portable commands are: ```sh cmake -S "$CUI_ROOT" -B build-cui -G Ninja -DCUI_BUILD_NATIVE=OFF cmake --build build-cui --target cui --parallel 1 cc -std=c11 -Wall -Wextra -Wpedantic -Werror -I"$CUI_ROOT/include" \ time_field_example.c build-cui/libcui.a -lm -o time_field_example ./time_field_example ./time_field_example base ``` The sample's exact C code was compiled strictly and run in both modes against the cached matching engine plus the new widget objects. The complete portable CMake rebuild recipe above was not run by this worker; the integrator validates the actual combined targets. This is a windowless consumer, not a native runner or a renderer support claim. Automated native tests still use the repository's private-Xvfb `scripts/test_local.py` wrapper; never use the desktop display. ## Ownership, resets and validation Keep one state per widget/context. Do not copy/move this `reminder` after wiring `options.text.locale` to its embedded locale, unless you repair that pointer outside composition. Literal strings have static lifetime; dynamically supplied strings must remain valid and immutable through each call. No token pointer is retained in state. No callback may mutate the active model, state, options, theme, UI or token bytes; external bookkeeping/copied payloads and queued future work are allowed. The callback is an applied aggregate notification, not a veto. `edit_generation` starts at1 and must stay nonzero. Change it outside composition when editing locale/name/domain bytes in place; the next ordinary writable pass clears unfinished token/digit input and validates the owner again. Cycle and precision changes are detected independently. An identical owner echo preserves unfinished digits; a changed owner value, real focused-segment change, omission/ gap, mode/generation change or final focus outside the widget clears them. Changing to minute precision requires explicitly setting owner.value.second=0; the widget never hides or silently truncates seconds. Bounds are inclusive same-day limits, not overnight wrap. Invalid user candidates leave the model unchanged and report validation/rejected_count. An out-of-bounds owner value is displayed invalid, never automatically clamped. A complete valid formatted TEXT payload replaces the whole value atomically (up to160 UTF-8 bytes); Core copies queued text_data, and callbacks receive copied scalar values. A split token prefix is bounded to16 owned bytes and cannot carry across a genuine focus change. IME preedit/composition and clipboard shortcuts remain unsupported. `result.status` is operation/preflight status. `result.validation` is the current edit validation outcome. `changed` means entry-to-final value difference whether or not a handler exists; `change_count` is actual callbacks0/1, **not accepted edits**. Several edits ending at the entry value produce changed=false and no callback. Rejection/draft/focus-only changes do not notify. Base notifies after semantics; Styled after paint submission. The Base companion's application boxes are composed after the Base call and are not part of that Base callback promise. For separate owner validation set OWNER_INVALID. Clear it when the application's validation succeeds. `cui_time_field_clear_validation_v1` clears transient edit validation only; an out-of-domain owner or OWNER_INVALID still gets the invalid border. Disabled, readonly, inert and layout-only paths freeze edits/callbacks; reenabling or reappearing first establishes healthy geometry. ## Explicit remaining scope All visible segments use existing ordinary global Tab stops. Forward/backward boundary traversal exits the field without consuming Tab; source one-root focus and selection-retaining re-entry remain unfinished. Legacy functions keep their old Tab, by-value options/state and CHANGE timing. Full source size/focus-ring styling, localized DateTimePicker, IME and physical accessibility are not closed. | Language | New localized widget/options/typed observer | | --- | --- | | C | Focused C widget/example checks passed; unreleased | | Python | Omitted; legacy scalar widget subset only | | JavaScript | Omitted; legacy scalar widget subset only | | TypeScript | Omitted; legacy scalar widget subset only | | Go | Omitted; legacy scalar widget subset only | | Rust | Omitted; legacy scalar widget subset only | Verified focused gates cover Base/Styled interactions and both example modes, split/coalesced input and actual focus transitions, copied UTF-8 paste and atomic range rejection, software border pixels/text-poison ownership, C++/WASM headers and source, and configured selective/umbrella module consumers. See the [receipt](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/validation/time-field-localized.json) for exact commands/limitations. Full combined engine/CMake acceptance and actual gallery WASM/browser checks remain integrator gates; no deployment or full-family claim is made. --- ## TimeField text values (unreleased) Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TIME_FIELD_TEXT.md # TimeField text values (unreleased) `cui/cui_time_text.h` provides pure C locale-aware time parsing, formatting and inclusive same-day bounds validation. These helpers do not change or localize the existing TimeField widget. Its legacy parser/formatter and typed aggregate CHANGE observer remain available; see [TimeField events](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TIME_FIELD_EVENTS.md). No foreign binding exposes these records yet. Initialize `cui_time_text_options_v1` with `cui_time_text_options_init_v1`; NULL locale selects ASCII digits, colon and uppercase AM/PM separated by one space. Select H23/H12 and minute/second precision explicitly. Parsing consumes exactly two digit tokens per numeric segment and the entire input. H12 requires the configured period; no whitespace trimming or case folding occurs. Minute precision rejects nonzero seconds in values/active bounds; it never silently truncates the model. Bounds are inclusive; minimum greater than maximum is invalid configuration, not an overnight range. A custom locale supplies ten digits, separator, period separator, AM and PM as borrowed `cui_str` tokens. Each token is1..16 UTF-8 bytes, contains no NUL, and all14 must be pairwise prefix-free. Locale/options/token storage stays immutable through each synchronous call; nothing is retained. No locale registry, OS lookup, allocation, IME composition or Unicode normalization is provided. ```c #include static bool parse_reminder(cui_str text, cui_time *reminder) { cui_time_text_options_v1 options; if (cui_time_text_options_init_v1(&options) != CUI_TIME_TEXT_OK) return false; options.flags = CUI_TIME_TEXT_HAS_MINIMUM_V1 | CUI_TIME_TEXT_HAS_MAXIMUM_V1; options.minimum = (cui_time){9, 0, 0}; options.maximum = (cui_time){17, 30, 0}; return cui_time_parse_v1(text, &options, reminder) == CUI_TIME_TEXT_OK; } ``` Parser failure leaves the output unchanged. Formatter output is atomic too: query required bytes with NULL output/capacity0, then provide at least required+1 bytes. Length excludes NUL. Insufficient capacity returns BUFFER_TOO_SMALL and reports required bytes without touching the buffer; other failures also leave the required-length output unchanged. Writable outputs must not overlap each other, records or borrowed strings. Maximum formatted text is160 bytes plus NUL. See the public header and [reviewed contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/TIME_FIELD_COMPLETION.md) for exact failure precedence. This is a partial pure-value slice. New editor typing/navigation, validation appearance, localized widget/DateTimePicker presentation, all five bindings, IME and host accessibility remain separate work. --- ## Toolbar and ToolbarGroup Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TOOLBAR.md # Toolbar and ToolbarGroup Toolbar is a transparent horizontal command container. It exposes Toolbar semantics, preserves ordinary Tab traversal through its controls, and handles unconsumed Left/Right keys after its children render. Focus wraps among enabled Tab stops in the scope, including nested groups. Nested toolbars handle their own keys first. Hosted inputs retain caret navigation when their input behavior consumes those events. The toolbar itself is passive. `disabled` suppresses only its navigation; applications disable hosted controls individually. This implementation follows the frozen upstream kit 0.7.1 `base/src/toolbar.rs` and `component/src/toolbar.rs`. The website mentions vertical navigation, but the actual source fixes orientation to horizontal and handles Left/Right only; CUI follows that implementation. `cui_toolbar_default()` selects Small. XSmall uses height 28, padding4, gap4, font12, and sized wrapper 20. Small uses 32/4/4/14/24. Medium uses 48/8/8/14/32. Large resolves to Medium. Custom preserves its numeric size for control callbacks while using Medium bar geometry and a 24px sized wrapper, matching the source's wildcard cases. Invalid enum/nonfinite/negative custom values fail before submitting the container. Arrays are bounded at 1024 items and borrowed for the call; no persistent allocations are required. Each item has a render callback. Sized items receive `prepared=true`, final metrics, and a centered fixed-height wrapper with a distinct nonzero ID. Their callback implements the control-specific `prepare_for_toolbar` hook before applying the final size; arbitrary C callbacks cannot be mutated automatically. Unsized content gets `prepared=false` and no wrapper. Items render in source order. A nested group callback forwards the presentation metrics into group options to inherit the enclosing size. Group carries passive Group semantics and an optional accessible label, lays out children horizontally and centered, and adds no padding or gap. Its owner supplies spacing and disables controls. `cui_toolbar_command_render` is the supplied sized-command callback: it renders an actual compact ghost button, uses controlled selected/disabled state, separate visible and accessible names, an optional icon callback, and validated pointer/keyboard activation. A label-less command requires an accessible name. Host tooltip display remains an application integration; the renderer does not invent a tooltip from invisible text. Icon rendering and callbacks are borrowed for the render call. Custom label commands retain natural content height and 20%-of-size horizontal padding; custom icon commands are square, as in source. `custom_box=true` supplies a complete container layout/style replacement, rather than guessing which zero fields in a C aggregate mean a style refinement. It can add a background/border or override dimensions, but its owner must preserve the source's intended horizontal layout when desired. Default containers have no background/border and never shrink their fixed height. The surrounding header or pane owns the surface. The base begin/end API accepts application-owned layout and supports arbitrary children without the styled layer. Pair end only after a successful begin. A base toolbar opens a nonmodal focus scope; a base group adds semantics without owning navigation. All pointer, focus, modal, clipping and inert rules come from core. Arrays/callbacks/state belong to the application; no platform or Clay types appear in the public API. --- ## Tree Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TREE.md # Tree `cui_tree.h` adds a retained bounded hierarchy, independent headless behavior and an ordinary styled Tree. Nodes are a preorder array of nonzero stable keys, borrowed labels, depths and disabled flags. The first depth is zero, depth increases by at most one and the maximum is 63. Application-owned expansion flags and selected key remain controlled. Nodes/labels must remain immutable and alive until a successful rebuild; changing expansion flags externally requires rebuilding the visible projection. Create a model with capacity up to 100,000 nodes. Two preallocated banks hold hierarchy, visible projection and key lookup. Rebuild validates depth/keys and swaps banks only on success, preserving the preceding model on capacity, duplicate-key or invalid-input errors. There are no allocations after create. Node lookup uses a bounded open-addressed key table; parent and branch lookups are constant time. Rebuild and expansion changes flatten the hierarchy in linear time. The memory-byte accessor reports model-owned allocations. The array representation also lets an application replace asynchronously loaded data without a platform-specific filesystem dependency. Rows select and report activated keys through ordinary pointer or Enter/Space activation. Separate expand buttons toggle branches. Up/Down moves between enabled visible rows, Home/End selects endpoints, Left collapses or moves to an enabled parent, and Right expands or visits an enabled direct child. Consecutive events reduce in input order. Selection follows navigation unless manual selection is requested. Disabled rows cannot activate/navigate; enabled descendants of an externally expanded disabled parent remain independent. Collapse preserves a hidden selected key until the application or a later selection changes it. ASCII typeahead supports accumulating prefixes, a 750 ms timeout, wrapping and repeated-letter cycling; Unicode case folding is pending. Semantic snapshots identify TREE and TREEITEM roles, stable parent relationships, expanded/selected/disabled details and a roving Tab stop. Expand controls are pointer/programmatic focus targets with no additional Tab stops. Native accessibility bridges and set-size/position metadata remain pending. Fixed-height virtualization computes the visible/overscan range arithmetically and emits only that window. Scroll state accepts fractional logical pixels. The styled renderer uses clipped child translation, preserving both the tree clip and its ancestor clips. Overscan rows above/below the viewport cannot receive pointer activation. Keyboard navigation scrolls the active cursor into view; wheel events update controlled scroll state. Separate reduce/submit APIs let custom renderers apply the final scroll offset before registering semantics inside their clipping ancestor. The combined base function emits no draw commands. Variable row heights, automatic tree scrollbar chrome and retained scroll anchoring across arbitrary external reorders remain pending. The styled Tree paints indented theme-colored rows, textual expand/collapse affordances, selected surfaces and focus borders. Its base model and public node accessors support application-specific row painting. Icons, custom row callback convenience, context menus and drag/drop are not implemented; none are claimed by the parity manifest. Tests cover transactional rejection and preserved models, parent/subtree structure, expand/collapse, a 10,000-node viewport and 1,000 deterministic expansion rebuilds compared with an independent ancestor scan. Routed keyboard/pointer tests run all four themes and verify multiple navigation events, disabled skipping, direct-child/parent behavior, expansion controls, typeahead/repeated letters, activation, manual selection and semantic hierarchy. Fractional-scroll tests verify measured row positions and reject overscan pointer targets. The same event suite builds with `CUI_TREE_BASE_ONLY`, links only core/base Tree and emits no draw commands. Strict C11 warnings, fully instrumented ASan/UBSan and existing CTest pass before submission. Build/distribution registration belongs to the integrator. The root exposes scroll offsets and extents for core wheel routing. Wheel events apply only when routed to this Tree; ancestor boundary bubbling is handled by core. Scrolling does not repeatedly reveal the focused row; keyboard navigation reveals it again. Tree-item semantics include the one-based hierarchy level. Items expose one-based hierarchy level, sibling position and sibling set size, including disabled siblings and siblings outside the virtual window. Parents remain logical keyed relations even when their row is unmounted by virtualization; a DOM adapter cannot resolve an unmounted parent element directly. Sibling metadata is computed during rebuild, without rescanning the hierarchy during rendering. --- ## Retained keyed variable-height virtualization Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/VIRTUALIZATION.md # Retained keyed variable-height virtualization `cui/cui_virtual.h` exposes a retained `cui_virtual_list`, separate from the existing stateless linear `cui_virtualize` utility. The application declares a maximum row capacity and positive default height at creation. The handle owns fixed arrays, a Fenwick tree, and two key tables; rebuilds, queries, updates, anchor capture, and anchor restoration do not allocate. `cui_virtual_memory_bytes` reports its requested allocation bytes, excluding allocator bookkeeping. Rebuild supplies the ordered stable 64-bit keys, including key zero. Duplicate keys, excess row count, nonfinite/nonpositive heights, and unsupported totals reject the entire rebuild without changing the current list. Supplying NULL heights retains each old measurement by key across insertion, removal, and reordering; new keys receive the default height. Supplying heights explicitly replaces all measurements. Rebuild constructs the new key table and tree in O(capacity + row count) work, with expected constant-time key lookup from a mixed open-addressed hash table at less than 50% load. Adversarial key collisions can degrade hash lookup; the Fenwick operations retain their logarithmic bound. `cui_virtual_offset(index)` returns the height before that row. `cui_virtual_lower_bound(offset)` returns the first row whose bottom exceeds the offset, with row count representing the end. Prefix offsets, updates, and lower-bound searches are O(log N). Key height updates combine the key lookup with the tree update. Heights are logical pixels stored as doubles. Zero-height rows are rejected. Totals above DBL_MAX/2 are rejected; like other floating geometry, extremely disparate magnitudes can lose subpixel precision, and repeated updates can accumulate rounding error. Viewport ranges are half-open `[begin,end)`, with optional overscan measured in rows on both sides. The range reports top and bottom spacer heights, total extent, and scroll clamped to `[0,max(total-viewport,0)]`. A row beginning exactly at the viewport's bottom is excluded. Negative or nonfinite query scroll/viewport values normalize to zero. A zero viewport has an empty visible range before overscan. No rows need to be materialized to query the range. Capture an anchor before changing measurements or rebuilding: it stores the row key and offset within that row. Restore looks up the same key in the new order and clamps its within-row offset to its new height. If the key was removed, it uses the captured ordinal, clamped to the remaining rows. Restored scroll is clamped to the new viewport extent. An empty list or invalid anchor restores zero. This supports stable scroll positioning during reorder, resize, and measurements; applications decide when to capture and restore. This model does not create a styled Virtual/ScrollArea widget, own scrollbars, handle focus for unmounted controls, perform asynchronous measurements, or implement keyboard navigation. Those behaviors require a later widget layer that submits the returned rows and spacers with stable IDs. It is an efficient data/geometry model, not a full component parity claim. Tests compare 20000 deterministic updates and queries against a linear reference, and cover exact boundaries, viewport overscan, keys including zero, retained measurements after reorder/removal, anchors, transactional rejection, empty lists, and oversized configurations under ASan/UBSan. A portable `clock()` benchmark compiled with GCC `-O2` in this workspace measured: | Rows | Rebuild | 100000 offset + lower-bound + update triples | Allocation bytes | | ---: | ---: | ---: | ---: | | 1000 | 0.035 ms | 6.851 ms | 105648 | | 10000 | 0.612 ms | 9.909 ms | 1448688 | | 100000 | 7.134 ms | 15.627 ms | 12388720 | These are local CPU timings, not performance guarantees. Run `test_virtual --benchmark` to reproduce on the current machine. Normal tests impose no timing threshold. ## Browser demonstration The VirtualList gallery composes the retained model with `cui_scrollable_begin`/`cui_scrollable_end_ex`. It submits a top spacer plus only the viewport range and one overscan row on each side. The fixed 144px viewport shows 24px tasks; an unaligned scroll can require seven intersecting rows and two overscan rows, at most nine of 100,000. Stable task keys provide row IDs and list-item position semantics. Wheel over the list, click or drag its scrollbar, or focus the scrollbar and press Home/End or arrow keys. The live submission count makes virtualization visible. The demo does not add asynchronous measurement, offscreen item focus, or drag-and-drop behavior to the model. --- ## VirtualList model and styled adapter Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/VIRTUAL_LIST.md # VirtualList model and styled adapter `cui_virtual.h` remains a standalone C11 variable-height model: compile `src/base/cui_virtual.c` with the C runtime and math library, without Core, Scroll, Theme, or a renderer. It stores stable keys and heights, supports keyed rebuilds, retains measurements by key, and uses prefix sums for offsets, visible ranges, height updates, and anchor capture/restore. Duplicate keys and invalid heights reject atomic rebuilds. Memory is proportional to the configured model capacity; virtualization bounds rendered rows, not model memory. `cui_virtual_scroll_to` calculates Top, Center, Bottom, or Nearest placement for an item and clamps to the content bounds. Invalid arguments preserve the output. For a horizontal widget, Top/Bottom mean left/right. An oversized item uses its start edge for Nearest. Apply the returned value to the widget's main scroll coordinate. The model uses double precision; the existing UI scroll state uses float coordinates, so very large scroll offsets lose subpixel resolution. Include `cui_virtual_scroll.h` for the optional interaction and styled adapter. Compile `src/base/cui_virtual_scroll.c` with Core, the virtual model, and base Scroll. It resolves the model's main content extent, delegates wheel gestures and scrollbar behavior to existing scroll infrastructure, and adds keyboard scrolling for the focusable owner: Home/End, PageUp/PageDown, and main-axis arrows. Compile `src/components/cui_virtual.c` with the styled Scroll component for `cui_virtual_list_draw`. These dependencies are explicit; the model-only source retains its previous independent linkage. ```c cui_virtual_widget_state state = {0}; /* Persistent, caller-owned. */ cui_virtual_widget_options options = { .scroll = {.width = 320, .height = 240, .wheel_step = 48}, .overscan = 2, }; /* Inside a frame; model and theme are borrowed. */ cui_virtual_widget_result result = cui_virtual_list_draw( ui, list_id, theme, model, &state, options, render_item, user); ``` The item callback receives its index, stable key, wrapper ID, and exact logical size. It runs only for the model window, including explicit overscan. Content is placed inside a fixed-size clipped wrapper; callback content does not change the model height. Include desired inter-row spacing in the model extents, since the scroll option's gap must be zero. Keep keys and heights unchanged during a draw; measure or update them before the next frame. No per-frame allocation occurs in the adapter. Model storage and host row resources remain caller-controlled. By default the adapter is vertical. Set `options.horizontal = true` to interpret model heights as horizontal item widths. Vertical lists can enable cross-axis horizontal scrolling through `scroll.horizontal` and `scroll.content_width`; horizontal lists can enable vertical scrolling through `scroll.vertical` and `scroll.content_height`. The main extent always comes from the model. Scrollbar visibility, wheel step, axis locking, and precise gesture locking use the existing Scroll options. Zero dimensions retain Scroll's 320 by 240 defaults. Invalid options, a nonzero gap, or main totals beyond one quarter of the float range reject before callbacks and scroll-state mutation. Rows use IDs derived from the list root and the stable key, so reordering does not change their identities. Use distinct child IDs inside callbacks; do not submit another painted wrapper with the supplied row ID. The scroll owner has focusable group semantics, and rows have passive list-item semantics with parent, position, and total count. Overscan rows are also represented. These are partial virtual children, not a fully materialized accessibility tree. Set `no_item_semantics` when the host supplies its own row semantics. Selection, row activation, focus retention for offscreen controls, and domain labels belong to the host. Keyboard scrolling does not intercept keys targeted at row controls. Rows are positioned using model offset minus scroll in double precision before converting to local float coordinates. This avoids large spacer elements and cancellation of small row differences at large global offsets. Precise wheel input retains fractional scroll amounts within the float state's resolution. When a nested child defers a wheel event after row callbacks ran, the adapter updates this frame's translation, sets `window_pending`, and invalidates the UI. The next frame renders the new window. `result.view` describes the callbacks that ran, including overscan; `state.scroll` holds the final scroll position. Verified scope: both orientations, variable extents, keyed reorder identity, visible-window callback bounds, overscan, cross-axis scroll, precise wheel motion, owner and scrollbar keyboard scrolling, disabled behavior, invalid-input state preservation, empty models, nested deferred scroll translation, large local row positions, and software clipping. The frozen upstream kit reference also supports intrinsic cross-axis measurement, sizing behaviors, deferred scroll strategies, and richer scroll-handle integration. CUI requires precomputed main extents; selected-row intrinsic measurement and Auto/Infer sizing are described below. It does not automatically measure render callbacks or guarantee focus restoration for virtualized children. This adapter is a tested vertical slice, not a claim of full VirtualList parity. Intrinsic cross sizing and Infer sizing ------------------------------------- The frozen upstream implementation measures one selected row, rather than every row, to obtain the cross extent. The styled CUI adapter now supports this via `options.measure`: a host callback receives the clamped `measure_index`, stable key, and previous vertical viewport width (zero means unconstrained). Horizontal measurement is unconstrained. It returns an intrinsic `cui_size`; the model continues to own every main-axis item extent. Empty lists skip measurement. Explicit content cross dimensions override the measured cross dimension. Measurement runs once each styled draw, before any scroll state mutation. Failure or nonfinite/negative measured dimensions rejects that draw. Hosts must keep model keys/heights unchanged during measurement as during rendering. `CUI_VIRTUAL_SIZE_INFER` resolves each viewport dimension from explicit scroll width/height, then `available`, then intrinsic content extent. An otherwise empty axis uses a one-pixel minimum because the scroll API reserves zero for its legacy default. `CUI_VIRTUAL_SIZE_AUTO` remains the zero/default behavior with 320 by 240 fallback dimensions. The drawing-free reducer can use Infer with explicit content cross dimensions; it does not invoke host measurement. This is explicit host measurement, not automatic offscreen measurement of render rows. The adapter does not reproduce the upstream horizontal Infer implementation's use of known width when resolving height: explicit width and height remain independent. --- ## Spinner frozen-source parity audit Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/audits/SPINNER_PARITY.md # Spinner frozen-source parity audit Audit target: CUI `7b2b8f85905880adab3ac493a8c7103a582d6fb5`. Reference: upstream kit 0.7.1 `87d10ae5e1299d1be18670a37570c5402f952e34`. This is an evidence map, not a ledger promotion or a new component family. Follow-up at next39 (base `e6e4bb68`) implements the three bounded motion/size corrections below. Follow-up at base `ab8fddbb` adds actual-WASM proof for finite turns, reduced ease(0), nonfinite rejection and named-rem/custom-pixel sizing. Inherited Icon/bridge and the explicitly listed broader proof gaps remain open. **Recommendation: retain tested/partial; do not mark the entire family verified.** ## Source authority The clean local reference checkout is `/tmp/cui-upstream-reference` at the exact frozen commit. Relevant source: - `crates/component/src/spinner.rs`: constructor at line 20, icon at 35, color at 41, easing at 47, Sizable at 53, rendering at 61 and reduced-motion regression at 91. - `crates/component/src/icon.rs`: owned/shared SVG data at 136, replacement transform at 158, Icon resolution at 175, size resolution at 188 and Styled at 204. - `crates/component/src/sizing.rs`: Size at 6 and Sizable at 190. - `crates/story/src/stories/spinner_story.rs`: presets/custom 64, LoaderCircle, custom colors, linear/bounce/quint easing examples. - `website/component/spinner.md`: frozen docs hash `a19b69831b06d9349ed8ed70b0f8bea0110bb03abebc46eea976fda7e7d8aacf`. Spinner source SHA256: `96d8c6f1b168fc2c01061c319f943349240497c7d03dc875c86bf370899991bc`. Its runtime animation implementation is locked by upstream Cargo.lock line 4094 to `upstream-pre 0.3.8`; the cached `/tmp/cui-upstream-pre-0.3.8.crate` SHA256 matches the lock checksum `d7f0bc3ebba070f8981b3f8e905a12f47d27794a30d029e59cdb9edf7a4b3360`. See its `src/elements/animation.rs`: unclamped easing at 60, reduced motion at 407, callback invocation at 444 and quadratic easing at 516. This matters for the two concrete behavior differences below; inspecting only Spinner's wrapper misses them. ## Contract and evidence map | Frozen contract | Local implementation | Existing evidence and boundary | | --- | --- | --- | | Default Loader SVG, Medium, foreground, 0.8s quadratic repeating rotation | `include/cui/cui_content.h:229`, `src/base/cui_status.c:337`, `src/components/cui_content.c:735` | `test_status_motion.c` checks default options, sample angle, real mask/software pixels; `test_spinner_contract.c` checks default tint and decorative semantics. Default Loader and LoaderCircle embedded bytes exactly match frozen assets. | | Alternate LoaderCircle and arbitrary compatible Icon | `cui_spinner_options.paint`, `cui_icon_named`, caller-owned `cui_icon_state` | `test_spinner_contract.c` rotates loader-circle/arrow-right and checks raster changes; `test_status_motion.c` checks custom callback arguments. Generic raw-data/path ownership is tested by `test_icon.c`, not by a combined Spinner raw-data fixture. | | XS/S/M/L plus custom pixels | `options.size` gives explicit pixels; `cui_icon_spinner` separately supports `cui_icon_options` presets/rem | `test_spinner_contract.c` covers 12/14/16/24/64 at one root scale; gallery covers the same choices. The additive `cui_spinner_sizing` now preserves named rem versus custom pixels; native descriptor tests cover rem 16/20/32, including custom paint. `test_spinner_contract_gallery.py` checks rem 0/16/20/32 and fixed pixels through default/custom painters in actual WASM. | | Explicit color, otherwise custom Icon color/ambient foreground | `options.custom_color/color`, theme foreground, arbitrary painter | Explicit/transparent colors and ancestor opacity pass software/gallery checks. Ambient text-scope inheritance remains unsupported by Core/Icon; custom Icon style precedence must be assembled by the painter. | | User-provided easing | `cui_loading_motion_sample`, callback user data | Standard default/linear timing and invalid-result atomicity are tested. Spinner now accepts all finite turns and reduces before radians; the legacy shared sampler/Skeleton remain bounded. | | Reduced motion: static repeating animation, no requested frame | context/option reduced motion, inactive result and zero wake | Native/software and real gallery tests prove quiescence/static default output. Spinner now evaluates custom ease(0) and preserves no-wake behavior; native and actual-WASM tests cover shifted angles, nonfinite failure and zero wake. | | Decorative/no native loading status or focus stop | `cui_spinner_ex` submits decorative Icon | `test_spinner_contract.c`, `test_status_motion.c`, `test_spinner_gallery.py`, `test_status_motion.py` inspect absent status/busy semantics and idle redraw. Completion/action callbacks are not upstream contracts. | | Custom Icon box style and leaf layout | `cui_icon_options.style/constraints`, `src/base/cui_icon_layout.h`, `src/components/cui_icon.c` | New `test_icon_style_source.c` proves padding/border floors, minima/maxima, transforms and retained masks; Spinner fixture proves background/radius and ancestor opacity/clip. General inherited Icon styling remains partial. | | Asset/callback lifetime | Icon owns SVG copy; source closures stored by Rust; C callbacks borrowed synchronously | `test_icon.c` tests source replacement, loader revisions, old masks; `test_icon_style_source.c` consumes three retained versions after replacement. Spinner motion/result rollback and resource exhaustion are in `test_status_motion.c`. A combined Spinner caller-owned-data/reload/destroy sequence is still absent. | Local test paths above are under `tests/unit/` unless named `.py` under `tests/web/`. These are inspected evidence, not a new run of the complete native or gallery suites during this audit. ## Concrete remaining differences 1. **Finite easing overshoot: corrected in the native source-style API.** Spinner now reuses shared clock validation/default timing but applies a separate finite-turn custom easing policy. It retains the callback value in result.phase and normalizes in double before multiplying by radians. Negative and FLT_MAX turns remain finite. `test_spinner_contract.c` checks asymmetric SVG software pixels for equivalent rotations and rejects nonfinite output atomically. `test_status_motion.c` locks shared sampler/Skeleton rejection of overshoot. 2. **Reduced motion ease(0): corrected, observable behavior change.** `cui_spinner_ex` now invokes custom easing at raw phase zero, even while reduced. A shifted easing freezes shifted, without active motion/deadline/invalidation. Nonfinite ease(0) now fails without advancing state/result or calling paint. The legacy pure sampler and Skeleton deliberately retain their bypass policy. Native tests cover both option and context reduction. `test_spinner_contract_gallery.py` proves selected finite, shifted and rejected curves plus live/reduced recovery; broader source bounce/quint curves remain outside this selected browser matrix. 3. **Named/custom size identity: additive opt-in implemented.** `cui_spinner_sizing` distinguishes XS/S/M/L rem multipliers from custom pixels. NULL descriptor preserves the previous explicit options.size behavior; zero named rem selects 16 logical pixels, explicit rem is supplied by the host. Resolved size is shared by default/custom painters. Native tests cover every preset at rem 16/20/32, fixed custom64, descriptor precedence and invalid preflight atomicity. This does not add automatic ambient scope inheritance or provide foreign binding support. Actual-WASM descriptor proof now lives in `test_spinner_contract_gallery.py`. 4. **Ambient/custom Icon style support is not complete.** New numeric box-style tests resolve important gaps; they do not establish general flex/percentage layout, automatic ambient text inheritance, or the full SVG renderer feature set inherited by source `.icon(Icon)`. Current ICON/SPINNER guides correctly retain this limitation. Parent composition covers many layouts, but does not prove identical custom Icon style precedence. Track the exact supported style subset and accept it explicitly before any scoped verification claim. 5. **The bridge Spinner remains the legacy primitive.** `src/bridge/cui_bridge.c:4387` calls eight-dot `cui_spinner`, with Loading status semantics and `reduced=false`, rather than decorative `cui_spinner_ex`. This is outside the current ledger's headless/WASM platform claim, but it blocks any unqualified claim covering language builders. Preserve legacy C API behavior; add an explicit source-style bridge contract and reduced-motion path if bindings are included in the eventual verification boundary. ## Documentation/source distinctions and deliberate CUI policies Upstream docs describe configurable speed, CSS transforms and shared timing. The frozen Rust Spinner has no public speed setter; speed is private 0.8s. It uses upstream transforms, not a CSS engine. Its `.repeat()` has `synced=false`, unlike the separate `.repeat_synced()` facility. Do not invent these as missing Spinner APIs. CUI's bounded duration option is an extension, not a source requirement. The source has no completion callback, loading-status announcement, focus handler, click action or pointer/touch state machine. Their absence from the decorative Spinner is correct. A custom painter is the portable C composition mechanism, not an upstream on-paint/action callback with matching Rust ownership semantics. CUI schedules explicit caller-clock deadlines at 60 Hz; source requests available animation frames with no maximum-fps policy on Spinner. This is a documented scheduling-policy difference, not evidence of hardware refresh-rate parity. Hidden/clipped spinners can still return active deadlines locally; the guide requires the application to omit them or stop scheduling. No hidden-work/power optimization is established by current evidence. ## Meaningful proof before reconsidering verification - Native and actual-WASM fixtures now cover finite negative/>1 turns, shifted ease(0), nonfinite rejection/recovery and reduced transitions with asymmetric SVG masks/canvas pixels. This bounded browser gap is closed; broader custom curve families and independent instance mount/remount remain unproved here. - Existing real-WASM scheduling tests already prove moving frames/pixels, finite wakes, no perpetual invalidation and quiescence after reduction. Exact sampled browser cycle angles and independently timed mounts are separate proof gaps. Add source bounce/quint curves, independent instances mounted at different times, and omission/remount policy. - Native and actual-WASM named-size fixtures cover rem 0/16/20/32 independently of text font size, with legacy/custom64 fixed. Both default/custom painters use the same logical size; rasterized rotated bounds may add a pixel fringe. - Combine a caller-owned raw-data Icon, style padding/border/min/max, explicit color precedence, rotation and source replacement in one Spinner frame; consume all returned draws before collect/destroy. Existing separate Icon tests are necessary but do not prove this composition end-to-end. - If builders are in scope, test actual bridge SVG/default semantics, reduced quiescence, custom icons/sizes/color/easing; legacy eight-dot smoke is insufficient. - Retain desktop/390px and DPR1/2 browser checks. GPU/platform acceptance remains separate; do not infer it from software or Canvas output. The ledger's current three features remain `tested`, both listed platforms remain `tested_partial`, and its explicit inherited-style limitation remains justified. Its evidence lists now include the contract, existing gallery and new bounded actual-WASM fixtures. Platform statuses remain partial; no family promotion. ## Historical isolated probe before the bounded fixes The original pre-fix audit used a temporary strict ISO C11 probe linking only the audited `cui_status.c` motion sections (unused sections garbage-collected). It characterized the old rejection of finite 1.25 output and bypass of shifted reduced easing; it is not evidence of current behavior. This is a passing characterization of a source difference, **not** a parity acceptance test. ```sh cmake -S /tmp/cui-spinner-audit-probe -B /tmp/cui-spinner-audit-build -G Ninja cmake --build /tmp/cui-spinner-audit-build python scripts/test_local.py --build-dir /tmp/cui-spinner-audit-build -- -V ``` Result: 1/1 passed, `-std=c11 -Wall -Wextra -Wpedantic -Werror`, private wrapper. No production/header/ledger/manifest changes were made. --- ## Base, themes, and components Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/base-components.md # Base, themes, and components Include `cui/cui_base.h` for behavior without a prescribed appearance. Begin a box using a stable ID, call the base control with that same ID, render any children, then end the box. Every value is application-owned: controls mutate passed pointers on accepted input and report whether the value changed. Base button returns the complete interaction state. Null value pointers do nothing. Disabled controls retain values and reject input. Checkbox mixed state becomes checked on activation. Radio activation selects its option without deselecting. Core queues dispatch input against the preceding completed frame. Submit the same IDs each frame. Space/Enter activation and tab focus come from core; the base slider consumes only input explicitly routed to its ID. It supports pointer drag/capture, arrow steps, Home/End, and a continuous value when step is zero. Positive step snaps relative to minimum. Slider range must be finite and ordered; a disabled slider never normalizes the application's value. Base controls add no draw commands. Include `cui/cui_components.h` for original styled controls. All interactive wrappers call base behavior. Light, dark, high contrast, and amber/ink terminal themes are value structs; callers can edit tokens to define another system. Text indicators keep checkbox, switch, and radio understandable with the portable text renderer. The terminal system uses square corners and a different palette and spacing. Focus uses a visible border. Progress, badge, label, and separator are presentational; progress has no accessibility range role yet. Standalone model APIs provide popup side flipping and viewport fitting, variable-height virtualization with overscan and spacer extents, and Gregorian calendar arithmetic over years 1–9999. These are building blocks, not complete popup, virtual-list, or calendar widgets. Virtualization scans heights in O(n) and allocates nothing. Date arithmetic returns a zero date on invalid input or out-of-range output; month navigation clamps the selected day. Popup placement requires finite rectangles and sizes. No animation, tri-state accessibility `mixed` flag, radio-group arrow navigation, range slider, logarithmic slider, or integrated calendar widget is claimed. `examples/unstyled` shows custom visuals consuming base checkbox state; `examples/styled_settings` submits a complete settings form to the draw list. The interactive gallery supplies the actual platform and renderer loop. The Input wrapper composes `cui_base_input` with the scalar UTF-8 editor model. Create an editor over your own fixed NUL-terminated buffer and retain its handle across frames. Input reports text changes, single-line Enter submission, and rejected edits. Selection movement alone does not report a text change. Arrow/Home/End, selection extension, and backspace/delete are supplied by the base editor event helper. Undo/redo are exposed as editor functions; keyboard shortcuts are not currently mapped. Disabled input rejects changes. The styled wrapper paints a named text field and focus border; it currently has no pixel caret or selection highlight, pointer-to-caret positioning, grapheme movement, IME, clipboard adapter, or text scrolling. It is partial Input functionality, not a complete native editor. --- ## Headless Editor operations benchmark Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/benchmarks/EDITOR_OPERATIONS.md # Headless Editor operations benchmark `tests/bench_editor_operations.c` exercises the actual styled `cui_editor`, including its default line-number gutter and a one-token-per-visible-line highlight callback. The older `tests/bench_editor_200k.c` remains a separate Textarea microbenchmark. Neither establishes full editor parity. Reproduce from the repository root (no native window or display is used): ```sh cmake -S . -B /tmp/cui-editor-bench -G Ninja -DCMAKE_BUILD_TYPE=Release -DCUI_BUILD_NATIVE=OFF cmake --build /tmp/cui-editor-bench --target cui cui_software -j 2 cc -std=c11 -O2 -UNDEBUG -Wall -Wextra -Wpedantic -Iinclude \ tests/bench_editor_operations.c /tmp/cui-editor-bench/libcui.a \ /tmp/cui-editor-bench/libcui_software.a -lm -o /tmp/cui-editor-operations /tmp/cui-editor-operations > /tmp/editor-operations.csv ``` The library uses the compiler's CMake Release flags (GCC `-O3 -DNDEBUG` in this run); benchmark assertions stay enabled. Each size creates a fresh context and 2K, 20K, or 200K LF-terminated 80-byte ASCII lines, without wrapping, with an 800x400 viewport. The largest document contains 16,000,000 bytes. Caller row storage is 11,200,056 bytes on this 64-bit build, plus 16,000,064 document buffer bytes. These are exact caller capacities, **not** total memory or allocation counts: model/context/history/frame allocations are not instrumented. CSV records process CPU milliseconds from C11 `clock`, text-measurement and highlight callback counts, and generated draw-command counts. The measurement provider returns seven pixels per byte; it does not shape or rasterize text. Timing covers begin-frame through end-frame, including event handling. Event queuing and programmatic selection setup occur outside the timed interval. Cold layout is sampled once per document; each hot workload has eleven samples, except alternating middle edits (five) and tail edits (six). Each insert is followed by Backspace to restore document length. Assertions verify layout row counts, scroll movement, keyboard navigation, and edited bytes. `pointer_move` measures ordinary editor pointer dispatch; no language-server hover provider is installed. No elapsed-time pass/fail threshold is imposed. Reference run: 2026-10-18, Linux x86_64, Intel Core Ultra 5 235U, GCC 16.2.1, source base `81a8bd3a` plus this benchmark. Other engineering builds were active; CPU timings and spread remain sensitive to frequency, cache and contention. Raw samples are in [editor-operations-2026-10-18.csv](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/benchmarks/editor-operations-2026-10-18.csv). Median CPU milliseconds (cold is a single sample): | Operation | 2K lines | 20K lines | 200K lines | | --- | ---: | ---: | ---: | | Cold layout | 2.367 | 11.614 | 97.496 | | Idle | 0.184 | 0.196 | 0.177 | | Programmatic caret at tail frame | 0.180 | 0.188 | 0.157 | | Actual Left key near tail | 5.249 | 50.912 | 454.884 | | Wheel scroll | 0.183 | 0.196 | 0.212 | | Pointer move | 0.172 | 0.176 | 0.170 | | Tail insertion | 0.395 | 2.405 | 21.938 | | Tail removal | 0.410 | 2.580 | 20.937 | | Middle insertion | 0.637 | 4.656 | 45.987 | | Middle removal | 0.641 | 4.703 | 45.035 | At 200K lines the eleven Left-key samples span 326.947–509.495 ms. This workload exposes document-size-dependent keyboard/edit cost even though steady layout, scroll, and pointer frames remain nearly constant. It does not justify an interactive 60 Hz claim. Investigate model grapheme navigation and document validation/copying before attributing these costs to viewport painting. Cold layout and middle edits still process substantial document content. Actual font providers, Unicode, long lines, wrapping, folds, multiple selections, search, IME, renderer execution and GPU presentation need separate measurements. ## Validated ASCII model-motion change The follow-up change routes Edit model grapheme motion through the existing validated-buffer helpers already used for grapheme erasure. Adjacent ASCII scalars admit a local answer, with CR/LF handled as one cluster. Non-ASCII context still uses the complete Unicode grapheme scan. The standalone public `cui_grapheme_*` functions retain whole-input validation and their behavior for malformed UTF-8 and arbitrary offsets. This does not introduce a Unicode backward scan or a new segmentation algorithm. The same executable source, flags, document sizes and machine produced these Left-key medians after the change: 0.116 ms at 2K lines, 0.179 ms at 20K, and 0.182 ms at 200K (200K range 0.165–0.193 ms). Raw samples are in [editor-operations-ascii-motion-2026-10-18.csv](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/benchmarks/editor-operations-ascii-motion-2026-10-18.csv). These sequential runs are illustrative, without a controlled machine load; the removed whole-document scan is also evident from the code path. Tail and middle insertion medians at 200K remain 21.946 and 43.101 ms. Unicode navigation and ordinary edits can still scale with document size. `test_model_grapheme_motion` compares model previous/next motion against the public segmenter at every scalar offset of every pinned Unicode grapheme test case, surrounded by ASCII context. It includes offsets within clusters, extended selections, and CR/LF selection collapse. Existing malformed-input and byte-interior public API tests remain in force. ## Validated Editor gutter index reuse The styled Editor previously counted every document byte again whenever the model revision changed, even after event handling had refreshed the Textarea row index. Its gutter now uses the final row's logical line number when that index matches the model, revision, storage and complete document extent. This counts logical lines rather than wrapped rows. Stale or missing layouts, folds and composition retain the document scan. No model storage, undo history, grapheme segmentation or change notification behavior changes. The unchanged benchmark above ran before and after this change on 2026-10-20, Linux x86_64, Intel Core Ultra 5 235U, GCC 16.2.1, source base `63a62d6f`. Raw samples: [before](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/benchmarks/editor-operations-gutter-before-2026-10-20.csv) and [after](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/benchmarks/editor-operations-gutter-after-2026-10-20.csv). Median CPU milliseconds: | Operation | 2K before / after | 20K before / after | 200K before / after | | --- | ---: | ---: | ---: | | Tail insertion | 0.396 / 0.165 | 1.353 / 0.174 | 12.546 / 0.098 | | Tail removal | 0.406 / 0.170 | 1.428 / 0.281 | 13.715 / 0.867 | | Middle insertion | 0.620 / 0.391 | 2.973 / 2.349 | 29.242 / 16.574 | | Middle removal | 0.617 / 0.381 | 2.982 / 2.374 | 29.729 / 16.873 | These sequential runs had uncontrolled concurrent engineering load; timing differences from the earlier reference run are not attributable solely to this patch. The removed full-document gutter pass is evident in the code path. Middle edits still lay out the changed suffix, and external programmatic edits still require a gutter scan before layout. This fixture has no undo storage. It does not establish Unicode, wrapped/folded, IME, history-enabled or renderer performance, full editor parity, or a general 60 Hz guarantee. The headless `gutter_logical_line_index` regression covers wrapped logical counts, CR/LF/CRLF, trailing newlines, multiline event insertion and rendered gutter labels, undo/redo, external edits, and U+2028 soft separators. Folded gutter fallback is also checked in the existing folding regression. --- ## Consumer skill output budget proposal Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/AGENT_SKILL_OUTPUT_BUDGET.md # Consumer skill output budget proposal Status: the presentation slice is implemented by `6ac3e2eb`, after the component-event implementation batch. The historical audit/proposals below explain its constraints; current CLI/SKILL instructions are authoritative. Human summaries preserve all canonical limitations; JSON and complete reads retain their previous shape/content. Exact ATX section retrieval is explicitly partial; arbitrary line slicing remains deferred. Final integrated validation and publication remain separate gates. ## Evidence and reproducibility Audited `integration/next39-components` at `e9d2c1a561ced3254e606b0206f412af8b156317` (the isolated worktree's starting commit), then repeated all eight measurements against the current integration checkout at `84376caa17b93e56ed643599207d5ee818b74011`: every byte/line count was identical. The skill instructions, CLI, canonical exporter and generator also have no diff between these revisions. Commands below use `python skills/cui/scripts/cui.py` with bundled references, without `--source`. Measurements include stdout and its final newline, count UTF-8 bytes and `splitlines()` lines. Estimates are **bytes / 4 rounded**, not tokenizer counts, model costs, or guarantees; code and multilingual text tokenize differently. | Helper arguments | Bytes | Lines | Estimated tokens | | --- | ---: | ---: | ---: | | `component Select` | 78,254 | 1,341 | 19,564 | | `component Select --show usage` | 597 | 18 | 149 | | `component Select --show limitations` | 1,294 | 51 | 324 | | `component Select --show examples` | 53,240 | 822 | 13,310 | | `component Input --show examples` | 43,565 | 601 | 10,891 | | `search "font fallback" --kind guide` | 540 | 20 | 135 | | `api cui_begin_frame` | 47,790 | 976 | 11,948 | | `read docs/START_HERE.md` | 5,539 | 97 | 1,385 | To repeat: invoke each command using `subprocess.run(..., capture_output=True, check=True)` and report `len(result.stdout)`, `len(result.stdout.splitlines())`, and `round(len(result.stdout)/4)`. Measure both bundled and `--source` modes after the event API merge; record the full commit SHA and resource digest with the implementation baseline. The present helper's `component()` defaults to `all`; `examples` expands every linked component document's complete body plus sample and test references. These are often broad guides, not narrowly scoped component examples. `api` prints complete matching headers, even when one function is requested. Search already limits results to ten, ranks literal words, labels partial matches, and exposes `--limit`; it is not currently an unbounded document dump. Limitations for Select are comparatively small: reducing their completeness would save little and risk misrepresenting supported behavior. The skill already recommends targeted `--show` calls, but its default and examples expansion work against that guidance. ## Proposed discovery contract Default component output should be a concise, useful summary: canonical name, resource digest/revision, scope, state ownership, interaction/event contract, public header path, selected declarations, and explicit support/limitation statements. Provide precise follow-up commands for API, examples and full source. Do not print a whole header, broad guide, test file, or all feature inventory just because a component name was requested. Proposed initial human-readable budgets (targets to validate, not truncation rules): default component summary 4 KiB; example index 2 KiB; search at most five results and 2 KiB normally. A limit can be exceeded by required safety/unsupported information, with a labelled explanation. Avoid a global byte slicer: it can cut a declaration, ownership condition, or limitation in half. Keep the source digest available in JSON and print a compact digest once in text. Suggested staged interface, to finalize after event API stabilization: - `component Select`: summary plus all critical limitations and follow-up paths. - `component Select --show examples`: indexed paths, language/host, purpose, component relevance, and build context; no automatic document bodies. - `component Select --example PATH`: one complete selected example, if linked and verified. Until such mapping is available, `read PATH` is the exact retrieval mechanism. Do not guess component relevance from arbitrary substrings. - `component Select --show limitations`: complete limitations, explicit feature support states and platform scope. Format concisely; do not hide unsupported behavior behind a count or an optional follow-up. - `component Select --full`: current complete `all` behavior. Keep explicit `--show all` as its compatibility spelling. - `api cui_begin_frame`: declaration, owning header path and required related type/ownership references; `--full` restores complete matching headers. Exact header reads remain available. An incomplete extracted declaration must not be presented as a complete callable contract. - `search QUERY`: five compact results with match status and retrieval command. Retain `--limit N`, validate positive integers, and cap ordinary requests (proposed 50). Offer explicit `--full` for all matching result metadata. Report returned versus total matches and continuation guidance; never silently discard results. Keep ranking and complete-before-partial behavior unchanged. Keep `read PATH` exact and unbounded by default: the caller deliberately selected a resource and existing users rely on verbatim retrieval. Add heading-based reads only if section boundaries can be resolved reliably, with document path, heading, and explicit omitted-section markers. Never return a clipped code example that looks runnable. `info` is a metadata inventory; consider a small default overview and explicit full hashes separately, rather than conflating it with search. ## Examples and limitations need source structure Prefer one authoritative minimal runnable example for each applicable language and host, then references to full applications. Include event setup, state lifetime, error handling, build entry point, and headless execution guidance when required; a shorter disconnected fragment is not necessarily cheaper to use correctly. The event API change may replace current polling examples, so mappings and tests must be selected after that merge. Do not promise all 78 components have a complete binding example or parity. Use existing component-specific limitation and feature records as authority. Summaries must preserve unsupported states, host/backend qualifications, required providers, and ownership/lifetime conditions. If records are too ambiguous to summarize safely, emit them completely and exceed the target. A future curated critical/noncritical classification requires explicit reviewed source metadata; keyword filtering is insufficient. Native display isolation, pinned setup, matching `--source` revision, dependency authorization, compiler/build verification, and incomplete platform/binding parity remain visible instructions in SKILL.md. ## Source and generated ownership - Hand-maintained entry instructions: `skills/cui/SKILL.md`. - Hand-maintained CLI and presentation: `skills/cui/scripts/cui.py`. - Canonical exporter: `scripts/agent_resources.py`; shared website/skill data model. - Canonical component usage/lifetime/example references: `docs/component-usage.json`; status/features/platforms/limitations come from `docs/component manifest` (confirm collector inputs after the event merge). - Original documents, public headers and examples remain authoritative. Generated summaries should reference them, never invent independent API declarations. - `scripts/generate_agent_skill.py` generates `skills/cui/data/resources.json` and copies the canonical exporter to `skills/cui/scripts/agent_resources.py`. **Never hand-edit these outputs.** Run the generator after source changes and verify `--check`. - Regression owner: `tests/test_agent_skill.py`, alongside shared exporter tests discovered in the updated tree. Preserve all 78 catalog entries and lifecycle metadata; lower output volume does not justify removing indexed resources. Prefer presentation-only changes first; add structured example metadata to the canonical exporter only when current references cannot distinguish examples from broad guides. Do not prune the offline resource bundle merely to reduce stdout: shipping size, discovery output, and runtime context consumption are separate costs. ## Compatibility and implementation sequence 1. Wait for component-event API merge; pin its SHA, refresh this measurement table, and verify exact entry-point/build instructions against it. 2. Add explicit summary/full modes and example indexing with meaningful tests. Preserve current structured JSON defaults initially; opt into concise JSON with a versioned schema or explicit mode. Avoid silently changing lists into envelopes or removing header/document fields from existing automation. 3. Switch human-readable defaults with documented migration to `--full` / `--show all`; update SKILL.md to start with summaries and fetch only chosen references. Do not require a second call to discover critical limitations. 4. Measure representative before/after bytes and exercise actual consumer flows: choose component, inspect contract, find one host-appropriate example, build and trigger an event. If multiple follow-up calls erase the savings, revise the defaults rather than claiming success from a single smaller response. 5. Regenerate resources and run existing skill/export checks. Implementation remains a separately assigned change; this audit does not authorize it. Regression coverage should assert semantic content plus generous byte ceilings, not brittle exact whitespace snapshots. Test Select/Input and a component with unsupported behavior; test short versus exceptionally long critical limitations, non-ASCII content, missing resources, exact/partial/no-match searches, positive and excessive limits, deterministic ranking, displayed omission counts, full-mode completeness, and legacy JSON shape. Check that default example output never expands unrelated document bodies and selected exact reads preserve all bytes. Compare bundled, live `--source`, and packaged-resource project modes; retain source digests, stale-generation detection, offline operation, archive guards and no-launch behavior. Compile chosen event examples with warnings and execute their meaningful headless tests through `scripts/test_local.py` for native cases. Budget assertions must allow a safety-completeness exception with an explicit reason. No benchmark should pass by deleting unsupported/API/build warnings. ## Current preparation checkpoint — 2026-10-18 **Still preparation only.** Implement only after the Scroll/API batch is complete and root has reviewed the resulting CLI scope. The earlier user dependency on the overall component-event API change remains in force; this checkpoint does not claim that batch is frozen or authorize CLI/SKILL/exporter/generated edits. Read the system skill-creator guidance and repository `skills/cui/SKILL.md` before this refresh. Its relevant principles are cheap discovery and progressive detail, while preserving non-obvious invariants and actual user intent. No need to invent another reference directory or duplicate the C manuals inside the entrypoint. ### Repeated measurements and freshness Measured clean isolated source HEAD `c63b100f81539428c3beef8eaee3ddd23abc99dd`. Bundled resource-file SHA256: `ff58ff9188a4ba3cc027a25f7a90c036bf8a6ff30d8cb2e4469aa6f78bdff1cc`. Bundled `source_digest`: `c65a2d1ab742de3bc47f5b71f2c918d4c3e58efaeef8546c7c1b395a1fba846a`. Live `collect(source)` digest: `0b73f7a749067e4502ccb0ef15f020143af679b5bf377a35159435688216d24e`. The digests differ: the sole differing resource hash is `docs/TEXT_VIEW.md`. This is an observed pending generation mismatch, not evidence of matching snapshots or an instruction to hand-edit resources. All measured output bytes/lines below happen to match between modes, but component stdout hashes differ because they print the different digest. API/search/read stdout hashes match for these queries. Regenerate only through the canonical generator after the final batch; remeasure rather than treating equal byte counts as equal content. Each row was run both without source (bundled) and with `--source /home/matteo/.cache/cui-worktrees/skill-output-current`. Values include the stdout final newline; token estimates are `round(UTF-8 bytes/4)`, not tokenizer counts. Both-mode results: | Arguments after helper | Bytes, each mode | Lines | Estimated tokens | | --- | ---: | ---: | ---: | | `component Select` | 88,935 | 1,468 | 22,234 | | `component Input` | 80,985 | 1,389 | 20,246 | | `component Select --show usage` | 597 | 18 | 149 | | `component Select --show limitations` | 1,294 | 51 | 324 | | `component Input --show limitations` | 7,588 | 167 | 1,897 | | `component Select --show examples` | 59,082 | 868 | 14,770 | | `component Input --show examples` | 45,952 | 647 | 11,488 | | `component Select --show api` | 28,229 | 537 | 7,057 | | `component Input --show api` | 26,897 | 564 | 6,724 | | `api cui_begin_frame` | 48,354 | 985 | 12,088 | | `api cui_select_events` | 27,713 | 521 | 6,928 | | `search font fallback --kind guide` | 634 | 20 | 158 | | `read docs/START_HERE.md` | 5,539 | 97 | 1,385 | Raw stdout files and per-output hashes are preserved externally in `/home/matteo/.cache/cui-validation/skill-output-current/`; `measurements.json` SHA256 is `4f87d0deba106a0f2f2e574b1401292307aa05b05678153cb18ba7ce5c52d021`. That evidence is machine-local, not a newly shipped skill resource. Commands use only Python stdlib and offline bundled/live resources; no downloads, builds, installation or native/browser windows were involved. Compared with the historical table, Select default grew 10,681 bytes and its examples grew 5,842; Input examples grew 2,387. The current default still prints all sections. `examples` still means **every linked guide body**, not a targeted runnable example: Select expands 53,015-byte `docs/CHOICE.md` plus 5,813-byte `docs/SELECT_EVENTS.md`. Input expands seven guides totaling 44,719 body bytes, plus headings/references. Input's complete limitations/feature/platform section alone is 7,588 bytes. It cannot fit a 4 KiB default without either safe formatting savings or a labelled budget exception; removing constraints to satisfy the target is unacceptable. ### Exact presentation proposal for review Keep existing JSON schemas and meaning unchanged initially. Only human-readable defaults change; new explicit flags are opt-in, not implemented by this checkpoint. | Command | Proposed exact semantic output | | --- | --- | | `component NAME` | Summary: name/digest; complete canonical scope/composition/state ownership/interaction/usage strings; state types/callback names; indexed public declarations and exact header paths; **all** canonical limitation/platform/status/feature facts; explicit incomplete-contract label and required header/linked-guide read commands. No automatic guide/header/example/test bodies; no claim to reproduce header contracts. | | `component NAME --show summary` | Explicit spelling for that same human summary. If JSON is requested, reject this new section initially rather than accidentally returning the legacy all schema under a new meaning. A concise JSON format needs a separately named/versioned contract. | | `component NAME --full` | Exact existing all-section human output; alias of existing explicit `--show all`. With `--json`, exact existing `--show all --json` dictionary/values. Reject conflicting `--full --show usage/limitations/...`; do not guess precedence. | | `component NAME --show usage` / `--show limitations` | Preserve existing section meaning. Limitations prints all current status/platforms/limitations/features, without count-only replacement, keyword filtering or suppressed unsupported states. | | `component NAME --show examples` | Human **index**, preserving every linked document, sample and test reference. Each entry has canonical path, actual title when available, source role (guide/sample/test reference), and exact `read PATH` command. Broad guide must be labelled guide, not claimed component-only runnable example. No bodies. | | `component NAME --show api` | Human declaration/index view using existing `symbols`, exact canonical header/linked-guide read commands and explicit incomplete-contract warning. JSON keeps its full existing API/header section. `--show all` / `--full` restores the old full human content. | | `api SYMBOL` / `api SYMBOL --declaration` | Human default and explicit alias: exact indexed declaration(s), owning header path(s), digest, known linked guide paths and executable `read PATH` commands, plus `Declaration/index only: incomplete contract; read authoritative headers and linked guides before calling.` No inferred ownership/type/macro code or contract extraction. If no indexed function exists, print only exact matching resource paths and retrieval guidance, with `No indexed function declaration; this lookup does not prove a type or macro definition.` | | `api SYMBOL --full` | Restore the exact old human text: indexed function declarations followed by every complete matching header. No clipping or implicit limit. Reject conflicting `--full --declaration`. JSON remains the existing full object by default and with `--full`. | | `read PATH` | Preserve exact existing content plus CLI's existing final print newline; no silent size limit, section slicing or JSON-shape change. Deliberate exact read remains available for offline consumers. | For legacy machine users, all existing `component --json` invocations (including omitted `--show`) retain name/digest and all usage/api/header/status/examples/ sample/tests fields and complete strings. Existing `--show examples --json` retains `{examples:[{path,text}],sample,tests,...}`; the new human index is not a JSON truncation. Existing `api --json` retains `{functions,matching_headers}`. `--declaration --json` should be rejected initially unless its distinct schema is explicitly reviewed; do not remove matching_headers from old JSON. Existing search JSON remains the same list with current fields/ranking/default 10; do not wrap it in a new envelope to report totals. Human search may default 5 with a footer giving returned/total/complete-or-partial status and `--limit` retrieval guidance; explicit limits and full-mode details require validated bounded semantics. These are presentation differences, not missing data in the bundle. ### Concrete minimal outputs and safe exceptions A Select summary starts with the actual authoritative facts: ```text Select | digest State: Caller retains cui_choice_popup, selected cui_id and item array. Interaction: API: cui_select; cui_select_events Header: include/cui/cui_choice.h Limitations/platforms/features: Contract: INCOMPLETE summary; read these authoritative resources before calling. read include/cui/cui_choice.h read docs/SELECT_EVENTS.md read docs/CHOICE.md Examples: component Select --show examples Full: component Select --full ``` Angle-bracket fields above are proposal placeholders, not shipped output or permission to omit content. The implementation must populate complete source facts and distinguish current legacy usage text from the added native observer contract; current Select interaction metadata still says only `Returns selection change...`, while the event guide carries multiplicity/lifetimes. Merely using that short usage sentence does not establish the event contract. The summary must say the contract is incomplete and give those exact required reads; it must not claim all header/guide conditions were preserved inline. A Select example index can accurately say: ```text Guide: docs/CHOICE.md — Tabs and toggle groups (shared multi-family guide) read docs/CHOICE.md Guide: docs/SELECT_EVENTS.md — Select selection notifications read docs/SELECT_EVENTS.md Sample reference: web/gallery.c (shared source, not a standalone Select app) Tests: tests/unit/test_choice.c; tests/web/test_browser.py (references only) ``` Do not guess language/host/relevance/build commands from a filename alone. The current metadata contains paths, not reviewed per-component runnable-example mappings. Choose existing complete examples only after their build context is explicitly captured; `read` of a linked full guide remains the honest fallback. Optional future heading reads must preserve a complete uniquely identified section and explicitly name omitted sections. `docs/CHOICE.md` has a `List, Select and Menu` section plus separate multiple-selection/context/dropdown sections; its first title is not a safe automatic Select slice. Input guides often have only one top-level heading, so heading slicing would not solve their output cost by itself. **Critical contracts cannot be extracted with the current regex index.** The first implementation is a cohesive **presentation-only** change: use existing `data.symbols` declarations and canonical component metadata, label the default view incomplete, and route explicitly to complete authoritative header/guide reads. Do not infer ownership from declaration syntax, classify safety by keywords, clip a header, or claim that a concise summary contains all header contracts. All actual canonical limitation/status/platform/feature facts remain inline; required build/lifetime/security instructions already in SKILL.md remain visible. Targets are 4 KiB summary / 2 KiB example index with no hard cut-off: complete Input limitations and other oversized canonical facts may exceed them. No new source metadata is a prerequisite for this presentation slice. If a future reviewed iteration wants **complete inline contract excerpts**, it needs explicit canonical section references and validated boundaries, with full fallback on ambiguity. That is separate from default declaration/index discovery; do not delay the useful presentation-only step or silently invent such metadata. Do not claim an 80% complete-building-flow reduction from a small initial response: include all mandatory contract and chosen-example/build reads in end-to-end totals. Essential SKILL.md rules remain visible: actual stack and matching `--source`, pinned setup/offline provenance, explicit optional dependencies, stable IDs and borrowed lifetimes, balanced begin/end, all 78 ≠ binding/platform parity, real font/provider and measurement/paint configuration, warnings/behavior checks, and private Xvfb/headless browser/no desktop launch. Example indexing does not delete build context; selected exact examples must retain it. Unsupported APIs and plain versus secure text/queued versus synchronous event boundaries stay explicit. ### Implementation boundaries and acceptance after the batch Hand-maintained ownership remains CLI `skills/cui/scripts/cui.py`, entrypoint `skills/cui/SKILL.md`, canonical exporter `scripts/agent_resources.py`, metadata `docs/component-usage.json` and actual docs/headers/examples. Generated `skills/cui/scripts/agent_resources.py` and `skills/cui/data/resources.json` are never hand-edited. The frozen batch must be regenerated with `python scripts/generate_agent_skill.py`, then checked with `--check`. Keep the shared website model, all 78 component records, hashes/lifecycle information and source-vs-packaged project selection intact. Existing `tests/test_agent_skill.py` checks complete component fields and JSON fixtures, rank/partial behavior, source freshness/digests, archive pinning and no-launch setup. Extend it rather than replacing those contracts with byte-only assertions. Add bundled/live/packaged cases for unchanged legacy JSON dictionaries and complete guide/header bodies; human summary/index/full and conflict errors; exact limitation/feature/platform retention including Input; explicit declaration absence for types/macros; broad-guide labels and correct read commands; explicit incomplete-contract labels and authoritative full-read commands; no inferred contract/typedef extraction or byte clipping; non-ASCII and metadata larger than target; 5-vs-10 human/JSON search semantics and honest counts. Exact `read` stays unchanged. Verify changed-digest source mode actually changes identity, not just byte counts. Measure real flows (summary → selected declaration → mandatory contract → selected example/build context) with both output modes after implementation. Report bytes/ lines and labelled estimates per call and total. No dependency installs, automatic UI launch, production CLI changes or generated edits occurred in this preparation. ### API-default refinement for final review (still no implementation) This refinement supersedes the earlier suggestion to keep human `api` full until curated contract blocks exist. Human default discovery is concise and explicitly incomplete; full contract reads are required next, not claimed to have vanished. No CLI, SKILL, exporter, canonical metadata or generated files change here. For a known indexed function the proposed human default is structurally: ```text API: cui_select_events | digest Declaration/index only: INCOMPLETE CONTRACT. Required authoritative reads before calling: python "$HELPER" read include/cui/cui_choice.h [same --source context] python "$HELPER" read docs/CHOICE.md [same --source context] python "$HELPER" read docs/SELECT_EVENTS.md [same --source context] Full matching-header output: python "$HELPER" api cui_select_events --full [same --source context] ``` Placeholders above describe formatting, not runnable emitted commands. Actual output uses exact paths/source selection and shell-safe quoting for the helper and source path. Known owning headers come from exact indexed-function matches; related component guides come only from canonical `api_symbols` membership and its `docs` paths. Do not claim this list is a complete automatically derived type or ownership dependency graph. Other matching headers may be listed separately as `matching resource`, never incorrectly labelled the owning declaration. For `api TYPE_OR_MACRO` without an indexed function, print `No indexed function declaration; exact matching resources only.` and all exact matching header paths with full read commands. Do not reconstruct struct bodies, macros, enum constants or typedefs with the function regex. If no indexed declaration or matching header exists, preserve the existing unknown-symbol error/nonzero status; no invented code, broad fuzzy replacement or successful empty-contract response. `--full` provides the old complete matching-header text even for such resource-only hits. All existing `api --json` defaults remain `{functions, matching_headers}` with complete header strings, including resource-only hits. The default change is human presentation only; `--declaration --json` remains an explicit error until a separate new schema is reviewed. Component JSON and examples JSON remain unchanged. Human component summaries preserve all canonical limitations and prominently mark missing complete header contracts; human example indexes retain every path. Human search defaults 5 versus JSON 10 as above, without changing legacy JSON list shape or ranking. Exact `read` and full escape hatches remain unbounded and offline. Acceptance measures a **complete building flow**, not just the first lookup: inspect existing integration and pinned source, component summary (all limitations), API declaration/index, each required authoritative contract, one selected example with build context, compile and meaningful headless behavior check. Track bytes/ lines per discovery/read response and their sum in bundled, live-source and packaged modes. A 59 KB shared Choice guide remains a 59 KB required read until a separate reviewed section-read/curated example feature exists; example indexing avoids automatic unrelated guide dumps but does not justify hiding required contracts or asserting every consumer flow saves the same amount. Targeted users who only need discovery benefit immediately; implementation users must still read the applicable contracts. Report observed savings and remaining large reads honestly. Production stays blocked on Scroll/API batch completion and root's subsequent implementation authorization, as requested by the user. ### Scoped resource reads: explicit partial retrieval proposal Preparation only, continuing from `cfe80acc542beee8e717f47432b041b5aca56854`. The current `read` branch looks up one exact `data.documents` path, then prints its complete string (or JSON-encodes that string). It has no section/line selector. Do not change that default or its newline/JSON behavior. The following additive human modes make a large-guide follow-up optional without pretending to recover an entire API contract: ```sh python "$HELPER" read docs/CHOICE.md --headings --source "$CUI_SOURCE" python "$HELPER" read docs/CHOICE.md --section 'List, Select and Menu' --source "$CUI_SOURCE" python "$HELPER" read docs/INPUT_ACCEPTANCE.md --section 'Ownership, bounds and rollback' --source "$CUI_SOURCE" python "$HELPER" read docs/INPUT.md --lines 1:14 --source "$CUI_SOURCE" ``` These flags are proposed, not currently callable. Exact semantics: - `--headings`: for Markdown only, list all supported ATX headings in source order, their level, exact heading text and inclusive line span. Print path, digest and exact follow-up section/full-read commands. This is an index, not a guide summary or inferred dependency graph; do not expand bodies. - `--section TEXT`: for Markdown only, match one exact unique heading text; retain Markdown punctuation rather than inventing slugs/rendered-text matches. Include that heading, its entire body and descendant subsections, stopping immediately before the next heading of equal or smaller level or EOF. Do not stop at a child heading or select only the first paragraph/example. Preserve selected text and blank lines; never cut by byte/token budget. - Duplicate heading text fails nonzero with every matching line/ancestor path and `--lines`/full-read guidance; never silently choose the first. Empty or absent heading is an explicit error, not an empty successful partial read. Do not add fuzzy fallback. A top-level heading can select nearly the whole document; report its actual span rather than promising a saving. - `--lines START:END`: any existing text resource, strict positive decimal, one-based inclusive endpoints with `START <= END <= source line count`. No negative indexing, omitted endpoints, clamping or implicit last-N behavior. Invalid/out-of-bounds ranges fail without partial stdout. Preserve those exact lines. This is an explicitly arbitrary excerpt, not a declaration extractor or runnable-example API. It may omit a declaration/type/lifetime condition. - Selectors are mutually exclusive (`--headings`, `--section`, `--lines`). Initially reject each with `--json`, leaving existing `read PATH --json` a JSON string with the complete unchanged document. No silent string-to-envelope migration. A later explicitly versioned partial-JSON schema needs its own review. The heading scanner is deliberately a documented Markdown subset: ATX levels 1–6, up to three leading spaces, required heading whitespace, optional CommonMark closing hashes. Ignore headings inside fenced backtick/tilde blocks and indented code; distinguish closing fences by matching character, sufficient length and whitespace-only tail. Unterminated/ambiguous fenced structure at a requested boundary fails rather than offering a clipped runnable block. Setext/HTML/other unsupported heading syntax is not heuristically interpreted; full reads and explicit line ranges remain available. Tests must include hashes inside C/Python code fences, longer/nested fences, trailing hashes, Unicode/punctuation, duplicate headings, children, CRLF as represented by the existing collected document string, last line without newline and empty documents. This needs no third-party parser or new dependency and does not claim a full CommonMark implementation. Every selected-body response begins with an explicit envelope: ```text PARTIAL RESOURCE EXCERPT — not a complete contract or standalone program Path: docs/CHOICE.md | digest Selection: section 'List, Select and Menu' | lines 76:170 of 805 Omitted: 75 lines before; 635 lines after (not automatically irrelevant) Full: python "$HELPER" read docs/CHOICE.md --source ``` Then the intact selected section follows. For arbitrary `--lines`, present the substring in an explicitly plaintext display envelope (choose an outer backtick fence longer than any run in the excerpt), so a cut inner Markdown/C fence does not masquerade as complete runnable code. Do not append invented code/fence contents to the resource body. Output metadata/fences belong to the partial view; default full `read` remains unchanged. Even a section spanning all lines does not prove dependency closure or complete usage guidance. Nonzero omitted counts and explicit source identity make partial retrieval visible; no keyword safety filter or automatic assertion that omitted material is irrelevant. API/default summaries should offer these scoped commands where an exact heading is actually present, alongside the complete resource command. This is retrieval, not a new claim of curated relevance: initially list the heading index so the consumer chooses. Do not hardcode `--lines 76:170` across future digests or treat section titles as stable IDs. A stale/renamed heading must fail clearly. Required header reads and dedicated event/lifetime guides still apply; section reads do not authorize silently removing canonical limitations from component summaries. ### Actual heading evidence and discovery-to-example cost Measured source content at `cfe80acc542beee8e717f47432b041b5aca56854`; live digest remains `0b73f7a749067e4502ccb0ef15f020143af679b5bf377a35159435688216d24e` because design checkpoints are excluded from exported consumer resources. The bundled/source mismatch recorded above remains; this does not regenerate it. | Actual document / exact section | Inclusive lines | Body bytes | Scope caveat | | --- | ---: | ---: | --- | | `docs/CHOICE.md` / `List, Select and Menu` | 76–170 | 6,221 | Includes the existing Select snippet, popup/state/ID/lifetime/scroll/gap discussion, plus List/Menu/split-button context; not a Select-only complete contract. | | `docs/CHOICE.md` / `Combobox` | 171–218 | 2,985 | Separate selected section; must not substitute for Select. | | `docs/CHOICE.md` / `Tab drag reorder requests` | 428–805 | 26,397 | Contains later appended material under the final heading; headings alone do not guarantee relevance or small output. | | `docs/INPUT_ACCEPTANCE.md` / `Ownership, bounds and rollback` | 68–99 | 2,160 | Relevant ownership slice, not the whole acceptance/engine contract. | | `docs/INPUT.md` / `Source sizes and fixed-height centering` | 15–41 | 3,081 | Metrics slice. Its top-level section instead spans the whole 6,241-byte document, including this child. | | `docs/SELECT_EVENTS.md` / top-level heading | 1–42 | 5,813 | Dedicated compact guide already; full read is sensible. | | `docs/TEXT_INPUT_STYLED_EVENTS.md` / top-level heading | 1–42 | 2,347 | Dedicated compact guide; section retrieval adds no content saving. | A plausible **existing-app single Select observer discovery → contract/example** flow was measured, not just default summary size. This scenario assumes the consumer already understands its project's Core/context/theme/host/build setup; it is not the complete dependency closure of a new application. It deliberately keeps the full 27,429-byte Choice header response and full shared event header, reads dedicated Select/shared selection guides, and uses the Select snippet in those guides/the chosen Choice section. It neither reads nor calls a clipped `web/gallery.c` a standalone example. New-host setup/build documentation, extra optional behavior, compiler logs and verification are additional costs, not zero. Current calls were executed offline with the existing CLI and `--source`; proposed summary/declaration/index/envelope strings were formatted by a temporary external measurement probe. **Proposed values are estimates from concrete formatting, not implemented CLI output or a completed app validation.** Both retain all canonical Select metadata limitations and full required reads in this scenario. | Current targeted flow | Bytes | Proposed flow | Bytes | | --- | ---: | --- | ---: | | `component Select --show usage` | 597 | Summary prototype with complete usage/limitations metadata | 1,971 | | `component Select --show limitations` | 1,294 | Declaration/index prototype | 521 | | `api cui_select_events` (complete matching header) | 27,713 | Example-index prototype | 244 | | `component Select --show examples` (both whole guides) | 59,082 | Full `read include/cui/cui_choice.h` | 27,429 | | `read docs/SELECTION_EVENTS.md` | 5,212 | Scoped Choice section including prototype partial envelope | 6,412 | | `read include/cui/cui_selection_events.h` | 1,094 | Full `read docs/SELECT_EVENTS.md` | 5,814 | | — | — | Full `read docs/SELECTION_EVENTS.md` | 5,212 | | — | — | Full `read include/cui/cui_selection_events.h` | 1,094 | | **Total** | **94,992** | **Total** | **48,697** | This prototype is 46,295 bytes (~48.7%) smaller; byte/4 token estimates are 23,748 versus 12,174, not tokenizer counts. Exact production envelope/read-command/title formatting and a requested heading-index call add bytes and must be remeasured. The savings are not the ~98% suggested by comparing an 89 KB default against only a 2 KB summary. Most remaining cost is deliberate full-header/contract material. Consumers needing the whole shared guide can still choose the full read; their flow saves less. Input with validation, password staging or format providers needs its additional specific guides; no Select estimate is generalized to it. External probe evidence: `/home/matteo/.cache/cui-validation/skill-output-current/scoped-read-measurements.json`, SHA256 `b49fbd374d92be7c5a80be40f18db1e3a0852b98877e7513b65f205a82d092f6`. It records actual section body hashes, source spans/digest and each flow call. No file from that probe enters the shipped skill; no production CLI/exporter/ generator or generated resources changed, and no build/native/browser test ran. After Scroll/API completion and root approval, implement these bounded selectors with semantic tests, preserve old JSON/full reads, and rerun the measured flows against frozen bundled/live/packaged sources before claiming savings. ## Implemented measurement and independent consumer check Worker commit `e24382143b37241a8e983dadc434572703326fc6`, integrated as `6ac3e2eb`, passed 16 semantic tests via the private-display wrapper. Frozen bundled and live CLI comparisons retained legacy full/read/JSON output byte-for-byte. The measured existing-host Select discovery/contract/example flow, including a heading index and full owning/shared headers and dedicated guides, was 50,992 bytes bundled and 51,544 live versus the earlier 94,992-byte flow: approximately 46.3% and 45.7% less. These are scenario-specific bytes, not tokenizer counts or a promise about every complete application workflow. Measurement receipt: `skill-output-implemented/measurements.json`, SHA256 `750e19505200dfc3c6380e01e415d3e549495bd5f9b2a8aedf7c44d07c9df286`. An independent consumer copied the installed skill at `6ac3e2eb`, discovered Select's applied-transition observer, wrote an actual caller-composed C function and passed strict C11 syntax compilation. No linking, UI runtime or application validation was claimed. It read broad Choice/Core resources despite the available section mode, demonstrating that retrieval choices still determine total context cost; the controlled 46% scenario must not be generalized to that larger flow. Its feedback identified incomplete handler-type metadata, which must be labelled as an incomplete index rather than interpreted as no handlers. Full applicable contracts remain mandatory; section retrieval does not establish dependency closure. --- ## Alert completed-dismiss observer checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/ALERT_EVENTS_SLICE.md # Alert completed-dismiss observer checkpoint Status: **design checkpoint only; no production observer is implemented**. Audited at `e220b5ca`. This document narrows the intrinsic Alert gap identified in [the render-family audit](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/AVATAR_EVENTS_SLICE.md) and [remaining coverage](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_REMAINING.md). It does not promote those ledgers or claim per-input, full-family, foreign-binding or platform parity. The [shared contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_CONTRACT.md) remains authoritative. ## Existing behavior that must remain exact [Public Alert options](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) contain an optional caller-owned `bool *visible`, render slots and their `user`; they contain no Dismiss listener. [The implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_content.c), `cui_alert`, performs this sequence: 1. Reject null UI/theme, an invalid kind, or `visible != NULL && !*visible` at entry. The visibility guard runs once. There is no second guard after slots. 2. Submit the Alert box/semantic and header/icon, then title content unless banner mode suppresses it, body content, and action content in that order. These render callbacks run before the built-in Dismiss Button and may change caller-owned visibility or consume input using their existing facilities. 3. If dismissible, invoke `cui_button` with the derived child ID `cui_content_child(id, 1)`, the exact text `Dismiss`, and `disabled=false`. `cui_button` delegates to `cui_button_ex` with only `.disabled=false` in an otherwise zero-initialized options record. This is the legacy Button style, not an explicit design-size, Ghost, icon-only or release-policy replacement. 4. The Button processes the entire accepted activation batch, paints and completes its normal work, then returns an aggregate bool. Alert assigns `*visible = false` **once, after that Button return**, if the bool is true and storage exists. It does not assign visibility inside a per-input hook. 5. End the Alert box and return that aggregate bool. With no visibility pointer, the same accepted Dismiss action still returns true. It cannot guarantee the caller will omit the Alert next frame. Multiple accepted Dismiss inputs can therefore produce one assignment and one true return. A slot setting visibility false before the Button does not cancel submission already in progress. It does not itself cause a true return. The existing assignment still runs after a true Button return even if the value is already false. An arbitrary action-slot child activation is not intrinsically an Alert dismissal. No ownership acceptance, veto, Escape/outside close policy, retained open state, animation completion or post-frame delivery exists here. Relevant regression evidence: - [Content](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_content.c) checks real Dismiss pointer input, subsequent hidden omission, light/dark Alert colors, SVG icons and semantics. - [Alert/Bubble slots](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_alert_bubble_slots.c) checks slot ordering and foregrounds, banner title suppression, interactive custom slots, accessible naming and initially false visibility suppressing slot execution. - [Button](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_components.c), `cui_button_ex`, registers the Button, iterates accepted events, calls legacy/typed click listeners per event, then paints. Its aggregate bool remains true for any accepted event. [The shared Button facade](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) exposes a different, per-input contract; it must not redefine Alert's assignment timing. These tests do not yet prove the proposed observer or the multiple-input and callback-driven visibility cases below. ## Recommended first additive API Add a native C-only `cui_alert_events` facade and dedicated pointer-free typed completion payload. Leave `cui_alert_options` and `cui_alert` unchanged. Proposed declarations, subject to implementation review: ```c typedef struct { cui_component_event_metadata event; bool visibility_assigned; } cui_alert_dismissal; typedef void (*cui_alert_dismiss_fn)(void *user, const cui_alert_dismissal *dismissal); typedef struct { cui_alert_dismiss_fn callback; void *user; } cui_alert_dismiss_handler; typedef struct { bool valid, submitted; size_t dismissal_count; bool legacy_dismissed; } cui_alert_dismiss_result; cui_alert_dismiss_result cui_alert_events( cui_context *, cui_id, const cui_theme *, cui_alert_options, cui_alert_dismiss_handler); ``` This is a **coalesced completed-dismiss-action observation**, zero or one notification per invocation. `dismissal_count` summarizes the eligible observed completed dismissal, never accepted input multiplicity or callback invocations. It is one when an ordinary active, non-omitted submission completes the built-in Dismiss action, independently of whether a callback is installed. Missing callbacks do not change interaction results. No overflow flag is necessary for this bounded 0/1 count. `legacy_dismissed` is exactly the bool the old function would return; passive/ineligible contexts retain that legacy bool independently of the observation count and cannot emit a notification. Reading the result does not dispatch or replay an observation. `visibility_assigned` records only whether the existing false assignment ran. It is true even when the value was already false; it is false when no storage was supplied. It is not a changed-value, accepted request, net transition, retained closed state or promise about what the owner submits next frame. The payload contains no owner pointer, message, slot resource or fabricated before/after value. Metadata describes the aggregate built-in action: `kind=ACTIVATE`, `target=public Alert ID`, `source=UNKNOWN`, and only `HAS_FRAME` with the actual active submission frame. UNKNOWN does not set `HAS_SOURCE`. `HAS_INDEX` and `HAS_ACTIVATION` stay absent; zero-filled unused fields are not evidence. Do not search for a last accepted child event after return, choose one of several inputs, claim a pointer origin, copy coordinates, or infer programmatic origin from the absence of input evidence. This deliberately conservative contract also applies when only one input happened. It does not label dismissal CLOSE, CHANGE, COMMIT or LIFECYCLE. [Toolbar's aggregate observer](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_toolbar_events.h) is useful precedent for bounded synchronous aggregate observation; its optional single-activation evidence recovery is **not** part of this Alert proposal. [Shared metadata](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_component_events.h) supplies immutable presence flags without requiring a new dispatch architecture. `valid` means the new facade's narrow preflight passed: nonnull UI/theme, nonzero ID, valid kind and structurally readable supplied string descriptors. This does not guarantee all later rendering succeeded. `submitted` means an ordinary active frame and a non-omitted Alert at entry. An initially false visibility value is a valid omission with `submitted=false`; a nondismissible Alert can submit normally with no dismissal. Inert/layout-only submission retains its legacy visual/slot behavior with `dismissal_count=0` and no user dismissal callback, independently of the legacy return. Do not introduce new legacy-entry rejection rules or suppress existing slots merely to normalize result bookkeeping. ## Preserve the existing owner-write boundary Implement the facade as a `static inline` function in the new dedicated `cui_alert_events.h`. Freeze the by-value options and handler, narrow preflight, ordinary active submission eligibility and actual frame identity at entry. Then call the existing `cui_alert` **exactly once**, including in passive contexts where its existing visual/slot behavior must remain untouched. The legacy call already returns after the optional owner assignment and `cui_end_box`. Store its unchanged bool in `legacy_dismissed`. The frozen operation fact `visibility_assigned = legacy_dismissed && options.visible != NULL` is sufficient: the legacy true return proves that its optional false assignment ran. Set `dismissal_count=1` only when the frozen entry eligibility and legacy bool are both true, regardless of handler presence. Freeze the frame-only payload, then invoke the optional observer before returning the result. No Button hook, second reduction, `content.c` hook, public options layout change or `content.h` declaration is needed. Passive/ineligible observation leaves the count zero; it must not suppress or rewrite any legacy operation. A private common implementation would also preserve the existing boundary, but is unnecessary for this coalesced slice. The header-only wrapper is preferred: it observes the actual legacy return directly, has no source ownership conflict, and leaves the zero-option Button invocation, child ID, text, paint, semantics, focus and input policy entirely in the existing function. This remains synchronous submission-time observation, not end-frame or a queued close event. Slot `user` and observer `user` remain independent. The observer sees the false assignment already applied if storage exists. It may deliberately set that owner value true again; the frozen payload, original aggregate bool and 0/1 dismissal count do not change. Such an owner write is not a second generated event and must not be overwritten after observation. Likewise, visibility changed by earlier title/body/action slots follows the existing single entry guard; do not recheck it to skip the Button or classify a fake transition. No callback return value may veto an action already accepted and assigned. Callbacks may copy the pointer-free payload or update application flags. Borrowed UI/theme/options/resources, caller visibility and slot/observer users remain alive through their existing submission/rendering boundaries. Copying this payload survives frame/context destruction; retaining its callback pointer does not. Recursive same-frame submission, context destruction, unwinding across C or freeing/rebinding active resources is unsupported. Request teardown and apply it after the frame. No guard, scheduler or destruction interception is added. ## Separate future alternative: detailed per-input activation A future, separately reviewed observer could hook the existing typed Button click boundary, retain genuine `cui_button_click_event`/activation evidence and report each accepted Dismiss input in reducer order. Public Alert identity and the real Dismiss child evidence target must remain distinguishable. No rewritten child snapshot, synthesized accepted event or general routing is justified. Those callbacks would execute **before** the Button returns, and therefore before Alert's one aggregate visibility assignment. They can see or change a different owner state from a completed-dismiss observer, and may consume later input before that input is processed. Moving `*visible=false` into that hook, stopping after the first input, or calling completion once per input breaks the legacy contract. The first slice above intentionally does not expose or count these per-input activations. Adding both observers later requires explicit dual-count and order proof; it is not permission to reinterpret `dismissal_count`. ## Required implementation proof and exclusions Before production, add meaningful real-input headless tests for: - Pointer and touch, Enter/Space and genuine supported accessibility Dismiss activation; preserve child semantics, exact Button pixels/options and legacy bool/visibility timing, including no listener and no visibility storage. - Two accepted Dismiss activations in one submission: the original Button batch completes, visibility is assigned once, completed observer runs once after box end, metadata has frame only, and the aggregate bool remains true. - Initial false visibility; nondismissible; hidden/invalid/inert/layout-only cases; no notification for custom child actions, hover, unrelated input or external visibility writes without accepted Dismiss activation. - Title/body/action order and independent users. Slots change visibility false or consume a later Dismiss input: preserve entry-only guard and actual Button outcome. Completed observer sees the applied assignment, can set visibility true again, and causes no extra synthetic completion or second assignment. - Null visibility storage still yields true plus one observation on accepted dismissal, with `visibility_assigned=false`. Already-false storage at the write boundary still yields assignment fact, not a fabricated transition. - Copied payload survives frame/context lifetime. An eligible completed dismissal has count one both with and without a handler; the callback-less case executes no callback and reading its result never replays one. Passive/ineligible contexts have count zero while preserving the independent legacy bool and mutations. Initial omission versus submitted state is explicit. Verify exact legacy drawing/semantic results alongside the new facade. - Strict portable C11 and C++ header checks; targeted `content`, `alert_bubble_slots`, Button event regressions and a new Alert observer CTest. On Linux run only through `python scripts/test_local.py --build-dir `; no desktop display or GPU parity claim. Approved implementation ownership: new `include/cui/cui_alert_events.h` containing all new types and the header-only facade, new focused tests and native consumer guide/example. The dedicated header includes the existing content header. Do not modify `src/components/cui_content.c` or `include/cui/cui_content.h`; neither is needed for this slice. Integrator owns registration, source metadata, generated SDK/distribution/skill refresh and ledger decisions. This checkpoint changes none of them. [The retained bridge](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/bridge/cui_bridge.c) currently constructs an Info Alert with title/detail and no dismissibility/visibility pointer; its arbitrary child actions are not this native operation. Python, Node/TypeScript, Go and Rust do not export these proposed native handlers/results, synchronous callback timing, owner-write facts or per-input activations. Existing foreign queued notifications are not native observer proof; see [binding coverage](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_BINDINGS.md). No binding hook, close/veto API, AlertDialog forwarding, dismissal policy, controlled request, or full Alert event parity is part of this slice. --- ## Alert announcements and Skeleton loading semantics: source audit Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/ALERT_SKELETON_SEMANTICS_AUDIT.md # Alert announcements and Skeleton loading semantics: source audit Status: design checkpoint, no production changes. Reference upstream kit `87d10ae5e1299d1be18670a37570c5402f952e34`, verified against the reference checkout; CUI audit baseline `9d4914830f29bcdd8b12517f21841fbdae17f631`. The two retained `not_started` feature rows describe different situations and must not be treated as equivalent missing component implementations. Preserve all 78 manifest entries. ## Frozen source requirements [Alert source](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/crates/component/src/alert.rs) implements `RenderOnce` at line 173. An invisible Alert returns `Empty`; a visible Alert's root explicitly calls `.role(Role::Alert)` at line 192. It composes icon, optional non-banner title, message and optional pointer close handler. This is positive evidence for an alert-role requirement. It does not establish that a particular OS or screen reader speaks the content, announces the initial mount, repeats identical text, or interrupts speech. The component source has no explicit announcement queue, delivery acknowledgement, utterance ID, or repeat policy. Its role call alone cannot prove the behavior of upstream's downstream accessibility implementation. This audit makes no such upstream AT claim. [Skeleton source](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/crates/component/src/skeleton.rs) contains a style refinement and `secondary` flag. `render` creates a `div`, applies size/background/style and a repeating two-second opacity animation. There is no loading boolean, role, accessible name, busy flag, content relationship, focus behavior or completion announcement in this component. Neither this source nor the associated frozen `website/component/skeleton.md` provides an explicit loading-semantics API. Decorative placeholders are therefore the demonstrated component scope. A meaningful loading region is an application composition, not an inferred missing upstream Skeleton feature. ## Existing CUI evidence and limits | Layer | Alert | Skeleton/loading | | --- | --- | --- | | Component | `src/components/cui_content.c:26` emits `CUI_ROLE_ALERT`, no tab stop; invisible alerts emit nothing. Name precedence is explicit accessible name, then message, then title. | Legacy `cui_skeleton` and extended `cui_skeleton_ex` paint boxes without semantic nodes. Extended API comment explicitly promises no focus stop or busy status. | | Core snapshot | `cui_semantics` exposes role, name, bounds and details. It is state, not a speech request or delivery receipt. | Existing `cui_interact` plus `cui_set_semantic_details` allow the application to expose a meaningful named region/status and its `busy` detail. A paint-only Skeleton cannot identify the actual loading operation. | | Native adapter | AccessKit mapping sets ALERT/ALERTDIALOG live assertive, STATUS/LOG live polite, and maps `details.busy`. | The same generic busy mapping is available for application-owned semantic nodes; no Skeleton-specific mapping is needed. | | Browser gallery | `web/gallery.js:670` maps role enum to DOM roles and `details.busy` to `aria-busy`. Stable IDs reuse DOM nodes. | `tests/web/test_status_motion.py` checks extended decorative motion emits no status/busy nodes. | | Live AT | Alert announcement delivery is not established by component snapshots, DOM assertions or existing native action tests. | No Skeleton utterance is required by the audited source. Application loading announcements still need transport and AT validation if claimed. | `include/cui/cui_content.h` exposes `cui_alert_options.accessible_name` and rich slots. For custom slot contents, a meaningful explicit name matters: the fallback message/title does not automatically summarize arbitrary children. The bounded `cui_bubble_announcement` enum selects GROUP/STATUS/ALERT semantic roles; despite its name it is not a Core announcement queue. Alert has no corresponding polite/assertive selector: its role matches the frozen Alert root. `tests/unit/test_alert_bubble_slots.c` checks Alert role, nonfocusable semantics, custom children and Bubble role selection. `tests/web/test_alert_bubble_slots.py` checks browser composition and interaction, not spoken announcements. Existing `tests/unit/test_status_motion.c` explicitly checks zero semantic nodes for extended Spinner/Skeleton, and preserves legacy Spinner's separate STATUS behavior. That legacy Spinner behavior must not be mistaken for Skeleton output. The AccessKit implementation at `backends/accesskit/cui_accessibility.c:192` already sets live attributes. It copies bounded snapshot strings, retains tokens for stable ID/role pairs, rejects invalid/capacity-overflow updates and suppresses unchanged snapshots. These are useful lifetime and idle guarantees. They also mean an unchanged Alert is not an event that must be resent every frame. A remove/reinsert or changed name is a tree transition; whether the platform emits an announcement, and its contents, requires evidence. There is no public announcement acknowledgement or guarantee that an unchanged identical message will be spoken again. The optional package is pinned AccessKit C 0.23.0 at `0824c4a1e3a4d13ce5582df20e394fba49485a15` (`third_party/accesskit/pin.json`). `backends/accesskit/root_bridge.cmake` explicitly supports Linux only and rejects cross compilation. `tests/integration/test_accessibility_native.c` verifies real private-session AT-SPI button/checkbox roles, bounds, focus/actions, relations, replacement and teardown. It does not create Alert/STATUS nodes or verify live region event delivery. Existing native tests cannot be cited as announcement proof. macOS/Windows adapters and their announcement delivery remain outside this package's demonstrated support. The gallery DOM mirror creates noninteractive alert/status `div`s with role and `aria-label`; it does not add a dedicated persistent live-text transport or explicit `aria-live` in `syncSemantics`. Role exposure and accessible naming can be tested headlessly. Initial insertion, label-only mutation and repeated identical content must not be advertised as reliably spoken without browser/AT evidence. The gallery mirror is also a host implementation, not a universal accessibility adapter installed for every CUI browser consumer. ## Actual remaining scope For Alert, the source-level role and Core representation already exist. The remaining reviewable work is transport-level evidence for Alert insertion, content change, removal and idle behavior; it is not automatically a new Core announcement API. Native live-attribute mapping exists but its platform event behavior is untested here. A complete live-AT claim additionally requires an opt-in screen-reader matrix, including initial mount versus update and naming of rich content. Do not promote the manifest row merely because role assertions pass. For Skeleton, retain the existing row as an explicit source-scope clarification. Do not add a busy flag or live announcement to every animated placeholder. A screen with twenty skeleton rows should have one application-owned loading region/status, not twenty competing utterances. The application owns transition from loading to loaded/failed, the text, and which region is busy. Existing Core semantic details can represent this without changing Skeleton or public structs. ## Bounded next slice for review Start with tests and an application-composition example using existing APIs; keep public APIs, Core dispatch, Skeleton and adapter ownership unchanged. 1. Add deterministic Core fixtures for visible Alert, unchanged rerender, changed explicit name, hide/reinsert, rich-content explicit naming and independent close/action descendants. Assert roles, names, no extra tab stop and omitted hidden subtree. Compose multiple decorative skeletons inside one named application region with `details.busy`, plus one application-owned STATUS message. Assert exactly the intended semantic nodes through loading, completion and failure, and unchanged output during animation frames. 2. Extend adapter-focused fixtures to inspect actual AccessKit node live/busy properties and token/diff behavior. If inspection needs a seam, keep it private and testing-only, consistent with current adapter counter hooks. Exercise bounded string/node failure without partial replacement and idle suppression. 3. Extend the existing private DBus/Xvfb AT-SPI integration harness to query Alert role and busy state and collect whichever live/text/property events the pinned adapter actually emits. First inspect the pinned AccessKit Unix source to establish supported event mapping; do not assume an announcement event exists. Assert only supported, observed event types and payloads, with bounded waits and no idle duplicate emissions. An unsupported event path is a documented adapter gap requiring a separate design, not a reason to invent a Core queue. 4. Add browser DOM tests for stable identity, role, name, busy transition, removal and absence of decorative placeholder semantics. If a browser transport change is necessary, review it separately with persistent live-text region behavior and bounded deduplication/repeat semantics; snapshots alone cannot certify it. All native tests use `scripts/test_local.py` and the adapter's private-session runner, never the maintainer's desktop or accessibility bus. Browser tests remain headless. Use strict C11 warnings and focused CTest targets; no dependency install or live screen reader is part of automated tests. Keep actual speech perception, interruption/coalescing, user preferences, browser/screen-reader combinations and macOS/Windows delivery explicitly deferred until opt-in validation exists. If later requirements include repeating identical announcements or delivery acknowledgement, propose an independent bounded host transport with copied UTF-8, explicit lifetime/overflow/coalescing rules and platform support evidence before adding any public API. Those requirements are not proved by the frozen component sources and are outside this next slice. Metadata/skill updates and any row classification remain integrator-owned after the chosen evidence is reviewed. ## Bounded proof implementation (after this audit) `examples/loading_region` now provides compiling application composition, Core snapshot output and a focused external CMake harness; corresponding new Core and headless DOM fixtures exercise transitions without changing public APIs. `test_native.c` uses the existing verified optional cache and private DBus/Xvfb runner to receive real AT-SPI announcement events, not synthetic callback events. Core/native focused tests passed 2/2 in normal and ASan/UBSan builds; the production-gallery-translator DOM fixture passed in headless Chromium. No native window or screen reader was launched. Inspection of the lockfile-selected `accesskit_atspi_common` 0.20.0 found named live-node insertion announcements in `adapter.rs:add_node`, changed-name announcements in `node.rs:notify_property_changes`, and live politeness mapping in `node.rs:live`. `accesskit_unix` 0.23.0 `atspi/bus.rs` serializes message and politeness in `object:announcement`. The real fixture verifies Alert insertion, changed name, hide/reinsert and idle deduplication, completion STATUS politeness, and busy true/false. The pinned Unix role mapping exposes AccessKit Alert as AT-SPI Notification (AlertDialog maps to AT-SPI Alert); this mapping is asserted without changing production code. Existing client cache-signature warnings do not prevent the direct queries or event assertions, but remain a compatibility observation. See the example README for commands and remaining live-AT/platform limits. No manifest status promotion follows automatically from these results. --- ## Attachment action observation checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/ATTACHMENT_EVENTS_SLICE.md # Attachment action observation checkpoint Design only, audited at `46506c9d`. Proposed names below are not implemented. Preserve all 78 manifest entries, the legacy options/result/state layouts and the existing callback timing. This is a direct C action facade, not foreign callbacks. ## Existing contract and seams The public [media API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_media.h) separates a pure Base attachment layout planner from the Styled interactive attachment. The planner has no interaction or action to dispatch. Styled owns no upload/request state: status/progress/options belong to the caller. Image loader and render hooks are resource/presentation callbacks, not action handlers. [Styled implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_media.c) validates first, plans, begins a focus scope, registers a pointer-activatable GROUP for the card only when identified and `on_click` is present, then submits content/actions/media portals. Remove/retry visibility depends on the corresponding legacy function pointer. Retry can originate in a media control or a description LINK; description retry IDs derive from the metadata subtree, not the card retry ID. Custom action children have their own controls and callbacks, outside these three channels. The three result flags are aggregate booleans. After original paint submission and tooltip work, callbacks run in fixed order: click, remove, retry, followed by focus-scope end. Each category invokes at most once per submission even with multiple inputs. This is category order, not global input order. Reading the result never invokes callbacks. Loading is not a universal disable flag: the old planner decides available actions by status/identified/touch/hovered state. There is no existing editable attachment value, owner rejection or submit event. ## Proposed compatible facade A new `cui_media_events.h` may include media plus shared metadata and declare: ```c typedef enum { CUI_ATTACHMENT_ACTION_OPEN, CUI_ATTACHMENT_ACTION_REMOVE, CUI_ATTACHMENT_ACTION_RETRY } cui_attachment_action; typedef struct { cui_component_event_metadata event; cui_attachment_action action; } cui_attachment_action_event; typedef void (*cui_attachment_event_fn)(void *, const cui_attachment_action_event *); typedef struct { cui_attachment_event_fn on_activate, on_remove, on_retry; void *user; } cui_attachment_handler; typedef struct { cui_attachment_result control; size_t activation_count, remove_count, retry_count; } cui_attachment_event_result; cui_attachment_event_result cui_attachment_events( cui_context *, cui_id, const cui_theme *, cui_attachment_state *, cui_attachment_options, cui_attachment_handler); ``` Call the complete legacy Styled operation exactly once. Synchronous stack thunks replace only categories having a new observer; each invokes the original callback with its original userdata, then the new observer. Other existing callbacks still need their original userdata through corresponding forwarding thunks if the shared `action_user` is replaced. Never replace one category and accidentally pass thunk userdata directly to another old callback. No retained registration/global state, heap allocation, input replay or new reducer is required. A new typed handler also enables that category when its old callback is absent, using the same existing planner/interaction path. An absent typed handler leaves the category availability unchanged. Missing all typed observers calls the old operation directly. Do not manufacture an observer from a true paint-valid flag. Count actual callbacks only; each category is zero or one, retaining coalescing. The old API is unchanged. Its booleans remain observations, not accepted requests. Use ACTIVATE metadata for each action; removal/retry are requested application actions, not proof that host deletion/upload happened. No CHANGE, COMMIT, SUBMIT or lifecycle event is inferred. New callbacks cannot retroactively consume input, stop propagation, prevent a platform default or veto an already observed action. ## Evidence and lifetime rules Snapshot evidence before the first legacy action callback can mutate application state. Map only actual possible control IDs: card, remove, media retry and every eligible description retry. Prefer capturing at the existing actual interaction seam if scanning cannot identify the real category without ambiguity. A unique accepted activation with a genuine snapshot retains its original source/index and activation target; metadata target remains the attachment compound. Multiple causal activations coalesce and cannot be represented by an arbitrary first/last snapshot: report proven frame with UNKNOWN source and no index/activation then. Do not guess a description retry ID from the card retry ID. Current Core accepts LINK accessibility ACTIVATE and pointer-activatable GROUP ACTIVATE after prior semantic registration. Preserve this existing allowlist; do not fabricate support before registration or invent keyboard behavior. New notification eligibility requires an active, paint-enabled, non-inert frame. Preserve passive/layout/omitted and status-dependent legacy work; never globally suppress loading actions that the old component allows. Preserve consumed/cancelled activation behavior at the actual old seam. Custom child actions do not become attachment action events merely because they are inside the card. Metadata/action payload is pointer-free, copyable and independently owned after copying. Handler/userdata are borrowed during this call only. Original callbacks retain old order and side effects. They must leave resources needed by the rest of the original operation and the new observer live. The new observer cannot mutate/free/rebind active state/options/children/context, recursively submit UI, or destroy the context. Unrelated flags and copying payload are supported; defer removal and teardown until outer return plus renderer consumption. A local thunk must never escape into retained state. ## Review and verification boundary Before production, verify all callback enablement, actual ID/evidence and suppression seams against the current source and existing media tests. If faithful causal capture needs a narrow internal observation hook, review that implementation choice before editing the reducer/presentation loop. Do not silently convert the old three aggregate callbacks into per-input callbacks. Proposed worker ownership: new public header, the Styled media source, new focused Attachment event test, new guide, this checkpoint status. Root owns build/WASI/docs registration, generated distribution/SDKs and resource generation. Base planner, Core, binding schemas and other families remain outside this slice. Meaningful headless proof must cover old/new owner/options/result/semantic/paint compatibility; original userdata and click/remove/retry order; missing old/new handlers; typed-only category availability; repeated activations and category coalescing; unique and ambiguous pointer/keyboard/accessibility evidence where actually supported; media versus description retry; status/identified/touch/hover availability; custom child action isolation; inactive/passive/inert/omitted calls; callback/result coexistence without replay; copied payload and deferred removal. Use strict C11/C++ header checks and the private native wrapper. Existing image and attachment/group tests remain regressions; no visible desktop tests. Foreign bindings retain their existing queued generic notifications unless separately implemented and tested; including this header in SDKs is not a language facade. ## Approved implementation refinement: private common hook The stack-thunk strategy above is superseded by a narrow private common entry in Styled media. Legacy `cui_attachment` passes no descriptor; the new facade passes its borrowed handler/result. No public old layout changes. Availability is the original matching callback OR new matching observer. The final fixed click/remove/ retry blocks invoke each original callback with the untouched `action_user`, then the typed observer. Missing all typed observers uses the exact old path. Use three fixed stack collector slots, no allocation/workspace/input replay. Collect only when the actual old `interaction.activated` is true, immediately at that seam before later custom rendering or legacy action callbacks can change focus/evidence. Record a unique genuine accepted snapshot when available; multiple accepted inputs/control origins coalesce to proven-frame UNKNOWN without index. Missing accepted evidence also gets frame-only UNKNOWN, never a fabricated index. Freeze category metadata before the first legacy action callback; dispatch still occurs at the original category callback point before `end_focus_scope`. Actual IDs and eligibility audited in current Styled/Base media: - Card uses compound ID, identified and (old click OR typed activate). Capture after existing GROUP interaction/details; loading does not disable it. - Remove uses `cui_attachment_remove_id(card)` only when planner remove_visible and prior tracked card width >0; planner requires identified, remove handler availability and touch/hover. Loading does not disable removal. - Media retry uses `cui_attachment_retry_id(card)` only when retry_media and prior tracked media width >0. Retry requires identified, FAILED, retry availability. - Description retry uses `media_id(attachment_retry_id(media_id(card,4)), child_index+1)`, not the card retry ID. Only the first non-TITLE/non-CUSTOM child when retry_description gets the LINK; a child status override does not independently gate it. Pass the collector to this existing private metadata helper rather than duplicating its child eligibility logic in an outer scan. The collector observes accepted activation evidence only, never reducers or input consumption. It does not change GROUP/LINK accessibility routing. Current Core accepts LINK and pointer-activatable GROUP ACTIVATE after previous semantics exist; before first registration queue admission correctly fails with INVALID_ACTION. Tests must include media/description retry, unchanged shared userdata/order, and a late legacy callback that changes focus after evidence was frozen, plus payload copying. Production is authorized only after this refinement is committed. ## Implementation checkpoint The common hook and three fixed collector slots are implemented in Styled media; Base and Core remain untouched. Tests compare legacy/facade paint, semantics, tracked bounds, focus/redraw, aggregate results and old callback counts; prove unchanged userdata/category order, typed-only and mixed-handler availability, media/description retry, repeated activation coalescing, unique pointer/key/a11y snapshots, late old callback consuming live evidence, custom action isolation, status/identified/touch/media matrix, passive/inert suppression, uploading OPEN/REMOVE, copied payload and deferred omission. Existing media suite passes. The earlier overbroad GROUP/LINK limitation is corrected against current Core; new fixture explicitly verifies failed queue admission before first semantics. No foreign binding or complete family parity claim follows from this slice. --- ## Avatar activation and render-family coverage checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/AVATAR_EVENTS_SLICE.md # Avatar activation and render-family coverage checkpoint Status: **proposal only; no Avatar event facade is implemented by this document**. Source checkpoint: `faa07960`. This is a documentation-only review of the current C implementation and twenty N rows in [remaining coverage](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_REMAINING.md). That matrix and the older [coverage inventory](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_COVERAGE.md) are intentionally unchanged pending integrator review. The shared [contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_CONTRACT.md) still applies. No production API, routing, capture/bubble, Core dispatch, legacy callback timing or binding behavior changes. Tests below were inspected, not newly executed for this checkpoint. ## Coverage correction for review The historical Avatar row is incorrect. `cui_avatar_ex` owns an interactive BUTTON, consumes matching activation events and returns an aggregate activation bool. `cui_avatar_stack` owns the visible children's composition and aggregates an activated item index. These are existing family behaviors, not merely arbitrary controls supplied by a render callback. The legacy `cui_avatar` void helper is presentational, but cannot justify classifying every Avatar entry point as N. Recommended current disposition: **G, direct activation observer gap**, with legacy initials/image rendering separately described. A proposal does not make this A or establish complete Avatar parity. Alert also needs a narrower correction. `cui_alert` constructs its own Dismiss button when dismissible, returns that button's aggregate activation bool, and writes `*visible = false` when a visibility pointer exists. Its return is not successful submission. Suggested disposition: **G, built-in dismiss observation gap plus arbitrary child composition**. A separate Alert proposal must preserve its post-content dismissal order, optional owner write, and child button evidence; it must not call a successful composition result a lifecycle close. The other eighteen N entries remain justified for current standalone entry points, with the explicit distinctions below. Merely calling `cui_interact` to register a semantic label/group/table does not establish an activation channel. Custom role overrides and application-supplied callbacks can compose interactive controls; these do not automatically become a family reducer or observer. | N family | Current source seam inspected | Proposed disposition and reason | | --- | --- | --- | | Alert | `src/components/cui_content.c:cui_alert` | G: intrinsic Dismiss result and optional visibility mutation; arbitrary action/content callbacks stay separate. | | Avatar | `src/components/cui_content.c:cui_avatar_ex`, `cui_avatar_stack` | G: direct opt-in activation and aggregate bool/index. Legacy void Avatar remains presentational. | | Badge | `src/components/cui_components.c:cui_badge_ex` | N: invokes caller content and paints a marker; true is valid composition, not badge activation. | | Bubble | `src/components/cui_content.c:cui_bubble`, `cui_bubble_reactions` | N: reaction/content functions are supplied by the application; the pill helper calls that renderer, not an intrinsic reaction reducer. Measurement invalidation is separate. | | Empty | `src/components/cui_content.c:cui_empty_ex` | N: typed slots and optional children compose controls; successful submission is not activation. | | Focus Trap | `src/base/cui_overlay.c:cui_overlay_begin`, `cui_overlay_end`; `include/cui/cui_overlay.h` | N primitive exception: caller-owned scope begin/end and explicit overlay operations; completed Surface close is a different API. Preserve the existing reviewed exception. | | GroupBox | `src/components/cui_content.c:cui_begin_group_box`, `cui_end_group_box` | N: presentation and child scope only. | | Kbd | `src/components/cui_content.c:cui_kbd` | N: chord presentation, not keyboard input capture or command activation. | | Label | `src/components/cui_components.c:cui_label`; `src/components/cui_label.c:cui_label_source` | N: text/label composition and relationships, no activation observer owned here. | | Marker | `src/components/cui_status.c:cui_marker` | N: text/icon/custom-child presentation and loading motion; children own their controls. | | Message | `src/components/cui_message.c:cui_message` | N: sender/avatar/body/footer slot composition, true means valid submission; MessageScroller scroll events are separate. | | Progress | `src/components/cui_components.c:cui_progress_ex`; `src/components/cui_components.c:cui_progress_circle` | N: value projection/motion/presentation; no owner value mutation or completion notification inferred. | | Shimmer | `src/components/cui_status.c:cui_shimmer_text` | N: time-driven text paint; role registration is not activation or animation completion. | | Skeleton | `src/components/cui_content.c:cui_skeleton_ex` | N: caller loading motion is sampled and committed after successful paint, not an input action or loading-completion event. | | Spinner | `src/components/cui_content.c:cui_spinner_ex` | N: easing/paint functions are policy/presentation; motion result and successful paint do not mean activation or completion. | | Tag | `src/components/cui_status.c:cui_tag`, `cui_begin_tag` | N: label semantics/style, optional child composition; no built-in click/remove path. Hover styling alone is not activation. | | Form | `src/components/cui_form.c:cui_form` | N: field rendering/association and layout error result; child validation, input events and application submit buttons remain separate. Input Group is independently covered. | | DescriptionList | `src/components/cui_description.c:cui_description_list` | N: labels/value callbacks; no direct selection/activation reducer. | | StatusBar | `src/components/cui_chrome.c:cui_status_bar`, `cui_chrome_region_draw` | N: supplied render callbacks own input; default items are LABELs. TitleBar's built-in controls are a separate family. | | Table | `src/components/cui_table.c:cui_table_begin_ex`, row/cell/head/caption helpers | N for basic table composition: semantic registration and validity checks, no sorting/selection reducer. DataTable's built-in selection/sort paths remain separate. | This is all twenty N rows, recommending two corrected gaps and eighteen retained render/child/primitive classifications. It does not re-audit the other fifty-eight families or promote any of the original seventy-eight manifest entries. ## Existing Avatar timing, aggregation and evidence The authoritative [header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) and [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_content.c) establish these distinctions: 1. `cui_avatar` draws initials and IMAGE semantics; it has no activation result. Cache preparation, palette and metrics helpers are resource/pure operations. 2. `cui_avatar_ex` validates UI/theme/nonzero ID, prepares the current image, begins its box, calls `cui_interact` with BUTTON only when `interactive`, submits photo/icon/initials, ends its box, updates semantic/focus/cursor details, then scans frame events in increasing Core event-index order. 3. Each event satisfying the existing `interactive && !disabled && !consumed && cui_event_activation(ui, index) == id` gate is consumed. The returned bool becomes true and remains true. Multiple matching inputs therefore produce one true bool while every matching event is consumed. The bool is neither a submission-success result nor proof that a host opened a profile. 4. No existing Avatar action callback runs. Image/icon preparation and any existing resource-loader policy still occur at their original earlier point. Do not move them after new notifications. The caller acts after return; there is no old action userdata to forward. The new facade must preserve this old path and its consume/paint order, rather than add callbacks to old options. 5. Stack children are submitted in increasing visible item order. Each child runs the complete Avatar operation, and the stack replaces its result index whenever a child reports true. Multiple activated items yield the highest activated visible index, **not the index of the chronologically last input**. An overflow badge is a passive IMAGE and never an activation target here. Hidden items are not submitted. Later painted overlapping children retain their existing hit-test priority. Current Core routing is evidence to preserve, not an Avatar-specific rewrite: - Pointer/touch activation comes from the routed accepted release/capture path; cancellation, consumed input, hit priority and prior bounds matter. Do not infer activation from hover, pointer-down, or successful bitmap preparation. - Avatar does not set `release_key_activation`. Its current default Core policy activates Enter on a nonrepeat key-down and Space on the matching key-up after capture; do not silently replace it with source Button's release-key policy. Focus changes, modifiers, cancellation and competing consumers need explicit regression tests rather than broad claims based on role alone. - Accessibility ACTIVATE requires prior supported semantics. Interactive BUTTON and its pointer-activatable details are supported by the current Core allowlist. Queue admission before first semantic registration can fail; current role/disabled/modal eligibility must still hold during submission. Passive Avatar IMAGE/no-focus is not an activation promise. Browser semantic evidence is not a tested native screen-reader integration. - `cui_interact` records accepted activation snapshots; the later explicit `cui_consume_event` can clear them, especially accessibility and release-key slots. Freeze the genuine snapshot immediately before consumption at the existing event-loop seam. A wrapper scanning only after `cui_avatar_ex` returns loses information and cannot faithfully recover multiplicity. - A raw legacy gate match is not automatically proof of an accepted snapshot. If supported active submission reaches that gate without accepted evidence, retain only proven frame and target, with UNKNOWN source and no index or activation flags. Do not fabricate a source/index from the aggregate bool or change the legacy gate in order to make metadata convenient. Dedicated tests must establish when this fallback can occur. Inspected regression evidence: [content tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_content.c) cover stack overlap pointer selection, Enter, cancelled touch, disabled suppression, named/passive semantics, cache failure recovery and real software pixels. They do **not** establish Avatar multi-input counts, Space timing or accessibility metadata snapshots. [Button events](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_control_events.c) and [Attachment events](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_attachment_events.c) illustrate proven per-event versus coalesced evidence capture, but are not Avatar proof. ## Proposed additive C API, not declarations currently available Use a new `cui_avatar_events.h` including Content and the existing Control event vocabulary. Do not modify existing option/result layouts. Proposed phase one: ```c cui_component_action_result cui_avatar_events( cui_context *, cui_id, const cui_theme *, cui_str name, cui_avatar_options, cui_component_activation_handler); ``` Reuse the existing `{callback, user}` typed activation handler and `cui_component_action_result`: `valid` is preflight only; `submitted` is ordinary active paint-enabled, non-inert submission (including disabled/passive Avatars); `activation_count` counts events accepted by the observed legacy loop, whether or not a handler is installed; `request_count` is always zero. Counts saturate with `count_overflow` while dispatch continues. The old bool API remains exactly as before. In this new API `activation_count > 0` is its aggregate activation observation; reading/copying the result never redispatches. A handler does not implicitly enable `interactive`: options continue to control role and routing. Missing handler still preserves legacy consumption and result counts. Add a narrow private common Avatar entry with an optional observer/result. Legacy `cui_avatar_ex` passes neither. The facade calls that operation once; never submit twice, replay input, or infer per-event counts from `interaction`'s aggregate flag. Inside the existing loop: freeze evidence, perform original consumption and bool update, increment the count, then call the observer synchronously before continuing to the next event. Metadata kind is ACTIVATE, target is the Avatar ID, and a genuine snapshot supplies its original frame/index/source/contact/key evidence. Photo/icon/initials painting has already been submitted at this point. No CHANGE, COMMIT, SUBMIT, resource-loading or host-profile-open event is implied. The later stack addition is separately reviewable after that seam is tested: ```c typedef struct { cui_component_event_metadata event; size_t index; uint64_t key; /* Original application key, including zero. */ } cui_avatar_stack_activation; typedef void (*cui_avatar_stack_activation_fn)( void *, const cui_avatar_stack_activation *); typedef struct { cui_avatar_stack_activation_fn callback; void *user; } cui_avatar_stack_handler; typedef struct { size_t control; /* Legacy aggregate index, or SIZE_MAX. */ cui_component_action_result action; /* request_count remains zero. */ } cui_avatar_stack_event_result; cui_avatar_stack_event_result cui_avatar_stack_events( cui_context *, cui_id, const cui_theme *, const cui_avatar_item *, size_t count, cui_avatar_stack_options, cui_avatar_stack_handler); ``` Forward each visible child's observed activation immediately in existing child-submission order, then that child's event-index order. Do not sort events across children, coalesce per item, or mistake `control` for last input time. The payload's metadata target is the compound stack ID; its genuine activation snapshot retains the child target. Freeze index/key by value before dispatch; key zero retains its documented index-derived identity behavior, and must not be silently replaced in the payload with a synthetic key. The old stack function uses no observer and preserves its aggregate result. Stack headers, semantics, overflow behavior, visible-item planning and stable ID formula remain untouched. A stack observer does not become an observer of arbitrary controls around it. ## Mutation, lifetime and unsupported operations Handlers/users/payload pointers are borrowed only for synchronous submission. Metadata and proposed stack payload are pointer-free, copyable by value beyond frame/context lifetime. Rendering resources, source pixels, cache storage, labels, typed icon state, item arrays and users retain their existing lifetimes through submission and, where required, completed rendering. No callback is registered on a retained Avatar or image cache. As with Button, copying payloads, changing unrelated application flags and requesting later omission/teardown are allowed. Consuming later events or changing focus can change later eligibility; freeze one event at a time and do not prequeue the whole submission. Changing caller-owned options affects later calls; never read mutable options back after the call-local descriptor snapshot. Do not mutate/rebind/free the active stack items, active resources or userdata, recursively submit the same component/frame, or destroy the active context. No local wrapper can provide a reliable use-after-free guard. Perform teardown after outer submission and renderer consumption. The facade neither grants capture/bubble control nor returns an acceptance/veto decision to Core. Original APIs have no added callback or timing change. The reviewed [Attachment approach](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/ATTACHMENT_EVENTS_SLICE.md) preserves old callbacks before its observer and deliberately coalesces categories; Avatar must not copy that aggregation rule. [Button's checkpoint](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_ACTIVATION_SLICE.md) provides the relevant per-event and mutation vocabulary. Existing callers may continue to act on legacy bool/index; recommend one side-effect path when a caller adopts new callbacks/results. ## Required proof before an implementation can be integrated - Legacy versus no-handler facade equivalence: draw commands/software pixels, semantics, cache revisions, focus/tab/cursor state, consumed events and bool or stack index. Photo/initial/icon/palette/design-size options are unchanged. - Several pointer/touch/Enter/Space/AT activations in one call: exact counts, callback order and copied genuine metadata, plus repeats/cancel/consumed origins. Enter down versus Space release and before-first-registration AT rejection need dedicated Avatar tests; inspect accepted snapshots before consumption and prove retained copies survive later event consumption. - Disabled, passive IMAGE, inert/layout-only/prepaint/measurement/outside-frame, omitted component, invalid ID, modal/role changes and error cases: no new notification is invented. Preserve legacy return behavior even when no observer is eligible; do not silently repair Core/routing behavior here. - Multiple stack items activated in reversed input order: callbacks retain child/event order and aggregate `control` retains the highest activated visible index. Verify stable/zero keys, overlap hit priority, narrowed width, hidden items and passive overflow; no extra callbacks for container paint. - Handler consumes a later event, changes focus, copies payload, and marks a sibling/panel for later omission. Verify event eligibility is checked live, payload evidence remains frozen, original descriptors remain intact, and active storage is freed only after the documented boundary. - Missing handler still yields counts without replay; one result read never redispatches. Counter saturation uses a small helper fixture, not an enormous input allocation. New API preflight distinguishes validity from paint success. - Strict portable C11/C++ header checks and meaningful unit/software tests use `python scripts/test_local.py --build-dir ` for invisible Xvfb. Any browser test stays headless. No GPU/native assistive-technology claim follows from synthetic Core or Chromium evidence. Production authorization is a later review. Proposed worker scope: new Avatar events header, Avatar-only private common entry and stack forwarding, focused unit tests, guide and a real owner example. Root owns event-family registration, coverage-matrix correction, SDK/binding exposure, distributions and consumer skill resources. Merely shipping C declarations through language SDKs is not a working foreign-language callback facade. Keep all seventy-eight frozen manifest entries and treat Video as its existing separate extension. --- ## Versioned background commands and five-adapter preparation Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/BACKGROUND_V2_RECORDS.md # Versioned background commands and five-adapter preparation Proposed records/contracts only, following approved transport B. Values/math are implemented by `2a435a5f` + `cf72b10e`. The integrator reviewed and approved the contract through `638fc225`; checkpoint2 now implements Core mode/storage/emission/setters only. Checkpoint3 supplies the private allocation-free CPU query/raster helper described in [BACKGROUND_PREPARATION.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BACKGROUND_PREPARATION.md). Adapter queries/renderers, upload lifetimes and bridge/wire records below remain proposals. V1 `cui_draw_command`, `cui_draw_list`, `cui_config`, `cui_renderer`, their enums, functions and default output remain unchanged; V1-only contexts allocate no V2 buffers. No context lookup, new V1 tag, transparent placeholder, incomplete V1 list or V1/V2 array cast. ## Concrete portable records and frame handshake New supplemental header `cui_draw_v2.h` includes the existing public headers (including `cui_background.h`): ```c #define CUI_DRAW_ABI_V2 2u /* Constants 0..8 explicitly equal existing V1 kinds; do NOT extend cui_draw_type. */ #define CUI_DRAW_V2_BACKGROUND 9u #define CUI_DRAW_V2_FEATURE_BACKGROUNDS UINT64_C(1) #define CUI_BACKGROUND_OUTPUT_SRGBA8_CENTER_V1 1u typedef struct { cui_rect bounds; cui_corner_radii radii; cui_background brush; /* OWNED fixed-two-stop value. */ float opacity; /* Already resolved ancestor product. */ } cui_background_draw_v2; typedef struct { uint32_t kind; union { cui_draw_command legacy; /* Active for kinds 0..8. */ cui_background_draw_v2 background; } payload; } cui_draw_command_v2; typedef struct { uint32_t header_size, abi_version; size_t command_stride; const cui_draw_command_v2 *commands; size_t count; float width, height; uint64_t required_features; uint32_t background_output; cui_error error; /* Non-OK list MUST NOT render/clear. */ } cui_draw_list_v2; typedef struct { uint32_t size, abi_version, background_output; uint64_t features; size_t max_commands, max_backgrounds; size_t max_pixels, max_pixels_per_background; size_t cpu_bytes, texture_bytes, transfer_bytes, metadata_bytes; } cui_draw_v2_support; typedef struct { uint32_t size; cui_draw_v2_support support; /* Actual consumer query, before begin. */ uint64_t required_features; size_t command_bytes, background_bytes; } cui_frame_v2_options; bool cui_begin_frame_v2(cui_context *, float w, float h, float dt, const cui_frame_v2_options *); bool cui_end_frame_v2(cui_context *, cui_draw_list_v2 *out); bool cui_set_background(cui_context *, const cui_background *); /* Open box. */ bool cui_element_set_background(cui_context *, cui_id, const cui_background *); ``` Version, header size and stride must equal this exact record version; do not guess prefix compatibility. No serialized representation is the raw struct/union/padding. V1/V2 pointers are incompatible C types; an explicit unsafe cast is outside the contract, not something runtime negotiation can make safe. For legacy kinds, `payload.legacy.type` must equal `kind`; all existing payload semantics remain intact. Inactive union bytes are ignored. Unknown kind, feature, policy, version or stride fails before any array traversal/target mutation. The background feature initially means BOTH models and BOTH interpolation spaces; no misleading partial-support bit. New policy versions require new negotiation. All five consumers expose a separate V2 support query and V2 render entry point; there is no extension to V1 renderer structs. Query actual initialized consumer, font/target policy and resource limits. Host queries BEFORE composition and passes support by value to begin; Core copies values, never an adapter/context association. A copied V2 array can consequently be rendered by any compatible V2 consumer. Missing symbol/old adapter/unsupported host means do not start a V2 background frame. Capabilities are an ordinary caller contract, not protection from fabricated C records. A changed/lost target after query can still fail render without replay. Zero byte-budget options select the documented defaults; null options, wrong record sizes/versions/unsupported features use INVALID_ACTION, allocation/budget failures CAPACITY. Existing lifecycle errors remain LIFECYCLE. Begin validates sizes/feature subset/limits and reserves optional storage BEFORE opening a frame or consuming queued input. Failure leaves no frame active and input queued. Existing begin starts V1; new begin starts V2. Background setters reject V1/outside-frame/measurement/prepaint/diagnostic reentrancy before modifying paint, with lifecycle diagnostics. A V2 frame must also have requested the background feature; otherwise setters reject before mutation. They never enable features implicitly. A legacy-only V2 frame needs no background map/storage. Wrong end function reports LIFECYCLE, returns an empty error result, and leaves the frame open without layout finalization or dispatch. Caller may clear the error and call the matching end exactly once; callbacks are not replayed. Matching end closes the frame once even on layout/conversion/capacity failure. V2 failure sets out to an ABI2 empty list with non-OK error and returns false; V1 wrong-end returns its existing zero list and sticky context error. Null V2 out is rejected before closing. Reentrant/multiple begin/end follows existing lifecycle guards. ## Ownership and bounded retained storage The brush is owned by value, NOT the entire command's resources. A Core-produced array lasts until next begin (either mode) or context destruction. Legacy strings, paragraph data, spans and text stops retain their existing frame lifetimes; bitmap pixels, mesh vertices, fonts/provider backing retain their existing borrowed-through-render-completion contracts. Copying/reordering a V2 command array copies brushes without lookup restrictions, but does NOT deep-copy those borrowed resources. A full snapshot/export must explicitly copy all payloads and rebase typed references. No full snapshot helper is implied by this slice. Optional V2 storage is reserved during explicit V2 begin, before opening it; retain its bounded capacity for reuse until context destruction, not another copy per frame. Default proposed ceilings: command_bytes=16MiB, background_bytes=512KiB; hard maxima16MiB each, checked against SIZE_MAX/PTRDIFF_MAX before allocation. Command capacity is min(config.max_commands,16384,support.max_commands, command_bytes/sizeof(cui_draw_command_v2)); count all clips and expanded decoration. Background capacity is min(config.max_elements,4096,support.max_backgrounds), subject to actual sizeof records plus config.max_elements*sizeof(uint32_t) optional node-slot map fitting background_bytes. Default4096-node map costs16KiB;4096 approximately88-byte owner/value records cost352KiB on a common64-bit ABI. Use actual sizeof/alignment, never those estimates, for budgeting. Large element configs may require larger explicit background_bytes or fail begin before input. Retained capacities are high-water marks bounded by those hard maxima (at most 32MiB additional Core payload storage); lowering a later frame's logical budget does not silently shrink retained storage or allocate another copy. V1 existing arrays/prepaint arrays/frame_bytes/resource_bytes remain separate; these ceilings are ADDITIONAL memory, not a claim of total context footprint. No raster/pixel/upload storage lives in Core. No unconditional V1 node growth or pre-attached custom paint: optional owner map indexes already owned current nodes. ## Setters, identity and precise Core seams NULL clears the override and restores the original box background; transparent SOLID replaces it with transparent fill. Last valid setter wins atomically per owner. Copy/validate the value and reserve a new slot before mutating node/custom configuration. Replacement reuses its slot; clear of an existing slot never allocates; cleared slots remain reusable by that owner until next frame. Budget counts distinct touched owners, not calls. Bad values/capacity/identity preserve the previous override and all shadows/underlays/outline/prepaint ownership. Open-box setter supports the actual open anonymous or named paint node. Named setter requires nonzero ID already submitted in THIS frame, open/closed/portal; reject missing/layout-only/suppressed targets and ambiguous duplicate/folded-ID collision frames. Reuse the guards in `cui_element_set_box_shadows`: current node ownership, matching internal map/config userData, no text/exiting/previous node. Do not invent anonymous IDs or expose the private layout engine. Existing late collision detection remains authoritative: failed frames publish no valid V2 list. Neither setter changes nodes, layout, semantics, event targets or callback timing. Clearing must retain other custom-paint owners; an installed V2 custom shell may remain through this frame only if ordinary output/order still matches exactly. No-setter V2 frames wrap exactly the same ordinary command sequence as V1. Refactor `src/core/cui.c:cui_end_frame` into one guarded finalizer with an internal V1-or-V2 emitter. Keep V1 emission code behavior; V2 wraps ordinary local commands and emits its background payload directly. NEVER produce/return an incomplete V1 list and repair it later. Existing `cui_prepaint_emit` continues accepting only valid V1 commands, which the V2 emitter wraps; no new tag sneaks through prepaint. Core's CUSTOM branch currently orders DROP list, outside outline, box fill, INSET list, mesh, locally clipped underlay, prepaint, children; deferred prepaint and portal/layer sorting retain their current positions. Replace ONLY box fill; background is emitted even when the original byte alpha was zero. Keep existing ancestor clips, separate outline/shadow radii and all shadow phases. Underlay's local clip must not become an ancestor clip for DROP. No extra clip wrapper that clips children/portals differently. Resolve bounds/radii from current final layout; individual corner radii clamp to half min(width,height), matching existing shapes. Store inherited opacity as one float, leave brush endpoints unchanged, apply that opacity once during preparation. Legacy opacity truncation remains unchanged. ## Shared CPU preparation, physical coverage and output policy New private allocation-free query/raster helper uses the approved common sampler. Proposed portable records, with checked size/version rather than appended V1 fields: ```c typedef struct { uint32_t size, background_output; unsigned viewport_width, viewport_height; float scale_x, scale_y, origin_x, origin_y; size_t cpu_bytes, texture_bytes, transfer_bytes, metadata_bytes; size_t max_pixels, max_pixels_per_background; } cui_render_v2_options; /* Private result; raster recomputes/checks plan rather than trusting caller edits. */ typedef struct { int32_t physical_x, physical_y; unsigned width, height; size_t stride, bytes; cui_rect logical_covered; } cui_background_prepared_query; ``` Private query/raster take draw-by-value, render options, conservative active clip and caller buffer/stride/capacity. Query leaves output unchanged on failure; raster validates/recomputes its whole plan before writing. Output byte budget is not a request for this helper to allocate. Place it below adapters, depending on Core values/math, never Core depending on an adapter/component. Query receives a copied background draw, viewport and explicit positive sx/sy in [1/65536,64], origin x/y in[-1e6,1e6]; checks finite geometry/overflow/work/byte limits and returns integer physical covering, logical placement, width/height/stride/bytes. Raster writes a caller-owned prepared buffer only after full validation/capacity checks. No retained cache or five new gradient shaders. Sampling frame always remains original logical bounds, never cropped bounds or a logical-ceil surrogate. Physical covering uses floor(left/top),ceil(right/bottom); sample target pixels at physical centers, inverse-transform to logical points, preserve fractional phase. Intersect with viewport/active clip OUTWARD integer covering for conservative work culling only, without changing gradient origin/extent or baking ancestor clip alpha into the raster. Initial explicit CENTER_V1 policy uses logical center-in-shape coverage and existing independently clamped corner circles (ellipses under unequal scale); transparent outside. It is a consistent discrete mask, not an analytic-AA or source-GPU edge parity claim. No radius remask later. Future AA needs an explicit policy/version and new tests, not silently changed pixels. Existing adapter ancestor clipping applies ONCE at submission: software center tests, native scissor conventions and Canvas clip edges retain their existing rules. Do not pre-mask those clips and apply them again. This does not promise identical ancestor-edge AA across adapters. Clip push/pop remain in the original stream. Use common sample_srgba8 semantics for color: preserve Oklab excursions until straight-linear clipping/encoding, alpha after resolved opacity/coverage, one final byte rounding. Implementation needs a shared output-conversion helper so opacity is applied BEFORE alpha quantization, not byte alpha multiplied a second time. Prepared output is straight encoded RGBA8; target source-over follows established IMAGE blending on encoded UNORM targets. No claim of linear-light destination compositing or complete source framebuffer color-space parity. Nonmatching target formats/color-management policies must reject negotiation, not approximate them. Draw uploaded pixels at the inverse-transformed INTEGER covering rectangle, using one-to-one physical sampling; drawing again into original fractional box bounds would stretch/shift phase. Existing IMAGE helper's logical-ceil raster/mask path MUST be bypassed via private prepared-image submission, not revision-bit tags, synthetic shadow kinds, changes to old IMAGE or generic second radius/opacity. ## Five consumers, staging and failure lifetime Proposed common `cui_render_v2_options` is a sized portable value containing output policy, actual physical viewport width/height, sx/sy/origin and separate CPU, texture, transfer and metadata byte budgets. Query validates actual target against it; render revalidates after resize. No platform pointer is in Core records. Each native opaque CUI adapter adds bool `*_support_v2(adapter,options,out_support)` and bool `*_render_v2(adapter,list,clear,options)` for prefixes cui_software, cui_sdl3, cui_sdl_gpu and cui_sokol; Canvas has the equivalent wire handshake. Adapter-specific diagnostics must identify validation/preparation/submission failure; existing error accessors are reused where available, new V2 diagnostics reviewed where absent. V1 functions remain available and cannot accept the V2 list type. No per-context adapter binding and no new input dispatch architecture. | Consumer/source seam | Required implementation, beyond shared query/raster | | --- | --- | | Software `backends/software/cui_software.c` | Full V2 validation before clearing pixels; prepared center-masked bytes source-over at exact physical cells; wrap ordinary drawing without routing backgrounds through `cui_bitmap_key_make`. | | SDL_Renderer `backends/sdl3/cui_sdl3.c` | Query current target/DPI; stage RGBA textures and exact physical destination/source rectangle, neutral texture tint/opacity, preserve clip/order; explicit completion of queued SDL work before releasing prepared textures. | | SDL_GPU `backends/sdl_gpu/cui_sdl_gpu.c` | New V2 collector branch feeds existing textured quads, direct prepared physical upload; no logical reraster. Retain texture/transfer resources through fence completion, including failed submissions and safe cancellation. | | Sokol `backends/sokol/cui_sokol.c` | Reserved-slot `sg_init_image`/view preparation, exact physical quads/UVs and ordinary same-context GL deletion after the last issued draw; no extra wait/commit. See borrowed-runtime boundary below. | | Canvas `web/gallery.c`, `web/gallery.js`, `scripts/build_web.py` | Negotiate V2 wire BEFORE compose; typed field exports and common C raster query/write exports; JS preflight all commands, owned ImageData/offscreen upload, strict tag/version checks and exact physical placement. Refresh views after WASM memory growth; no Canvas-gradient approximation. | Every V2 renderer first validates header/stride/features/count overflow, all active payloads, finite geometry and complete bounded clip-stack balance (depth<=256). Then queries all work/allocations and stages needed backgrounds plus existing image/mesh/shadow/glyph resources before clearing or beginning a target pass. Some current legacy paths validate/upload while drawing; those need real V2 preparation refactors, not merely wrapping the old renderer and hoping. Borrowed pointer validity is the caller's C contract; a validator cannot prove arbitrary pointer safety. Rendering returns false with adapter error on failure, never a representative-color or silently omitted background. Existing V1 stays exact. Limits per V2 render: <=4M pixels/background, <=8M pixels/frame, <=16384 each physical side, <=4096 backgrounds,32MiB CPU pixels,32MiB texture payload,32MiB transfer staging, plus<=1MiB prepared-command/handle metadata, all constrained further by explicit adapter limits. If actual metadata exceeds its limit, reject before target mutation. Conservative additional application-visible per-call payload budget is97MiB when these copies coexist; it is NOT a physical GPU/process-memory peak bound. Existing text/image/shadow caches, target/offscreen surfaces, allocator alignment and opaque driver allocation add separately. Query must expose/reject needed capacity; incremental release may lower peak only with a proven lifetime ledger. Do not claim the earlier64MiB CPU+texture shorthand as a complete upload bound. No retention cache initially. One application-owned prepared batch per adapter call is the initial allocation policy. Render success means accepted/issued, NOT GPU completion. Before returning, consume or copy every needed frame-owned CPU payload into accounted staging; GPU execution cannot extend the Core array/text/stop lifetime. Private resource release follows each backend's actual API guarantee, NOT a blanket requirement to wait for GPU completion. GLCORE ordinary deletion after last issued use is proved below; other native adapters still require their own concrete ownership proof. Fresh private resources bypass legacy pointer/revision caches. Canvas's synchronous byte/offscreen path may release C/JS staging after copying; asynchronous createImageBitmap must retain it until copy completion and fit byte limits. Driver-retained allocations after safe API release are NOT bounded by these application-owned per-call budgets. No total VRAM/process-memory guarantee. Validation/allocation/preparation failures leave the previous target untouched and clean partial staging. After target mutation, unexpected provider errors, driver submission failure or device loss report failure; there is NO GPU rollback promise. Reset/recreate a lost consumer and re-query before a later application frame. Actions may already have run during composition: never replay input, rerun accepted callbacks, silently recompose or downgrade to V1 in the failed frame. CPU commands and borrowed resources remain valid only under their documented lifetimes. ## Bridge, serialization and implementation checkpoints `src/bridge/cui_bridge.c:cui_bridge_step` currently composes then ends a V1 list; `cui_bridge_sdl.c` forwards it to `cui_sdl3_render`. Add a distinct versioned bridge mode/symbol negotiation, query initialized actual backend before first V2 begin, and choose ONE matching begin/end/render route throughout a step. Unsupported or headless/no-consumer mode cannot advertise rendering; pure values stay usable. Keep bridge ABI1 entry points/ordinary facade defaults intact. The future typed Python/JS/TS/Go/Rust layer must detect symbols/features, copy brushes, validate numbers, and surface failure; ABI1 alone is not a background feature test. Gallery V1 `gallery_command` exports a property table, not binary command memory. Add explicit V2 host/wire version and typed accessors for kind, brush kind/model/ space/angle, both color/position stops, bounds/radii/opacity and required policy. Pointers/size_t/union bytes are never serialized. Legacy text/bitmap/mesh exports need equivalent lifetime/deep-copy rules and bounded lengths; use checked wire integer widths, not lossy float fields for 64-bit identity/revisions. Host snapshots must own resource bytes explicitly. No old JS unknown-tag fill fallback in V2. Intermediate forwarders/captures either deliberately negotiate V2 or stay V1; they cannot receive an apparently successful incomplete V1 substitute. Independent implementation checkpoints, each reviewed/tested before the next: 1. Freeze V1 ABI/command/software oracles and review these exact records, output policy, budgets and Sokol GLCORE deletion/pool-reservation contract; no renderer claimed yet. 2. Core V2 mode/storage/emitter and setters with source metadata/distribution/skill updates. No-setter V2 normalized legacy commands/pixels equal V1; reject old consumers before composition. Test wrong ends with real queued actions exactly once, bad-capability begin preserving queue, setter invalid/capacity/collision atomicity, anonymous/current named/portal geometry, clear/owners and lifetimes. 3. Shared physical query/raster plus software V2. Independent CSS/SOURCE_038 and sRGB/Oklab goldens; tiny HSLA, out-of-gamut/alpha quantization, fractional moves, unequal scales, clip corners, opacity once, DROP/outline/fill/INSET/mesh/underlay/ prepaint order. Fault-inject all bounds/allocation/preparation paths and next-frame recovery; byte guards, borrowed-resource copy tests and no old-cache collisions. 4. SDL_Renderer, SDL_GPU and Sokol V2 preparation/ownership/output, then Canvas/WASM wire. Keep all five in scope. Compare prepared pixel oracle exactly; compare target pixels under each declared encoded-UNORM policy with explicit readback tolerance, including alpha/background mixtures and independent text commands. Test resize/DPI/phase, target-loss, upload failure, frame completion and Sokol host-owned runtime, deletion before host commit, repeated reuse and context loss. Native automation ONLY private-Xvfb wrapper, browser headless; hardware unavailable in virtual display is explicitly deferred, never marked PASS. 5. Versioned bridge + all five language authoring paths and installed consumers; old library/old header/unknown version refusal, resource serialization, WASM memory growth/strict unknown handling. Component-owned parts/theme gradients, remaining source patterns/focus/text backgrounds and all78 coverage stay explicit remaining work. No generic setter alone completes the component roadmap. Run component-usage guide synchronization tests whenever usage metadata changes, plus exact generated SDK/amalgamation/skill freshness. This checkpoint changes only this design document; no public ABI, renderer or implementation is enabled. ## Simpler correction: ordinary GLCORE deletion, not GPU waiting This replaces the fence/quarantine/loader/new-close proposal in `6160b94e` as well as the earlier generic submit_and_wait hook. Normal asynchronous execution does NOT require CUI to retain API objects until GPU completion. Scope is the existing single-current-context GLCORE adapter only; no claim for other Sokol backends, exported views, cross-context consumers, persistent maps or deferred CPU replay. Primary [OpenGL4.4 core specification](https://registry.khronos.org/OpenGL/specs/gl/glspec44.core.pdf): §2.1 (printed p9) requires ordered command effects and interprets client data on call; later changes cannot alter already supplied data. §5.1.2–.3 (pp48–49) separates name deletion/current-context unbinding from underlying storage retained by references/views. Combining those rules, later deletion cannot invalidate an already-issued draw. Driver storage reclamation may be deferred; deletion is not GPU completion or a synchronous memory-release guarantee. §8.4.1 distinguishes client pointers from pixel-unpack-buffer offsets. Pinned Sokol evidence: commit `401f21f8b7039258c35fef75c11d9a8a0e616771`, local `third_party/sokol/sokol_gfx.h` checked SHA256 `e23802d543747b1d24b4ab76e52634fb8b0a4a30afdb9f1437f63814f6bc77d7`; [exact pinned source](https://github.com/floooh/sokol/blob/401f21f8b7039258c35fef75c11d9a8a0e616771/sokol_gfx.h). | Source seam | Actual behavior relevant to lifetime | | --- | --- | | `_sg_gl_draw`, near13180–13214 | Issues glDrawArrays/glDrawElements variants during sg_draw. There is no deferred CPU Sokol draw-list replay at commit. | | `sg_commit`, near28267; `_sg_gl_commit`, near13230 | Commit updates accounting/listeners/frame index and clears GL binding caches. It is neither a GPU wait nor required to issue the preceding GLCORE draws. | | `_sg_gl_create_image` / `_sg_gl_teximage`, near11810–11901 | Immutable client bytes go into GL texture calls; no retained caller-pixel pointer. Require PIXEL_UNPACK_BUFFER=0 for this path; validate/refuse a nonzero external binding rather than treating a pointer as a PBO offset. | | `_sg_gl_discard_view`, near12382 | Invalidates cached texture/sampler bindings, deletes any GL texture views (and relevant auxiliary objects). Plain texture views may use the parent image without a separate GL view object. | | `_sg_gl_discard_image`, near11904 | Invalidates cached texture/sampler bindings and glDeleteTextures for owned images. Background images are not injected/external. | | `_sg_gl_cache_invalidate_texture_sampler`, near11389 | Unbinds matching texture/sampler slots and clears cached/stored identifiers, preventing numeric GL-name reuse from skipping a needed bind. | | `_sg_uninit_view/image`, near26991–27023; reset helpers near8387/8423 | Calls backend discard, clears payload and resets to ALLOC, retaining reserved slot and incrementing uninit_count. | | `_sg_sref_slot_eql`, near8712; resource-ref alive checks near8790 | Internal references compare ID AND uninit_count, so ordinary reserved-slot reinitialization invalidates old internal references. Public same-slot handles still require explicit private-reference clearing. | | `_sg_dealloc_view/image`, near26834–26867 | Returns ALLOC slot to the pool and resets slot identity. | | `_sg_slot_alloc`, near8490; `_sg_lookup_view/image`, near8566/8606 | Allocation increments generation; lookups compare full ID. Generation wrap is explicitly not permanently prevented by pinned code. Do not rely on immortal stale-handle rejection. | ### Proposed preparation/use/release sequence 1. Before composition, configure/reserve actual image AND view slots (below), query support; use the existing same-context/current-thread/no-active-host-pass contract. 2. Prepare RGBA bytes and initialize reserved owned immutable images, then views. Client source bytes may be freed after sg_init_image returns with the upload consumed, not after an arbitrary future fence. Check logger/GL errors as well as sg resource state BEFORE clear: GL create_image returns VALID after its GL calls, so resource state alone does not prove an allocation succeeded. 3. Emit every prepared draw through the normal immediate sg_apply_*/sg_draw path, preserving command order. End the CUI pass. Once there is no future CPU use of those private view/image handles, uninit views FIRST, then images to ALLOC. This ordered API deletion is safe even when GPU work remains outstanding. 4. Clear prepared draw references/counts before any next collection. Do not put these images in old bitmap caches, export them to the host, retain them in other contexts/containers, or replay a copied CPU plan after releasing them. Future initialization of the same reserved handle is a new private payload; no stale CPU command may survive. Sokol invalidates its GL cache on discard. No raw GL upload/bind bypass or additional cache-reset API is needed for this route. 5. Owned runtime performs its normal sg_commit; borrowed runtime DOES NOT gain an extra commit. Host still commits normally to advance Sokol frame accounting; current rendered/listener guard still prevents another adapter render before that host commit. Resource deletion may occur before commit because draws are already issued. No new loader, GPU-wait hook, fence polling, quarantine or checked-close lifecycle is required for ordinary asynchronous execution. This is an API lifetime proof, not measured GPU completion. A test must delete before host commit and read pixels AFTER commit without using the deleted handles. Sokol has its own binding validation/state; next host draws must apply their own valid resources as usual. No continued CPU draw may use the discarded CUI handles. Immutable images use one GL storage slot (`num_slots` near9005); do not silently switch to transient multi-slot images or persistent-mapped staging. ### Actual reservations and complete Core/adapter accounting Keep explicit adapter-local V2 prepare/configure outside composition. Atomically reserve N image and N view slots via sg_alloc_*; ALLOC is a slot, not an initialized GPU object. Keep slots across frames, initializing/uninitializing only payloads. On configure failure roll back newly reserved ALLOC slots; reconfiguration adds only the positive delta and preserves prior limits on failure. Shrink only outside rendering, deallocating unused ALLOC slots. A borrowed host cannot steal a slot already reserved. Query reports successful reservation, not predicted evictions. CUI currently uses owned Sokol image/view pools512 each. White1+glyph256+bitmap64 can consume321 pairs, leaving191 as arithmetic upper bound, not guaranteed free capacity. A reasonable owned-runtime REQUEST is128 additional pairs, which must actually reserve or fail; do not enlarge V1 pools silently. Borrowed hosts may use Sokol defaults128 images/256 views or custom pools and concurrent allocations; reserve actual requested slots or refuse setup. This corrects blanket4096 support. Support reports actual N plus the complete pixel/CPU/texture/transfer/metadata limits in the record above, constrained by requested/shared/adapter ceilings. Input max_commands counts input records, not expanded glyph/mesh quads; full-list preparation checks actual draw expansion separately. Query refuses active passes, uncommitted previous adapter rendering, invalid/lost targets and unavailable reservations, not merely a GPU that may still be executing safely deleted objects. Core admission is C=min(config.max_commands,16384,support.max_commands, floor(command_bytes/sizeof(command_v2))); B=min(config.max_elements,4096, support.max_backgrounds). With checked alignment/multiplication/sums: M=align_up(config.max_elements*sizeof(uint32_t),alignof(owner_record)), then M+B*sizeof(owner_record)<=background_bytes for one optional block; command storage C*sizeof(command_v2)<=command_bytes. Reject C0 and requested-backgrounds B0 before input. Do not silently shrink B to hide insufficient map/record bytes. A growth begin may free old frame-only storage before replacement (borrowed lists already expire at begin); failed allocation leaves input queued/context usable. Do not temporarily duplicate high-water blocks beyond32MiB Core payload bounds. For N128/default4096 nodes, common64-bit estimates are16KiB node map+11KiB owner records, not4096 records; use actual sizeof/alignment on each ABI. Node maps/commands belong to Core, CPU rasters and live API textures to adapters; copying support transfers no reservation ownership. Another compatible consumer revalidates its own actual capacity. The97MiB CPU+live texture+transfer+metadata figure is a conservative per-call ADDITIONAL application-visible envelope, NOT a limit on process RSS, total VRAM or driver-deferred backing from past frames. OpenGL may retain deleted storage/command copies across queued frames, so a strict physical GPU-memory bound does not follow from N reserved slots or byte ledgers. No bounded reclamation latency is claimed. Existing caches/targets/driver overhead add separately. GLCORE client uploads need no CUI-owned transfer buffer; other adapters' concrete upload copies must still be charged. If a hard driver-memory bound is required, explicit throttling/completion becomes a separately reviewed policy; it is not necessary for this image-lifetime correctness proof. ### Failure, resize and destruction CPU/allocation/preparation failure before clear preserves the previous target. With the original valid context, dispose partially initialized private views then images through normal Sokol APIs, even after upload or already-issued draws; no GPU fence is needed for deletion safety. Clear CPU references and preserve the reserved ALLOC capacity for the next frame. Do not silently omit or flatten a background. A late draw/device error can already have changed the target: report failure, no rollback or event replay. A resize in the same valid context follows the same API cleanup and fresh physical preparation, without waiting for old GPU work merely because its deleted storage may remain driver-owned. Normal destroy under the original valid context may deallocate reserved slots and normal resources with the existing lifecycle; no new pending-GPU close protocol. Actual context loss remains outside that valid-context deletion proof: stop GL calls, do not delete old numeric names in a replacement context. The existing host/runtime teardown requirements still apply; pinned Sokol provides no proven abandon-without-GL API, so do not promise automatic in-process lost-context cleanup. This limitation does not justify fence quarantine during NORMAL async execution. Required tests: reserved-versus-initialized slot accounting/partial failure; uninit view/image after last draw BEFORE borrowed host commit; copied CPU bytes mutated/freed after upload; immediate repeated reinit with different brushes and numeric-name reuse; no stale draw/cache references; correct ordinary host draw bindings after disposal; unchanged V1 pools/routes; resize/error cleanup; byte and alignment admission limits; original-context loss refusal. Native GLCORE proof runs only via private-Xvfb where supported; no hardware PASS inferred from source inspection. Other four adapter ownership proofs remain independently required. ## Approved text accounting clarification (V2 opt-in only) Following `SOFTWARE_V2_FONT_SESSION.md` (224309bd), `cpu_bytes` bounds adapter-owned transaction payload plus counted CUI text temporaries. Metadata is separately bounded. Existing caller-owned font/cache state AND newly allocated opaque FT/HB/Sheen/provider temporaries are outside that byte envelope. Their lifecycle and failures are audited, not silently reported as zero or jointly <=32MiB. This is not a process/RSS or arbitrary-provider allocation/time bound. No global allocator swaps or host dependency replacements follow from this clarification. Text admission additionally limits full paragraph input64KiB, aggregate repeated input256KiB, selected/fallback faces64, shaping attempts8192, segments4096, glyphs65536 and copied coverage8M pixels per frame; a bitmap has <=4096/side and 4M pixels. Enforce countable input limits before work; output-dependent limits can fail after opaque allocation but before publication. Full shaping/fallback, selection and approved glyph transforms remain required; these opt-in limits do not alter V1. No adapter capability is advertised until preparation/painting and independent tests are complete. --- ## Frozen Badge family completion audit Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/BADGE_FAMILY_COMPLETION_AUDIT.md # Frozen Badge family completion audit Source-only checkpoint against CUI `b4cd6a8f`; no build, runtime, browser, generation or status change was performed for this audit. Existing tests below are inspected evidence, not a fresh execution receipt. The family remains partial. ## Authority The baseline is upstream kit v0.7.1, commit `87d10ae5e1299d1be18670a37570c5402f952e34`, as recorded in `docs/upstream-baseline.md`. Primary files were fetched individually from `https://raw.githubusercontent.com/longbridge/gpui-kit/87d10ae5e1299d1be18670a37570c5402f952e34/`; no repository clone or dependency installation was used. | Path below pinned repository | SHA256 | | --- | --- | | `crates/component/src/badge.rs` | `f4debc66e913a6fb4450beeebc3acd19d2b882b891a6e9fbe65ca4421497a691` | | `website/component/badge.md` | `87c7eca64a16f293ab94bcc8377b25a281960ae58f1709f92ef7e8b05e750c14` | | `crates/component/src/icon.rs` | `f8f9355f51bed7e16634c9052454c2649ba1b800dd7932b1094997a967eebf02` | | `crates/component/src/lib.rs` | `81b2e61f0dcd6b5a083cfb1b4c603a26aff0a30d2ddcb583b9c130f975acfabd` | | `crates/component/src/sizing.rs` | `379fa0e1ffd05c5a1711647f183ba3e5f1fb297887ea0929f229d22d32142251` | | `crates/component/src/component_traits.rs` | `f95ca555f338c8a61a74dca5a9ad1da82499b6e7a2c198c83bb1be777339bdc4` | The website digest exactly matches the Badge row in `docs/component manifest`. Its three feature labels are an index, not the family definition. That row has partial platform evidence and no last-verified commit. Its sample points to `gallery/main.c`, which demonstrates the legacy pill; the richer demo is in `web/gallery.c`. Neither reference establishes complete family coverage. ## Source behavior and coverage matrix C authority: `include/cui/cui_components.h`, `src/components/cui_components.c`, `docs/BADGE.md`. Existing direct tests: `test_badge_variants` and design-size coverage in `tests/unit/test_components.c`. P means implemented with specific inspected assertions; U means no sufficient independent proof located here. | Frozen behavior or state | Current C route and inspected evidence | Remaining gate | | --- | --- | --- | | Default Number, count 0, maximum 99, Medium | `cui_badge_options_default`; count-zero keeps child wrapper and removes marker, P | Default full geometry and empty-child oracle | | Positive count, maximum equality, decimal overflow `maximum+` | `size_t` formatting; count100→99+ P | 1/9/10/99/100, equality, custom maximum, maximum0, SIZE_MAX without truncation | | Dot always visible independently of count | DOT P, 6px square | Count/max changes must not affect dot; zero/alpha/clipping witnesses | | Icon always visible independently of count | ICON/check image P | Custom SVG and source icon refinement below | | Builder variant ordering | Source count() does not reset dot/icon, despite its comment; C uses explicit enum | Document declarative equivalent; test transitions without stale marker | | Arbitrary child content; marker appended after children | Callback once, fixed80×40 child and text, P | Empty, multiple children, avatars, nested badges, responsive child, independent child input/state | | Zero-flow absolute corner placement | First-frame outer and child80×40 retained for all 4 sizes ×3 variants, P | Real-font narrow/wide resize, nested clip, overlap and software pixels | | Count top/right offsets | Large +2/−N, Medium −3/−3N, Small/XSmall −4/−4N; P | Multi-digit/custom maximum widths and transform/clip cases | | Count pill geometry | Text10, line10, padding2, minimum14; measured width, P | Actual font pixels/baseline and non-default rem policy | | Source sizes | Medium default; Large24, Medium/custom Size(_)16, Small/XSmall10 for icon shell; dot6/count10 unchanged | C explicit design-size is an extension, not proof of source arbitrary Size(_) mapping; publish distinction | | Icon bottom-right shell | 10/16/24, rounded, border1 theme background; image command P | Border pixels, transparent/custom background, clipped shell and artwork | | Supplied icon remains an Icon object | Source retains path/data, own size/style/color/rotation; icon.rs uses inherited size/color only as fallback | C reconstructs named icon at extent−2 and white. Add compatible icon-content/refinement route or explicitly keep this gap; current configurable name is insufficient | | Default color and custom color | Source theme.red; C theme.danger/custom RGBA, opaque custom RECT P | Prove semantic token mapping in light/dark themes; alpha0/partial alpha and exact colors | | Rounded marker, white foreground, stacking | C radius1024, white text/icon, absolute overlay | Pixel/culling/shadow ownership witnesses, not command presence alone | | Outer style refinement | Source stores/refines StyleRefinement but badge.rs has no Styled implementation; Icon does | Do not claim arbitrary Badge style builders merely from imports/private field. Distinguish reachable parent composition from any proven direct authoring; verify actual examples compile before adding API scope | | Different positions/complex nesting examples | Parent layout and caller composition, not a Badge position setter in pinned implementation | Copyable recipes and real geometry tests; no invented source position API | | Passive semantics | Source Badge has no own focus, activation or event handler. C adds STATUS/name, parent wrapper, no focus/tab; P | Dynamic names, empty/custom names, absent marker references, screen-reader/AccessKit evidence still separate | | Child interactivity | Gallery button child increments count; browser test checks 7→8 | Pointer/touch/key child activation exactly once with overlay marker; marker must not capture or steal focus | | Lifetime and state | Source consumes builder/children each render; C caller owns count and child state, synchronous callback; no Badge retained state | Copied frame text/name and SVG lifetime/resource recovery tests, omission/reappearance and ID reuse | | Invalid input/failure | Invalid variant prevents callback/submission P; invalid design-size P | All invalid records, malformed strings, derived-ID/collision boundary, resource exhaustion; no partial callback or leaked frame resources | The frozen Badge itself does not require drag, selection, keyboard navigation, focus rings, disabled paint, close handling, animation, or value callbacks. These are justified noninteractive exceptions for the marker only. Arbitrary interactive children retain their own full input/lifetime contracts. Count updates must still be visible and accessible; the exception does not excuse stale content or blocking child input. Native GPU and browser visual equivalence are not inferred from C command assertions. ## Five binding coverage All facades reach `src/bridge/cui_bridge.c`'s CUI_BRIDGE_BADGE branch, which calls legacy `cui_badge(text)`, not `cui_badge_ex`. This is the standalone text pill, with primary/on-primary styling; it is not the frozen count-overlay family. | Facade | Actual authoring path | Coverage and missing surface | | --- | --- | --- | | Python | `bindings/python/cui_bridge/__init__.py`: badge(key,text)→Widget("badge") | Legacy label; component smoke test. No typed count/max/variant/icon/size/color or composed Badge child API | | JavaScript | `bindings/node/index.cjs`: badge(key,text)→Node(11,text) | Same legacy bridge route; generic node styling does not add overlay semantics | | TypeScript | `bindings/typescript/index.d.ts`: badge→Label with shadow traits; Node declarations re-export it | Typed legacy surface only; no frozen Badge options or owned icon content | | Go | `bindings/go/cui/native.go`: Badge(text)→Node kind11 | Legacy smoke in native_test; no extended Badge record or nested marker ownership | | Rust | `bindings/rust/src/lib.rs`: Kind::Badge11, App root/child/build APIs | Generic typed node construction reaches legacy render path; no Badge-specific options | Existing root/part shadow facilities must be checked against their actual allowlists. A shadow trait is not evidence that the extended marker or arbitrary nested child is exposed. Bridge node lifetime/rollback and copied-string ownership must be preserved when adding the family; no arbitrary child support should be advertised unless the actual Badge painter submits those children. ## Gallery and browser evidence boundary `web/gallery.c` case8 demonstrates count7, overflow125, dot, check icon, and zero marker with clickable children; control sizes also exercise CUI design metrics. `tests/web/test_browser.py` checks semantic names, 7→8 and four design-size marker extents. These are useful partial tests, not pixel/refinement/clip/asset/lifetime or all-five-runtime proof. Avatar/nested/color/position examples from the source document are not equivalent to the current five-button demo. ## Next cohesive implementation and verification slice 1. Preserve legacy `cui_badge` and all existing foreign calls. Settle an additive extended C icon-content/options route supporting a supplied configured icon without resizing published records. Retain named-SVG convenience. Record source-red versus danger mapping, arbitrary source Size(_) versus CUI design scale, and only genuinely reachable outer refinements. No generic style graph. 2. Add owned bounded bridge Badge options and explicit child-composition painting, with default absence preserving legacy pill. Expose the same typed family in Python/JS/TS/Go/Rust, copied values, atomic invalid replacement, clear/reset and node reuse/destruction. Specify marker IDs separately from wrapper IDs; no silent compound-part or portal ownership claim. 3. Add table-driven source numerical oracles for the matrix, real-font first-frame and resize tests, software pixels for color/alpha/border/clip/stacking, and passive-marker child input tests. Exercise maximum edges, variant transitions, omissions, nested content, asset lifetime and resource failures. Keep an independent legacy pill/foreign default control to detect compatibility drift. 4. Run all five actual runtime suites and TypeScript checks; migrate/add narrow gallery examples for nested/avatar/custom icon/color cases and headless browser coverage. Record exact platform/renderer exceptions instead of replacing them with a generic parity claim. 5. Update authoritative headers, BADGE guide, component usage/metadata, examples, SDK/amalgamation and consumer skill through canonical generators. Only after fresh configured native/browser/binding evidence covers the agreed matrix may the integrator consider family verification. This checkpoint changes no status. The first review should settle the small icon/options and bridge ownership contract; there is no justification for an input dispatcher or new global state. The C geometry foundation is substantial, but foreign authoring and configured-icon fidelity prevent a complete-family claim today. ## Proposed additive authoring contract (source-only, not declarations) This checkpoint proposes APIs; none is implemented or measured. Preserve both `cui_badge` and `cui_badge_ex`, including their existing named-icon painter. Do not enlarge `cui_badge_options`. Existing Icon already supports owned SVG state, path/name loaders, affine rotation, explicit/inherited size/color, opacity, box decoration and numeric constraints (`include/cui/cui_icon.h`). Reuse that implementation instead of adding Badge-specific rasterization. ```c /* Proposed in cui_components.h; names subject to review. */ typedef struct { cui_icon_state *state; cui_icon_options options; } cui_badge_icon_content; typedef struct { bool submitted; cui_icon_error icon_error; } cui_badge_result; cui_badge_result cui_badge_with_icon( cui_context *, cui_id, const cui_theme *, cui_badge_options, const cui_badge_icon_content *, cui_button_content_fn, void *); ``` The configured route requires ICON variant and nonnull initialized state and content descriptor. Reject incompatible variants before invoking child content. Shell geometry still follows Badge size; artwork is a separate ordinary Icon child, with its own configured dimensions and transform. No extent-minus-two rewrite. Supply source fallback inherited text size 14/10/8 for Large/Medium/ Small-or-XSmall, inherited white, while explicit icon size/color remain unchanged. `Size::Size(_)` on source Badge maps to Medium shell/fallback; explicit CUI design scaling remains separately documented. An inherited-size descriptor can use these Badge defaults; authored Icon overrides take precedence. Copy options locally before applying fallbacks; never mutate caller records. Force artwork decorative so Badge STATUS/name remains the sole marker semantic; child content keeps its own semantics. Rotation affects artwork paint, not shell dimensions, anchoring or input. The descriptor/options/style/constraints and callback userdata are borrowed synchronously. State masks must outlive rendering of every returned draw list; collect/destroy follows the existing Icon contract. SVG replacement preserves older masks. Validate descriptor fields before submission; missing/parse/limit errors from icon preparation are reported in `icon_error`, with the valid shell and ordinary child content retained (not falsely reported as atomic UI rollback). `submitted` distinguishes invalid call from admitted Badge with failed artwork. The implementation must preflight preparation before invoking content so error ordering is deterministic. Exact native/WASM sizes and offsets require a later compiler lease; no constants are published by this checkpoint. ### Bounded owned bridge proposal Add a separate optional Badge configuration to the existing legacy Badge node. Absent configuration keeps its current legacy text painter and child policy. Configured Badge explicitly owns an ordered list of ordinary child nodes; submit each exactly once inside the Badge content callback. This admits nested badges, avatar nodes and custom child rows/buttons without a synthetic text-only wrapper. Apply the existing graph's parent, mount rollback, destruction and cycle checks; no second ownership graph or portal reparenting. A marker is an internal part, never an independently destroyable child handle. Proposed pointer-free bridge record and explicit copied source setter: ```c /* Proposed bridge ABI V1; source tag NONE/NAME/SVG. */ typedef struct { uint32_t version, variant, size, flags; uint64_t count, maximum; uint32_t rgba, reserved; float icon_width, icon_height; float icon_rgba_r, icon_rgba_g, icon_rgba_b, icon_rgba_a; float transform[6]; uint32_t icon_flags, reserved_icon; } cui_bridge_badge_options_v1; /* Proposed signatures use existing app/node/error types. */ cui_bridge_status cui_bridge_badge_set_options( cui_bridge_app *, cui_bridge_node, const cui_bridge_badge_options_v1 *); cui_bridge_status cui_bridge_badge_set_icon_source( cui_bridge_app *, cui_bridge_node, uint32_t source_kind, const char *bytes, size_t length); cui_bridge_status cui_bridge_badge_reset(cui_bridge_app *, cui_bridge_node); ``` This proposed record is 96 bytes by field arithmetic, NOT an ABI measurement. Flags express custom background, artwork dimensions/color/transform; unused fields/reserved bytes must be zero. Colors are straight RGBA; background uses 0xRRGGBBAA. Float32 values must be finite and accepted by Icon's existing domain; facades reject overflowing conversions. Counts uint64 must fit native size_t before commit, including WASM32. A separate name setter should reuse the existing copied node text/name mechanism, not overload SVG bytes or infer accessibility from paths. Version/flags/numeric/source validation and allocations finish before replacing old values; failures preserve old configuration and child ownership. Proposal: lazily allocate one per-configured-node payload, capped at 256 bytes excluding the existing Icon state/cache and copied strings; measure actual payload before approval. Cap source bytes at 64KiB, name/path at 1KiB and accessible name at 1KiB; additionally apply existing Icon pixel/cache/version limits, not an unlimited per-node raster cache. Allocation counts/bytes and retained old draw-list versions must be disclosed separately. Zero configured Badge nodes incur no payload allocation. Clearing source means empty artwork while keeping the ICON shell; resetting configuration restores the legacy pill. Removing a child does not reset options. Node destruction frees sources/state only after outstanding rendering borrows end under the existing bridge frame lifetime. Replacement/destruction and slot reuse need actual tests. ### Five-language surface and required review decisions All five facades should expose a typed `BadgeOptions` and `BadgeIcon` value, count/dot/icon constructors, optional content children, and explicit reset. Python dataclasses, JS frozen/plain validated records, TS discriminated unions, Go value structs and Rust enums/builders map to the same owned bridge contract. Unmounted builders retain a request locally; mount validates against their owning app/library. Never normalize through another global library. Mounted setters commit facade state only after C success; absent new symbols preserve old loads and return feature-unavailable on new authoring. No facade duplicates Icon math. Source byte ownership is copied; arbitrary native loaders/callback pointers are not exposed as cross-language records. Before production settle: whether complete Icon decoration/constraints belong in this first bridge record or an additive owned Icon descriptor shared with standalone Icon (preferred for full family fidelity); exact Icon inherited versus authored-size flags; source-red token mapping; and reachable outer Badge style. The small record above covers required rotation/color/dimensions but must NOT be claimed to represent all Icon refinements until those remaining fields have a reviewed shared route. Source Badge has no Styled implementation; its private style field alone does not justify inventing public Badge refinement methods. ### Meaningful acceptance tests | Gate | Independent witness | | --- | --- | | Configured artwork | Same asymmetric SVG through standalone Icon and Badge: rotation, custom color/alpha, width/height, inherited fallback; compare software pixels and shell bounds | | All variants | Count/max boundaries, zero hiding, dot and icon transitions, every source size; existing legacy painter frozen control | | Composition | Empty/multiple children, avatar, nested Badge, interactive child; callback once, wrapper intrinsic first-frame/resize, marker zero-flow and clipped pixels | | Semantics | One passive marker STATUS, explicit/default name, no icon duplicate/focus; child keyboard/touch activation retained | | Ownership | Source replacement with old draw list alive, failed parse/allocation/oversize replacement, reset/clear, node removal/reuse and bounded cache collection | | Five runtimes | Actual configured count/dot/icon/custom SVG and nested child rendering in Python/JS/Go/Rust, TS typechecks; old-library load and failed mount rollback | | ABI and resources | Native/WASM sizeof/offsetof, exact source caps, uint64→size_t and float32 overflow, invalid flags/reserved fields, zero-idle allocation and payload size | No production or generation is authorized by this proposed-record checkpoint. Full family verification still requires the preceding matrix, not just these new route tests or a legacy text-pill facade. ## Integrator decision: first C slice Approve additive configured-icon C implementation and prepared meaningful tests, preserving `cui_badge_options`, `cui_badge` and `cui_badge_ex`. Reuse full existing Icon options/state, including decoration and constraints; do not duplicate SVG, raster or dimension-resolution logic. Force only decorative semantics and unprovided inherited fallbacks, preserving explicit authored settings. Validate the new call's structural requirements before composing content. The proposal's prepare-before-content ordering is not required if it would duplicate Icon's layout logic: a documented content-before-artwork order consistent with existing Badge composition is acceptable. Valid shell/content may remain when artwork reports failure; no atomic UI rollback is promised. Borrowed options and userdata last through synchronous submission; prepared masks follow Icon's draw- list lifetime. Preserve source/default color mapping explicitly. The illustrative foreign record remains proposed, not approved or implemented: it must use actual bridge status types and cover complete shared Icon styling before full-fidelity authoring is advertised. C source work does not close five- language, ABI, pixel, lifecycle or gallery acceptance. Worker builds and generation remain held while the localized TimeField bridge owns the serial validation slot. ### Unvalidated additive C source checkpoint Prepared `cui_badge_with_icon`, descriptor/result declarations and a standalone `tests/unit/test_badge_configured_icon.c`. Both old public routes use the same unchanged Badge painter branch; only the new configured path invokes ordinary `cui_icon` with copied options/decorative and missing inherited fallbacks. Content-before-artwork validation is explicit. No raster/layout math duplicated. Prepared assertions cover first-frame shell/content/artwork dimensions with constraints/style/rotation/color, sole STATUS, caller descriptor immutability, structural callback isolation and later artwork-invalid error ordering. UNEXECUTED: compile/ABI, prepared test, software pixels versus standalone Icon, SVG replacement/draw-list lifetime, invalid-resource cases and frozen old-route regressions. Test registration, canonical generations, metadata and all five binding work remain pending; no runtime, freshness or full-family claim. ### Prepared configured test registration and independent controls Source-only followup registers `badge_configured_icon` in CMake, linking software and the frozen Badge excerpt from exact b4cd6a8f. The excerpt's original byte SHA is embedded in `tests/reference/badge_b4cd6a8f.c`; only symbols were prefixed. Prepared old-control scenes cover standalone pill, count overflow, hidden zero, dot and named icon with equal geometry/semantic names/command counts. Existing `test_components` remains the more detailed unchanged old-route geometry oracle. The configured test constructs a separate ordinary shell/Icon tree and compares software RGBA under four rotations, partial alpha and numeric width constraints; it clears the source after both lists are finalized, before rendering their old masks. It requires nonempty painted coverage. No huge engine source is copied. Public descriptor offsets/containment are compile-time assertions; exact native and WASM sizeof/offsetof measurement remains a separate unexecuted gate. These tests are PREPARED, not executed. First-frame/resize/nesting, exhaustive invalid callbacks, actual native/WASM ABI receipts and failure allocation cases still need completion under the later compiler lease. No generated resources or status was updated in this source-only followup. ### First focused execution receipt Strict C11 O2/Wall/Wextra/Wpedantic/Werror compilation of candidate components, fixture and frozen excerpt passed against hashed current root cached archives. The private-Xvfb wrapper passed `badge_configured_icon` 1/1 (.02s), including configured error ordering, frozen scenes and software/retained-mask comparison. See `docs/validation/badge-configured-c-focused.json` for exact source/log hashes and limitations. Reproduce compilation with `tests/run_badge_configured_probe.py` then run the emitted test directory only through `scripts/test_local.py`. Native descriptor/options offset is136/8; WASM32 is104/4. Result size/error offset is8/4 on both. WASM was a header assembly probe, not a runtime claim. Generation, configured full CMake consumption and the remaining family matrix are pending. ### Prepared remaining C family cases (not executed) The fixture now additionally submits nested dot/count Badges around an actual button, asserts current first-frame width and corner geometry at120→48→160→48, marker omission/reappearance without losing nested semantics, once-only content callbacks and exactly one queued child click. Whole subtree omission/reappearance must not replay activation. Separate Icon max-pixel failure keeps content/shell, then reduced artwork size recovers; malformed SVG reports PARSE under the same composition contract. These new assertions have not run. They cover deterministic resource limits, not injected allocator failure; no all-family claim follows. --- ## Foreign-builder element shadow authoring proposal Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/BRIDGE_ELEMENT_SHADOW_AUTHORING.md # Foreign-builder element shadow authoring proposal Audit base: `37eecd1f` (2026-10-31). Proposal only: no bridge declaration, implementation, facade, generated resource or coverage status changes. The current Core named-box APIs remain C-only. This document requires API review before production work, especially before extending the mapping to component parts or detached surfaces. See `../ELEMENT_SHADOWS.md` and `ELEMENT_SHADOW_STYLING.md` for the implemented Core seam and renderer limits. ## Smallest compatible first slice Offer an owned, typed list of at most eight mixed DROP/INSET layers and explicit corner radii on six bridge node kinds: ROW, COLUMN, LABEL, BUTTON, INPUT and BADGE. These are two authoring containers plus four catalog families; they are not six of 78 equivalent component contracts, nor all-family/part support. Reject other node kinds immediately at the authoring setter. Expose identical scope through Python, JavaScript/TypeScript, Go and Rust. Presets expand through canonical C preset logic. An explicit CSS constructor converts blur radius to sigma; ordinary layer constructors continue to accept sigma. This first slice needs no new part registry, public Core paint-node query, wrapper box or generic fallback from a semantic node to an arbitrary rectangle. Add explicit post-submission hooks to the existing dispatch branches. Expanding beyond this allowlist requires an owner-specific mapping and tests, reviewed separately. A future component-part addressing API must not be smuggled into a universal `node.id` fallback. ## Audited submission and identity The opaque bridge handle is slot+generation. `bridge_node` validates both and live membership (`src/bridge/cui_bridge.c:341`); node creation assigns a private Core ID independently of the key/handle (`:1201`). Removal recursively frees resources and marks nodes nonlive (`:1345`); reused slots receive a new generation. Keep all existing app provenance and one-thread/serialized-app rules. | Proposed kind | Current submission / target | Attachment point and scope | | --- | --- | --- | | ROW, COLUMN | `bridge_render_node` opens/closes `node->id` (`src/bridge/cui_bridge.c:4700`) | After its matching end, after all children. Includes a row/column app root, excluding the bridge's separate background wrapper ID1. No implicit background or new hit/semantic node. | | LABEL | Explicit named box containing text (`src/bridge/cui_bridge.c:4436`) | After that box closes. Shadows follow its rectangular layout bounds, not glyph outlines; transparent boxes still have rectangular caster semantics. | | BUTTON | Fallback branch calls `cui_button_ex(node->id)` (`src/bridge/cui_bridge.c:4664`); `cui_button_paint_state` opens root ID (`src/components/cui_components.c:609`) | After the complete Button helper returns. Guard specifically BUTTON, rather than assuming every fallback kind is a Button forever. Style only its root, excluding text, caret, icons and tooltip. | | INPUT | Branch calls `cui_input_ex(node->id)` (`src/bridge/cui_bridge.c:4577`); `cui_input_common` paints through `cui_input_paint`, which opens ID (`src/components/cui_components.c:2579`) | After the complete Input helper returns. Root includes its input frame; selection/caret/text are separate content. Preserve its existing clip/input behavior. | | BADGE | `cui_badge(node->id)` (`src/bridge/cui_bridge.c:4575`) opens/closes that ID (`src/components/cui_components.c:1914`) | After the Badge helper returns. Root only. | Source line references identify the audited base; inspect the named functions when rebasing. Styling success must come from Core current-frame resolution, never previous-frame `cui_bounds` or semantic presence. Button's bool result is activation, not paint admission. Input has an error result (which does not itself prove root absence). Preserve existing error propagation and honor component/Core failure paths; a missing expected root must report a frame error, not silently claim successful rendering or patch the previous frame. ### Why a universal epilogue is insufficient `bridge_render_node` returns immediately after dispatching non-row/column nodes. A hook only after its row/column end misses those nodes. A hook at the bottom of `bridge_render_node_other` misses the TextView allocation early return (`:4325`) and cannot establish that each helper actually admitted its paint root. That return also bypasses the existing disabled restoration; this audit does not fix that unrelated behavior. Helper-local failures also return without materializing a root, for example group scratch allocation (`bridge_render_group:3147`). ITEM is intentionally not painted by its own dispatch branch; its owner renders it. NOTIFICATION is a no-op there and the shared notification stack is submitted later in `cui_bridge_step` (`:4768`). Styling either at ordinary dispatch end would invent a target. A child authored under a composite is not proof that its own bridge dispatch runs, or that an owner does not measure/omit/repeat that child. First-slice tests must include nesting and protected/layout-only submissions; retain Core mutation guards and never make them an excuse to ignore failures. Use the existing `cui_frame_paint_enabled(ui)` predicate before applying an owned override. It is false in host measurement/layout-only work but true in painted inert ancestry. `cui_frame_sequence` is an input-observation predicate and returns zero in inert ancestry, so it is the wrong paint guard. Skipping a nonpainting pass retains authored values for the subsequent real paint pass; an unexpected Core setter failure during an ordinary painted pass is a frame error. ### Explicitly deferred mappings | Family/path | Why the first slice rejects it | | --- | --- | | Dialog, AlertDialog, Sheet, Popover | Bridge initializes `surface_state.overlay.id` from `node->id | (1<<62)` (`:1331`). `cui_surface` paints its panel at the overlay ID, with separate backdrop, arrow and resize IDs. Root node ID is not a panel contract. | | Tooltip, HoverCard | The content portal uses `node->id`, but exists only after trigger/placement/admission and balanced begin/end. This is a promising second slice with explicit presence results and popup-only semantics, not automatic trigger styling. | | Select, Combobox, Menu, DropdownButton, DatePicker, Command | Triggers and conditionally live popups have separate owners and derived identities; audit each. | | Checkbox, Radio, Switch, Slider, Stepper and other compound controls | A semantic/layout root does not imply the visible indicator, thumb, track, connector or repeated item is styled. Anonymous and repeated parts need owner-approved APIs. | | Notification, ITEM, Settings/Questionnaire-owned fields, virtualized/repeated children | Deferred or owner-controlled rendering may bypass direct node dispatch. No inferred ownership or wildcard style application. | | Root View, Focus Trap, Dock and remaining unlisted kinds | Structural behavior or helper submission differs; absent from first-slice support even if a named rectangle could be found today. | Keep the bridge background wrapper, application root, popup panel, trigger and backdrop independently scoped. No traversal that paints all descendants and no new wrapper that changes layout, clipping, capacity, hit tests or semantics. ## Proposed additive ABI and owned state Names below are review candidates, not declarations available today. Preserve ABI_VERSION1, existing public layouts and all old entry points. Add a fixed, pointer-free `cui_bridge_box_shadows_v1` input record and a size probe, following the existing versioned notification precedent. The setter takes explicit `struct_size`, checks exact size/schema, and copies before returning. Define field order/types in the header; do not alias `cui_box_shadow`, C enums or Clay. A V1 record contains `uint32_t` size/schema/count/reserved, four named float radii (`top_left`, `top_right`, `bottom_left`, `bottom_right`, matching Core), and eight fixed layer slots. Each slot contains four floats (offset_x/y, sigma, spread), `uint32_t kind` and `uint32_t rgba` explicitly packed `0xRRGGBBAA`. No pointer, `size_t`, bool, implicit CSS corner order or host-endian byte-array reinterpretation crosses the ABI. Count controls the active prefix; reserved fields must be zero. Publish/test the size and offsets in all FFIs. Exact-size V1 can coexist with a future V2 without resizing old options or requiring old callers to know V2. Candidate operations: - `cui_bridge_set_box_shadows_v1`: replace the owned normalized list atomically. - `cui_bridge_set_shadow_preset_v1`: explicit preset+radii, expanded by canonical preset code to the same normalized list. NONE is an explicit empty override. - `cui_bridge_reset_box_shadows`: remove the override and restore normal component defaults on subsequent submissions. - `cui_bridge_box_shadow_from_css_v1`: checked factory for one typed layer; output unchanged on rejection. Reuse Core conversion, not five divergent copies of the conversion/preset tables. The exact function signatures, optional capability query and error precedence need approval. Existing unsupported-kind setters return INVALID_ARGUMENT; use that precedent, STALE_HANDLE for stale handles and INVALID_STATE while stepping. Validate the entire record, allowed kind, finite/domain values, count<=8 and radii for nonempty lists before modifying owned state. Keep the existing empty-list radii validation policy, including NONE, rather than introducing a clear-only mismatch. Reuse Core-supported domains (sigma[0,256], offsets/spread[-4096,4096], CSS radius[0,512]); do not silently clamp NaN, truncate nine layers, coerce invalid colors or reinterpret sigma as blur radius. Check float conversion overflow in the facade before conversion where necessary, and validate again in C. A rejected replacement preserves the previous list. Store `has_shadow_override`, normalized count, radii and eight copied Core layers in the private node record. This bounds memory per node and avoids a new heap resource lifetime; document/check the actual per-node memory increase. No layer array is retained by reference. Initialize to no override. Remove/reset stale slot state, and rely on creation's whole-record initialization on slot reuse. Unattached builder objects also copy their typed values; mounted objects update C first and commit their local copy only on success. Removal/app destruction invalidates subsequent mutations under existing handle rules. There are three distinct states: absent override (normal component defaults), explicit empty override (suppress both DROP and INSET), and explicit nonempty replacement. Clearing and resetting cannot be synonyms because components can have default shadows now or later. `[]` and preset NONE must remain empty on every frame until replaced/reset. They must not merely skip the Core setter and allow default shadows to reappear. Core styles last only for the submitted frame. The bridge retains authored style and reapplies it after the owner's complete submission every frame. Component styles/defaults run first; the explicit override is last. Begin/end components must finish their owner work before styling, if later approved. For example, `cui_surface` installs its own shadows while the panel is open (`src/components/cui_surface.c:188`); a pre-submission or trigger-level setter would not provide panel override semantics. Explicit radii are part of the style value; first-slice authoring must not promise automatic matching of theme/state-dependent component radii. A preset supplies layers, not target geometry. Any future automatic-radius feature needs a separate owner contract and theme/state transition tests. ## Facade work and compatibility | Facade | Concrete integration points and owned authoring shape | | --- | --- | | Python | ctypes `_API`, immutable typed layer/radii values, `Widget` retained fields and `App.mount` application in `bindings/python/cui_bridge/__init__.py`. Copy user sequences immediately and apply both pre-mount and mounted updates. | | JS and TypeScript | Add N-API marshalling/exports in `bindings/node/addon.c`, owned validated immutable records in `Node` and mount replay in `index.cjs`, typed declarations in `index.d.cts`. JS and TS share runtime; TS declarations alone are not runtime coverage. | | Go | Add dynamic/static bridge function plumbing in `bindings/go/cui/native.go`, typed value structs/enums and a copied owned slice/fixed array on `Node`, plus mount replay. Preserve fluent error behavior, app checks and pointer lifetime through the copying call. | | Rust | Add V1 `repr(C)` wire structs, separate safe value types and validated `App` mutation methods in `bindings/rust/src/lib.rs`; retain existing Node app identity and Result errors. Copy borrowed slice data through a local fixed record; no borrowed slice retained by C. | Typed examples should use a DROP layer, an INSET layer, a preset, empty-list clear and reset on an allowed node kind in each language. Keep sigma and CSS factory names distinct. Do not expose raw private paint IDs, numeric node-kind constants or Core pointers as user authoring parameters. Missing newer symbols in an older shared library must produce an explicit upgrade/matching-artifact error, never silently drop styles. If adding optional symbol lookup, review that as a separate loader decision; ABI1 equality by itself does not prove symbol availability. ## Focused acceptance plan after review Reuse the existing portable private bridge-render fixture pattern in `tests/unit/test_bridge_avatar_style.c`; it captures the real bridge draw list without exporting a public renderer/test API or opening a window. Add a targeted bridge shadow fixture linked only against needed portable libraries. Test: 1. Each of the six allowed kinds actually emits the requested root layers and unchanged bounds, hit activation, focus and semantics. Compare no-opt-in legacy commands/pixels and explicit reset to normal default behavior. 2. All eight mixed layers, copy-after-call, same-frame replace, next-frame retained replay, empty/NONE clear, reset, invalid ninth/NaN/enum/radii/size/schema/color atomic rejection. Canonical preset expansion and CSS constructor boundaries must match C exactly; no duplicate facade-specific preset tables. 3. Nested row/column and two independently styled nodes, subtree omission/removal, stale handle/slot reuse, failed mount rollback and app destruction. A child must not inherit its parent's layer list or overwrite its decoration. 4. Unsupported popup/ITEM/Notification/composite setters reject before render; closed/missing trigger states do not start styling some other target. Protect measurement/layout-only and mutation-during-step boundaries; reject missing expected roots after component capacity/error paths and recover cleanly. 5. One focused contract suite per facade: pre-mount ownership/replay where that facade supports unattached builders, immediate-construction ownership for Rust, mounted update, replace/clear/reset, invalid-input atomicity and propagated native errors. Check JS runtime and TS compile-time surface, Go both loader paths and Rust FFI layout, while avoiding package suites that rebuild unrelated targets. Existing Core/renderer shadow tests remain authoritative for raster algorithms. Only add necessary bridge-level pixels/order checks rather than duplicating that suite. Browser proof, if a builder host is actually used, must execute the matching artifact headlessly; the C gallery cannot prove Python/Node/Go/Rust authoring. Native tests use `scripts/test_local.py` with private Xvfb. Unavailable GPU/live AT checks remain deferred. Coordinate one nice19, -j1 build slot and reuse the existing focused build directory; this audit ran no builds or tests. On implementation, update bridge docs, `binding-coverage.json`, examples and source metadata for exactly the tested allowlist; regenerate SDK/amalgamation/skill resources and run required focused freshness/offline checks. Keep all78 catalog entries and the beta roadmap shadow item pending until its stated broader work is complete. This proposal changes no actual coverage, so the existing unchecked roadmap and C-only consumer limitation remain correct. ## Approved V1 checkpoint before production The six-kind scope and owned override are approved. Freeze these additive names and signatures (all return `cui_bridge_status` except the two uint32 queries): ```c uint32_t cui_bridge_box_shadows_v1_size(void); uint32_t cui_bridge_box_shadows_supported_v1(uint32_t kind); cui_bridge_status cui_bridge_set_box_shadows_v1(cui_bridge_app *, cui_bridge_node, uint32_t struct_size, const cui_bridge_box_shadows_v1 *); cui_bridge_status cui_bridge_reset_box_shadows(cui_bridge_app *, cui_bridge_node); cui_bridge_status cui_bridge_box_shadow_from_css_v1(float x, float y, float blur_radius, float spread, uint32_t rgba, uint32_t kind, uint32_t layer_size, cui_bridge_box_shadow_v1 *out); cui_bridge_status cui_bridge_shadow_preset_v1(uint32_t preset, float top_left, float top_right, float bottom_left, float bottom_right, uint32_t struct_size, cui_bridge_box_shadows_v1 *out); ``` `cui_bridge_box_shadow_v1` is 24 bytes: float offset_x/y/sigma/spread at offsets 0/4/8/12, uint32 kind/rgba at16/20. `cui_bridge_box_shadows_v1` is224 bytes: uint32 struct_size/schema_version/count/reserved at0/4/8/12, four float radii in Core named order at16/20/24/28, and eight layer records at32 with stride24. Schema is1; reserved is0. Size/offset assertions and each facade's layout tests are required. Packed color is numerically0xRRGGBBAA, independent of byte order. Factories reuse Core preset/CSS functions and commit outputs only on success. `preset_v1` constructs a complete owned style, so every facade can use precisely the same value setter for explicit, preset and empty lists. Private node storage is one inline224-byte V1 value; schema0 means no override, schema1/count0 means explicit empty, and schema1/count1..8 means replacement. No new allocation or retained pointer is introduced. All224 bytes are copied on successful set. Runtime application converts at most eight wire layers to a stack-local Core list, which Core itself copies. Existing whole-node creation initialization clears inherited slot state. Verify/document the actual node-size delta on the supported build ABI rather than assuming host struct packing. App setter/reset validation order is existing `bridge_valid_node` first (app lifecycle then live slot/generation), supported node kind next (INVALID_ARGUMENT), then exact record size/schema/reserved and complete active values. Invalid records preserve the old override. No new callback or mutation phase policy: follow existing setters' step/run-dispatch rules. Capability query returns exactly0 or1 for the six approved kinds. Pure factories have no app or handle; invalid size/output/value returns INVALID_ARGUMENT with output unchanged. NONE produces an explicit empty record with the same empty-list radii policy as Core. Reset returns the node to schema0, restoring normal defaults next frame. Facade numeric validation must reject values that overflow conversion to finite float32; C validates again. Python/Go optional loading must preserve old default library loads, with explicit unsupported-feature errors only when new authoring is requested. Static/dynamic facade layout checks must agree on224/24 and fixed offsets. Reapply only when `cui_frame_paint_enabled` is true, after complete owner submission; an unexpected missing named target in an ordinary painted pass becomes the existing bridge frame CORE_ERROR. Inert ancestry still paints. This signed checkpoint changes no production or coverage status. The pending beta shadow item remains unchecked; implementation and focused all-facade proof must follow under the coordinated build slot. --- ## Semantic bridge part shadows: review checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/BRIDGE_PART_SHADOW_AUTHORING.md # Semantic bridge part shadows: review checkpoint Status: approved design with bounded next-batch implementation evidence below. The original signed proposal was audited at b9c2f3d1 and changed no production or coverage. Review approved the target table, whole-group opt-in boundary and nullable extension choice. This decision record retains the proposal details; authoritative implemented declarations and consumer behavior are in `include/cui/cui_bridge.h` and [BRIDGE_PART_SHADOWS.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_PART_SHADOWS.md). The existing six-root V1 allowlist/default behavior remains unchanged; broader beta completion is pending. Read with [element styling](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/ELEMENT_SHADOW_STYLING.md), the complete 78-family inventory there, [component ownership](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SHADOW_COMPONENT_OWNERSHIP.md), [approved bridge V1](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/BRIDGE_ELEMENT_SHADOW_AUTHORING.md), [named indicator checkpoint](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/NAMED_SELECTION_INDICATORS.md) and the consumer [named indicator contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NAMED_SELECTION_INDICATORS.md). Historical inventory rows describe their audit base; implemented C getters/named entry points and the six-root bridge contract at this checkpoint supersede their older pending text. This is a small next mapping, not a replacement 78-family completion matrix. ## Proposed scope and vocabulary A target belongs to one generation-checked bridge node. ROOT means that node's actual outer named layout/paint box; it never means its visually prominent child. MAIN means a documented per-kind alias for one physical target. INDICATOR, TRACK and THUMB name specific physical surfaces. MAIN does not inherit from ROOT, and an unsupported MAIN never silently falls back to the label row. A shadow on a rounded rectangular caster is not a shadow of a glyph or arbitrary alpha mask. | Node and actual route | ROOT | MAIN | Other supported roles | | --- | --- | --- | --- | | Existing Row, Column, Label, Button, Badge, Input direct submissions | Existing V1 root | ROOT alias | None | | Checkbox direct `cui_checkbox` branch | Whole label/control row | INDICATOR alias | INDICATOR square, named only on indicator override | | Individual Radio direct `cui_radio` branch | Whole label/control row | INDICATOR alias | INDICATOR circle, named only on indicator override | | Switch direct `cui_switch_ex` branch | Whole label/control row | TRACK alias | TRACK and THUMB | | Slider direct `cui_slider` branch | Framed label/control root | TRACK alias | TRACK only | | RadioGroup direct `bridge_render_group` branch | Group layout container | Unsupported: no single group indicator | None | | ITEM whose immediate owner is the above RadioGroup | Item label/control row | INDICATOR alias | INDICATOR circle, through the group owner | | Every other node/owner route | Unsupported by this proposal | Unsupported | Unsupported | MAIN and its explicit alias address exactly the same stored override. Last successful set through either name replaces that one value; reset through either name removes it. They cannot be styled independently. ROOT versus INDICATOR, and Switch ROOT/TRACK/THUMB, are independent slots. A group ROOT affects its own container, not its items; no wildcard or selected-item propagation is introduced. Slider's fill is anonymous and exists only at positive ratio. Its current painter has **no independent thumb box**. THUMB and INDICATOR on Slider must be rejected at authoring time, even if a frontend convention calls it a knob. No new Slider appearance, geometry or input behavior is proposed. ROOT support for the four new control kinds and RadioGroup/item rows is available only through the proposed explicit-target API. Do not expand the existing `cui_bridge_box_shadows_supported_v1` six-kind query or old root setter allowlist. On the original six kinds, new ROOT/MAIN shares the old inline root record, so there are no two competing root stores or conflicting reset semantics. ## Painter evidence and attachment points References below identify functions in the audited source, not promises based on semantic IDs or previous-frame bounds. - `src/bridge/cui_bridge.c`, `bridge_render_node_other`: Checkbox uses the bool convenience `cui_checkbox`, individual Radio uses `cui_radio` with option1, and both update the same existing retained value/change notification. The named convenience variants can replace exactly those calls when an indicator has an authored override. Do not switch Checkbox to the source/events facade or alter reducer/focus policy. Preserve bool changed semantics and reduce once. - `cui_switch_ex` already names the real boxes using `cui_switch_track_id` and `cui_switch_thumb_id`. Track owns clipping; a thumb DROP shadow remains clipped by that track. Apply distinct overrides after the whole helper returns; do not target the separate conditional focus-ring portal. - `cui_slider` opens its caller root, names its track through `cui_slider_track_id`, then conditionally paints an anonymous fill. Apply track and root overrides after the helper. Zero value does not omit the track. - `bridge_render_group` gathers <=64 direct ITEM children into `scratch->radios` and `binding.slots`, resolves the selection by live child slot, then calls **one** `cui_radio_group`. `src/components/cui_radio_group.c` has a distinct painter which emits the group container, item rows, indicators and labels. It does not call individual `cui_radio`. The new branch must call one `cui_radio_group_with_parts`, retain selected-slot/change handling, then apply each item's stored overrides using the same captured slot/ID mapping. Reorder uses item identity, not the array index. Do not introduce one reducer per item. - `bridge_render_node_other` has a deliberate no-op ITEM branch. An epilogue on ITEM cannot implement group item shadows. Group scratch allocation can fail before painting; generic hooks also cannot infer successful root submission. - Settings is a concrete counterexample to kind-only support: its retained Checkbox/Switch field nodes are converted into `cui_setting_item` data in `bridge_render_settings`, then painted by Settings using its ownership scheme. They do not reach the direct control dispatcher. Those field routes remain unsupported, rather than accepting a style that never reaches its target. Capability classification must recognize actual direct-dispatch owners and RadioGroup-owned ITEMs, with a reviewed whitelist for container/panel callbacks that really call `bridge_render_node`. It must reject owner-rendered Settings fields and other unmapped model/composite routes. It must not infer support from node kind alone, the mere existence of `node->id`, a child relationship, semantic presence or `cui_bounds`. Existing six-root operations retain their current behavior; this stricter classification governs the new target operation. Recommended first owner whitelist: the target is the app root, or every ancestor between a directly dispatched target and the app root is Row/Column. For a RadioGroup ITEM, its immediate parent is RadioGroup and every ancestor above that group is Row/Column. RadioGroup ROOT follows the same ordinary-tree rule. This makes the initial supported topology explicit and excludes Settings/panel/model ownership without speculative traversal inference. Additional panel callback contexts require a later reviewed whitelist extension and absence tests; unreviewed contexts report unsupported, not conditionally hidden. A previously authored unmounted request placed outside this topology fails at mount rather than becoming a dormant accepted style. No portal target is added here. ## Additive portable V1 contract candidate Reuse `cui_bridge_box_shadows_v1` exactly: 224 bytes, schema1, reserved0, <=8 24-byte DROP/INSET layers, numeric0xRRGGBBAA, explicit TL/TR/BL/BR radii. Reuse existing pure CSS/preset factories; no duplicate math or preset tables. Old ABI version1, options/state layouts and functions do not change. Proposed descriptor and discovery record contain only fixed-width integers: ```c /* Proposed names; not available declarations. Enum values are wire constants. */ /* ROOT=0, MAIN=1, INDICATOR=2, TRACK=3, THUMB=4. */ typedef struct { uint32_t struct_size, schema_version, role, reserved; } cui_bridge_shadow_target_v1; /* size16; offsets0/4/8/12 */ typedef struct { uint32_t struct_size, schema_version, canonical_role, flags; } cui_bridge_shadow_target_info_v1; /* size16; offsets0/4/8/12 */ uint32_t cui_bridge_shadow_target_v1_size(void); uint32_t cui_bridge_shadow_target_info_v1_size(void); cui_bridge_status cui_bridge_shadow_target_query_v1( cui_bridge_app *, cui_bridge_node, uint32_t target_size, const cui_bridge_shadow_target_v1 *, uint32_t info_size, cui_bridge_shadow_target_info_v1 *out); cui_bridge_status cui_bridge_set_target_box_shadows_v1( cui_bridge_app *, cui_bridge_node, uint32_t target_size, const cui_bridge_shadow_target_v1 *, uint32_t style_size, const cui_bridge_box_shadows_v1 *); cui_bridge_status cui_bridge_reset_target_box_shadows_v1( cui_bridge_app *, cui_bridge_node, uint32_t target_size, const cui_bridge_shadow_target_v1 *); ``` The descriptor selects only a semantic role. No raw paint ID, index, native enum layout, pointer-sized field, platform/Clay object or selector string crosses the wire. Select a RadioGroup item using that ITEM's own bridge handle; the parent is validated from the retained tree, not supplied as an arbitrary second handle. Unknown roles/schema/reserved/size are INVALID_ARGUMENT. All offsets/sizes need C static assertions and facade layout tests before production. For a valid known role and live handle, query returns OK and writes the full info record. Flags are SUPPORTED=1, NEEDS_NAMED_INDICATOR_ROUTE=2 and CONDITIONAL_SUBMISSION=4; all other bits are zero. Unsupported known mappings return flags0 and canonical_role=UINT32_MAX, without promising a future mapping. Query never allocates, invokes component code or resolves current-frame bounds. It reports declared capability, not whether paint exists this frame. The initial ordinary control/group/item mappings have no internal conditional indicator, track or thumb, so do not set CONDITIONAL_SUBMISSION merely because unchecked, disabled or outside a painted traversal. A reviewed future callback/panel route may use this flag with its explicit normal-absence condition. Query and mutation validate app/lifecycle/thread/handle first using existing setter rules; then descriptor shape, owner route and role. Mutation on a known unsupported mapping returns INVALID_ARGUMENT, matching the existing style setter precedent. For set, validate the complete style next; then acquire needed storage and commit once. Query output and old authored styles remain unchanged on any error. No additional callback phase restriction is introduced. Missing newer symbols yield an explicit unsupported-feature/matching-revision error in facades, without breaking default loads of older Python/Go libraries. ## Owned values, replacement and identity Each canonical target has three states: absent override, explicit empty, or a nonempty copied list. Empty and preset NONE actively suppress both shadow kinds on every painted frame. Reset removes the override and restores the component's normal defaults. Replace/reset affects only the specified canonical target; it cannot clear another part's style. Whole-style validation and allocation happen before changing retained state. Multi-call edits are separate transactions; no cross-call batch atomicity is promised. A future multi-target transaction needs its own bounded descriptor and review. The bridge retains copied scalar values only. Unmounted builder sequences are copied immediately; mounted methods commit local state only after C succeeds. Preset/CSS requests in Python normalize through the owning App's chosen library at mount/update, preserving the existing deferred-provider contract. App lifetime, stale generation, failed mount rollback and mutation errors follow current facade rules. Node removal/subtree destruction frees part state; recycled slots start absent. Item reorder preserves styles on item handles; removing/replacing an item must not transfer styles by index or equal text/key alone. Use stable bridge-private part identities associated with the owner's existing stable `node->id`, never expose numeric salts to callers. The implementation must choose and test one deterministic private domain-separated derivation, including nonzero/full-ID distinction checks against group/item descriptors. Do not copy Core's folded-ID hash to pretend to reserve identities globally. Private derived IDs can still collide with other submitted/full/folded identities under the existing Core collision boundary. Naming allocates explicit identity registration capacity even though no extra layout box is added. This proposal adds no global identity registry, reservation phase or input architecture. Standalone Checkbox/Radio uses its new C `_with_parts` route **only while its INDICATOR canonical slot is authored, including explicit empty**. Root-only styles retain the old anonymous route. Reset of INDICATOR/MAIN restores the old anonymous route on the next submission, even if a row ROOT override remains. Do not submit old and named facades together, and do not replace custom glyph painting with a second component or wrapper. ### RadioGroup all-descriptor boundary The existing C named group API requires one nonzero descriptor per item, with count equal to item count; partial zero descriptors are invalid. Therefore if **any** child ITEM indicator override is authored, call the named group route with captured stable IDs for **all** current items, while applying shadows only to authored targets. Unstyled peers acquire explicit indicator identities in that opted-in group submission; their layer defaults and pixels remain normal. This identity/capacity change must be documented and tested, not called a per-item anonymous-preservation guarantee. Group ROOT or item ROOT alone does not activate named indicators. Resetting the last authored item indicator returns the whole group to the legacy anonymous route next frame. Removing the last such item has the same effect; adding/reordering items regenerates descriptors from stable item identity before the single reducer call. This is the recommended first compatible route with the existing C API. If review requires unstyled peers to remain anonymous while another item is styled, stop before production: that requires a separately approved additive partial-naming C contract and tests. Do not pass zero descriptors to today's named API, mutate its validation, silently reject mixed authored groups or repaint individual Radios. ## Submission, absence and error boundaries Capture routing/descriptor choices before owner callbacks. Component defaults and all complete owner paint run first; apply each authored override afterward using the actual public getter or captured named descriptor. Use `cui_frame_paint_enabled`, not the input-observation `cui_frame_sequence` guard. Inert ancestry still paints decorations. Measurement/layout-only passes neither apply styles nor report missing paint; retained values survive for real paint. Distinguish four cases explicitly: | Case | Required behavior | | --- | --- | | Declared unsupported role/owner path | Reject mutation before copying; no row fallback and no dormant-success fiction. | | Supported owner not visited in this frame | Retain styles, do no Core lookup, no frame error merely for omission. No previous-frame presence required. | | Reviewed conditional owner not admitted by its actual rendering branch | Retain styles; branch reports normal omission internally and does not attempt part styling. No entire-UI failure. | | Owner has entered ordinary painting and its expected mandatory part is missing, collided, or rejected | Existing bridge CORE_ERROR/frame diagnostic; do not swallow Core INVALID_ACTION as ordinary absence. | The first mapped control parts are mandatory once their owner successfully enters ordinary paint. Unchecked Radio still has its circular indicator; empty label still has indicator/track; Slider ratio0 omits fill, never track. An empty RadioGroup has no ITEM targets to style, and may still have its group ROOT. Detached/unvisited items are not absent items of a different group; handle/owner validation prevents that ambiguity. An implementation should carry a small stack-local submission outcome (not-attempted/omitted/submitted/failed) at the owner branch, not add a retained style graph or infer admission from changed/valid component return values. Group `result.valid` is input validation, not completed layout; bool changed is activation, not paint admission. Authoring allocation failure returns OUT_OF_MEMORY with previous styles and local facade state unchanged. Descriptor/capability/style errors occur before allocation. Exhausted allowed identity counters, if an implementation chooses allocation rather than derivation, must return CAPACITY before committing any identity/style state; that alternative requires its own exact rollback design. Do not introduce that allocator implicitly while implementing this proposal. Frame node/command/ID capacity or global/folded collision remains an ordinary composition failure. Reduction/callbacks/accepted owner values may already have occurred, exactly as documented by the C named-indicator API; no rollback of input, callbacks or owner state is promised. Retained requested styles remain available for recovery. Rejected authoring and late frame failure are different atomicity boundaries. Preserve the first meaningful frame error and avoid converting an earlier OUT_OF_MEMORY into a misleading later missing-target error. ## Storage budget and choice requiring review The existing inline root style costs224 bytes on every node; its measured complete Linux x86-64 node was73,128 bytes before this extension. Reuse that field for ROOT on every admitted kind. Do not move or resize any public wire/options struct. Nonroot roles are bounded: one indicator for Checkbox/Radio/RadioGroup ITEM, one track for Slider, two independent track/thumb values for Switch. MAIN is an alias and consumes no additional slot. Recommended: one nullable private extension pointer per node, allocated only on first nonroot set (including empty), freed after the last nonroot reset/removal. A pointer contributes8 bytes/node on the audited64-bit ABI, including idle nodes; 32-bit cost/packing must be measured separately. A concrete payload can contain uint32 presence/reserved (8 bytes) plus one or two224-byte V1 values:232 bytes for indicator/Slider,456 for Switch, plus allocator overhead. ROOT stays inline. No per-frame allocation or borrowed layer pointer is needed; descriptor arrays for <=64 group items fit512 bytes of stack without retaining new item-ID buffers. If a new persistent field is added for identity, revise these numbers before code. At the current app maximum1024 nodes, new idle pointer overhead is8,192 bytes on that ABI; all-Switch nonroot payloads are at most466,944 bytes excluding allocator metadata. Existing root storage is229,376 bytes and is not a new part cost. These are bounded estimates, not measured final `sizeof` claims. Styles on unsupported roles cannot allocate more slots. Check size arithmetic before malloc and test injected allocation failure on initial set and existing-target replace. Alternatives to review: | Choice | Idle overhead | Active cost/tradeoff | | --- | --- | --- | | Two extra inline styles + mask per node | At least452 bytes/node even with no part authoring | No allocation failure, but >=462,848 extra bytes at1024 nodes; wasteful for most kinds. | | Recommended nullable extension | One pointer/node |232/456 payload per styled node, allocator overhead and explicit failure/free paths. | | App-owned sparse array keyed by slot+generation+canonical role | Potentially zero new node bytes, plus app bookkeeping | Bounded search/growth/removal complexity and explicit capacity policy. Could share a small hard cap, but cannot silently evict another style. | Do not introduce an unbounded map, inherited style graph or generalized resource registry for this slice. The sparse-app alternative needs separately approved capacity/lookup behavior before replacing the simpler pointer proposal. No new option is appended to the old bridge options struct. ## Typed facade shape Reuse existing `BoxShadow`, `CornerRadii`, `ShadowStyle`, typed presets and Core factories. Add typed role selection rather than raw paint IDs or CSS strings. Example spelling to review: ```text Python/JS: control.part_shadows(ShadowPart.INDICATOR, layers, radii) control.part_shadow_preset(ShadowPart.MAIN, preset, radii) control.reset_part_shadows(ShadowPart.INDICATOR) Go: control.PartShadows(ShadowIndicator, style).ResetPartShadows(ShadowIndicator) Rust: app.part_box_shadows(control, ShadowPart::Indicator, &style)? app.reset_part_box_shadows(control, ShadowPart::Indicator)? ``` Explicit ROOT uses these new target methods; current `.box_shadows` methods keep their exact six-kind behavior. `[]` is clear; reset is separate. Mounted runtime capability always decides the actual owner route. Python/Go preserve optional new-symbol loading. Rust error and app identity checks precede mutation; JS retains its current failed-mount disposal behavior. None may commit local copied state after a native failure. Unmounted ITEM requests may be stored before its RadioGroup parent is assigned, but mount must validate ownership and roll back with the facade's existing contract if placed under Tabs/List/other owners. TypeScript should expose bounded per-constructor part interfaces rather than add all roles to shared Label/Input/base interfaces. Checkbox/Radio allow ROOT/MAIN/ INDICATOR, Switch ROOT/MAIN/TRACK/THUMB, Slider ROOT/MAIN/TRACK. A RadioGroup item builder can provide an owner-specific typed result; generic ITEM must still validate at runtime and cannot promise every ITEM is an indicator. JS and TS are one runtime proof plus a separate strict declaration test, not two independent renderers. Keep the typed definitions in their narrow modules and revision-matched skill resource exports; no bulky binding-wide context dump is required. ## Acceptance gate after review The original design checkpoint ran no production or tests. Review subsequently approved the descriptor/info signatures, role table, context whitelist, whole-group naming boundary, pointer budget and failure semantics. The acceptance plan was: 1. Portable real bridge capture for every table row and alias. Assert actual caster is square/circle/track/thumb rather than label row; independent ROOT and part lists, both Switch parts, mixed DROP/INSET, eight layers, movement, explicit radii, clipping and opacity. Slider THUMB/fill rejects. Original no-opt-in streams/pixels and old six-root setters remain unchanged. 2. Standalone Checkbox/Radio named route activates only with authored indicator, including empty; ROOT-only stays anonymous and reset restores legacy. Count Base requests/callbacks once. All state/disabled/empty-label variants preserve existing focus, semantics, glyphs and activation; introduce no new hit target. 3. RadioGroup uses its real owner painter once, styles distinct ITEMs independently, and retains selection and notification order. Cover mixed styled/unstyled peers, group/item ROOT, reorder, add/remove, last-reset legacy return,64 items, group descriptor copies, full/folded collision and ID-capacity costs. Other ITEM parents and Settings-owned field controls reject without allocating. 4. Copied caller arrays, replacement, alias last-write-wins, empty/NONE versus reset, stale handle/subtree destruction/slot reuse, invalid style and allocation failure atomicity. Measure actual node/payload sizes and active allocation balance; check no allocation or ID growth on each repeated frame. 5. Inert paint, measurement/layout-only work, omitted traversal and any admitted conditional callback route. Assert normal omission succeeds without styling stale geometry, while unexpected missing mandatory parts and capacity errors preserve the documented frame/error boundary and recover next frame. 6. All five facades: pre-mount and mounted ownership, unsupported owner mount rollback, native failure/local-state preservation, callback mutation under existing rules, float32 overflow/radii ordering, canonical factory parity and missing-symbol compatibility. Strict TS rejects nonexistent Slider thumb and generic compound claims. Wire size/offset tests cover every FFI. Use the existing focused build and coordinated nice19, single-CPU/-j1 slot; native executions only through test_local.py/private Xvfb and browser probes headless. Fontless software may omit TEXT only with independent original text command checks; it cannot establish glyph/GPU/browser parity. Update source coverage, docs, examples, SDK/amalgamation and skill resources only when production is approved and actual tests pass. Keep all78 manifest entries and the broader beta shadow milestone pending. Portals, other compound parts, generic style inheritance, Core presence registries and input architecture remain separate work. ## Approved implementation checkpoint Review approved the nullable per-node extension and whole-group naming choice. The next-batch implementation uses public `cui_id_from(NULL, bounded_key)` for private deterministic indicator identities, checks snprintf/zero/full-owner identity, and uses existing Switch/Slider public part getters. It copies no Core folded-ID algorithm and adds no identity allocator/reservation or input path. The measured Linux x86-64 node is73,136 bytes, extension pointer8 and payloads 232/456 bytes. Deletion resets the freed pointer before later app cleanup. Focused portable/native and all five facade checks cover the bounded target mapping; the consumer contract and reproducible commands are in [BRIDGE_PART_SHADOWS.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_PART_SHADOWS.md). The original signed proposal is preserved above. This checkpoint does not extend panel/portal mappings or mark the broader beta/all78 shadow milestone complete. --- ## Controlled typed Slider bridge v1: exact proposal Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/BRIDGE_SLIDER_MODEL_V1.md # Controlled typed Slider bridge v1: exact proposal Design only, `/root/hidden_windows`, 2026-11-01. Based on integrated `259e298a2c65ad5d1554e04360c7b74ac437d58f`, including the new typed gallery. No production declarations/implementation, compilation, dependency or generation changes here. This makes the future-bridge section of [SLIDER_MODEL_ABI_V1.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SLIDER_MODEL_ABI_V1.md) concrete; its b24 immutable-current / evolving-requested and explicit acceptance resolution remains authoritative. Root decisions below precede implementation; this is not an implemented API. ## Existing authority and preservation boundary - `include/cui/cui_bridge.h`: ABI_VERSION1, exact-size `cui_bridge_options`, node `{uint32_t slot,generation}`, old scalar event/ex/notification layouts. Keep every old struct, enum value, exported signature and constructor unchanged. - `src/bridge/cui_bridge.c`: `bridge_ready` checks null/closed/stepping, not a portable thread identity. `bridge_node` checks full live generation. `cui_bridge_node_create` retires generation UINT32_MAX slots and stops ID allocation at UINT64_MAX; failed creation can consume an unpublished internal ID. Preserve that monotonic/no-reuse policy, not fabricated identity reuse. - Legacy Slider render branch casts node doubles to float, calls `cui_slider`, writes its result back and enqueues CHANGE. `set_range` requires min0 and Slider bounds/step within its existing float-safe range. Keep this exact route, callbacks, precision, limits, autoaccept and notifications. - `bridge_change` / `poll_event_ex` / notification views share the existing FIFO. New proposals must never enter it, downgrade to LEGACY, or be drained by old polling. New typed requests are not scalar accepted-value notifications. Existing shadow target contracts remain unchanged for legacy Slider. New kind81 has no implicit shadow setter support: initially reject those authoring calls explicitly; named typed root/track/thumb shadow authoring needs its own facade mapping review, not salt reuse or a false THUMB capability. This omission must appear in all-five guidance until implemented. - Actual model source: `src/base/cui_base_slider_model.c` validation reserves sequence space with **all** current frame events, `3*count+1`; it does not expose a target-only capacity reservation. Use that conservative bound. - `web/gallery.c` now demonstrates synchronous C model requests, external owner acceptance and passive wakes. Bridge requests instead cross an owned queue and callbacks happen after step. Do not claim their acceptance repaints that frame. ## New kind and exact records Propose append `CUI_BRIDGE_SLIDER_MODEL = 81`, a versioned authoring route for the same Slider family, not an additional catalog family. All78 stay intact. A new factory below creates it; old `slider()` builders still create kind9. Generic `node_create` with81 rejects INVALID_STATE and directs callers to the factory until valid config/value can be supplied atomically. Common Row/Column composition, label text and disabled policy are supported; legacy scalar value/range APIs reject kind81. No hidden upgrade of mounted kind9 nodes. Public header remains independent of Core/Base/Styled headers. All tags are uint32_t fields and all identities uint64_t; enums below name fixed numbers. Order new record headers `struct_size,schema_version`, matching current bridge V1 conventions (the older design's version/size order is not a shipped ABI). Natural C ABI, no packing, pointers, unions, size_t, platform or Clay types: ```c #define CUI_BRIDGE_SLIDER_MODEL_V1 1u /* Value kind SINGLE0/RANGE1; scale LINEAR0/LOGARITHMIC1; axis H0/V1. */ typedef struct { uint32_t kind, reserved; double start, end; } cui_bridge_slider_value_v1; typedef struct { double minimum, maximum, step; uint32_t scale, reserved; } cui_bridge_slider_domain_v1; typedef struct { uint32_t struct_size, schema_version, flags, orientation; uint64_t source_generation; cui_bridge_slider_domain_v1 domain; float rem, length; uint32_t layout, reserved; } cui_bridge_slider_config_v1; /* flags: REQUESTS1, READONLY2, REVERSE_FILL4, REDUCED_MOTION8, HIDE_FOCUS16. * layout: FIXED0 / PARENT1. Node disabled is the existing common policy. */ typedef struct { uint32_t struct_size, schema_version, render_status, reserved; double core_time, next_wake_seconds; } cui_bridge_slider_presentation_v1; typedef struct { uint32_t struct_size, schema_version, capacity, reserved; } cui_bridge_slider_queue_options_v1; typedef struct { uint32_t struct_size, schema_version; uint64_t app_epoch; cui_bridge_node node; uint64_t source_generation, configuration_revision; uint64_t submission_frame, request_sequence; } cui_bridge_slider_receipt_v1; typedef struct { uint32_t type, flags, key, modifiers; float x, y; uint32_t repeat, pointer_type, pointer_button, accessibility_action; uint64_t pointer_id, pointer_device, accessibility_target; double accessibility_value; } cui_bridge_slider_input_v1; typedef struct { uint32_t struct_size, schema_version, phase, reason; uint32_t thumb, event_kind, event_source, event_flags; cui_bridge_slider_receipt_v1 receipt; uint64_t event_target, event_frame, event_index; cui_bridge_slider_value_v1 current, requested; cui_bridge_slider_domain_v1 domain, gesture_domain; cui_bridge_slider_input_v1 input; } cui_bridge_slider_request_v1; ``` Expected sizes from field-layout arithmetic (not compiler proof at this static checkpoint): LP64 with 8-aligned double/u64, i386-style ILP32 with4 alignment, and wasm32 with8 alignment all give the same sizes/offsets, because preceding groups are deliberately multiples of8. Production must prove native and actual pinned wasm32 `sizeof/offsetof` with strict fixtures; no claim all ILP32 ABIs measured. | Record | Bytes on these three models | Important offsets | | --- | ---: | --- | | value |24|kind0,reserved4,start8,end16| | domain |32|min0,max8,step16,scale24,reserved28| | config |72|flags8,axis12,source16,domain24,rem56,length60,layout64,reserved68| | queue options |16|capacity8,reserved12| | presentation |32|render_status8,reserved12,Core time16,wake24| | receipt |56|epoch8,node16,source24,revision32,frame40,sequence48| | input |72|type0,flags4,key8,modifiers12,x16,y20,repeat24,type28,button32,action36,id40,device48,target56,value64| | request |296|phase8,reason12,thumb16,kind20,source24,flags28,receipt32,target88,frame96,index104,current112,requested136,domain160,gesture192,input224| Size query functions below return library sizes, not permission to truncate or reinterpret records on another ABI. Fixed nested records have no separate schema header; their authority is the containing v1 schema and explicit size argument. ## Exact exported signatures proposed Every declaration below would carry CUI_BRIDGE_API and return existing status. No C foreign callback registration is added. The Base handler is a private bridge queue producer, not a language trampoline during Core composition. ```c uint32_t cui_bridge_slider_model_versions(void); /* bit0 means complete v1 */ uint32_t cui_bridge_slider_config_v1_size(void); uint32_t cui_bridge_slider_value_v1_size(void); uint32_t cui_bridge_slider_receipt_v1_size(void); uint32_t cui_bridge_slider_request_v1_size(void); uint32_t cui_bridge_slider_presentation_v1_size(void); cui_bridge_status cui_bridge_slider_queue_enable_v1(cui_bridge_app *, uint32_t options_size, const cui_bridge_slider_queue_options_v1 *); cui_bridge_status cui_bridge_slider_model_create_v1(cui_bridge_app *, cui_bridge_node parent, const char *key_utf8, uint32_t config_size, const cui_bridge_slider_config_v1 *, uint32_t value_size, const cui_bridge_slider_value_v1 *, cui_bridge_node *out); cui_bridge_status cui_bridge_slider_model_configure_v1(cui_bridge_app *, cui_bridge_node, uint32_t config_size, const cui_bridge_slider_config_v1 *, uint32_t value_size, const cui_bridge_slider_value_v1 *); cui_bridge_status cui_bridge_slider_model_get_config_v1(cui_bridge_app *, cui_bridge_node, uint32_t config_size, cui_bridge_slider_config_v1 *out); cui_bridge_status cui_bridge_slider_model_set_value_v1(cui_bridge_app *, cui_bridge_node, uint32_t value_size, const cui_bridge_slider_value_v1 *); cui_bridge_status cui_bridge_slider_model_get_value_v1(cui_bridge_app *, cui_bridge_node, uint32_t value_size, cui_bridge_slider_value_v1 *out); cui_bridge_status cui_bridge_poll_slider_request_v1(cui_bridge_app *, uint32_t request_size, cui_bridge_slider_request_v1 *out); cui_bridge_status cui_bridge_accept_slider_request_v1(cui_bridge_app *, uint32_t receipt_size, const cui_bridge_slider_receipt_v1 *, uint32_t value_size, const cui_bridge_slider_value_v1 *); cui_bridge_status cui_bridge_slider_model_get_presentation_v1(cui_bridge_app *, cui_bridge_node, uint32_t presentation_size, cui_bridge_slider_presentation_v1 *out); cui_bridge_status cui_bridge_slider_model_part_bounds_v1(cui_bridge_app *, cui_bridge_node, uint32_t part, cui_bridge_rect *out); ``` Enable is explicit before factory; no implicit allocation in old constructors. Queue options size/schema16/1, reserved0, capacity1..4096;0 selects4096. Re-enable same capacity on owner thread is idempotent, different capacity INVALID_STATE; no resize/shrink/receipt replay. New factory requires enabled sidecar. A readonly new model can exist without REQUESTS, but enabling remains explicit for common thread/epoch ownership. Capacity exhaustion/unsupported returns existing codes. Part0..4 means ROOT/TRACK/FILL/START_THUMB/END_THUMB. It queries actual last completed geometry; absent/inactive START/disabled omitted paint can return EMPTY without changing out. Getter never manufactures presence from stable IDs. Root geometry and semantic nodes may exist when decorative surface paint omits. Presentation query copies last completed render status (explicit mapped0..5), absolute accumulated Core time and passive next wake (0 idle). Before first successful submission EMPTY; failed completed frame CORE_ERROR, outputs unchanged. It exposes observations, never internal animation state or renderer capability. Manual hosts translate `next_wake_seconds-core_time` to their monotonic clock; accept invalidates via existing Core mechanism and needs a later host frame. `src/bridge/cui_bridge_sdl.c:bridge_run_frame` already continuously invalidates when an after-frame callback exists. Preserve that old run cadence; no claim this slice converts native run/all-five loops to passive scheduling. New UI examples can use the copied deadline in manual loops without adding a dispatcher. ## Validation and atomicity - Exact top-level size/schema1, reserved0, known flags/tags, nonnull accessible declared storage extents. Public callers own all extents; no buffer probing. - Value: reserved0, SINGLE0 ignores start even NaN and canonicalizes copied start0; RANGE1 requires finite min<=start<=end<=max. End always finite. No sorting, float32 casts or scalar end-only fallback. Getters return full tagged copies. - Domain uses actual `cui_slider_model_domain_valid_v1`: finite min<=max, finite span, finite step>=0; log requires positive min0 with finite1.5*rem. FIXED requires finite length>0; PARENT ignores length and canonicalizes copied length0. No palette/brush/theme pointers. Owned style is resolved from current app theme via the actual facade, not preset-name inference. V1 visible linear brush rejects before Base. Real V2 host/palette transport is deliberately absent, not flattened or advertised. - REQUESTS absent or READONLY set makes new model readonly. Flags remain stored separately so changing the explicit observer policy is visible in config. New common disabled changes invalidate receipt policy; old nodes unchanged. Existing set-text copies the accessible name, with bounded copied derived start/end labels; no public borrowed strings. New-kind label changes revise receipt configuration. Actual visible labels remain ordinary sibling Label nodes in examples. Initial source/rem/layout/domain defaults are explicit wrapper config factories, not inferred from scalar legacy Value/range. - Config+value change validates both before commit, updates external confirmed pair and increments revision, retains Base reducer for captured cancellation, resets presentation as needed. Never reinitialize an active Base gesture to bypass CANCEL. Direct set-value also increments revision even for equal pair; successful accept does not. Revision UINT64_MAX rejects replacement atomically. - Invalid getters, size/version/reserved/tag/pair, wrong phase/thread or capacity preserve output bytes and queues/owner/config. Public input is copied before mutation, so normal caller input/output aliasing is safe. Model factory failure preserves public out/queues/other nodes; existing allocator may consume an unpublished internal ID, never a reusable public receipt identity. - REQUEST output is fieldwise mapped and canonicalized, never memcpy of Base metadata/padding. phase BEGIN0/UPDATE1/COMMIT2/CANCEL3; reason0..9 follows actual Base named vocabulary, thumb START0/END1. event_kind UPDATE=REQUEST1, COMMIT=COMMIT3, BEGIN/CANCEL=LIFECYCLE5. SOURCE UNKNOWN0,PROGRAMMATIC1,POINTER2, KEYBOARD3,ACCESSIBILITY4. event flags HAS_FRAME1/HAS_INDEX2/HAS_SOURCE4 only; HAS_ACTIVATION8 never synthesized. Target is actual semantic64 ID, not node. - Absent event frame=0/index=UINT64_MAX; present size_t index widens checked. UNKNOWN omits HAS_SOURCE. Actual input flags HAS_INPUT1/HAS_NUMERIC_VALUE2; absent input is allzero. Pointer/key fields copy actual evidence only; numeric SET keeps raw published-semantic double/action/target. Increment/decrement inactive numeric value canonical0; no coordinate or key fabrication. Producer maps supported Core constants explicitly in source; it must not assert raw enum ABI equality. Proposed output tags: POINTER_MOVE0/DOWN1/UP2, KEY_DOWN3, CANCEL7, ACCESSIBILITY13; key NONE0/ESCAPE4/LEFT5/RIGHT6/UP7/DOWN8/HOME9/END10/ PAGEUP19/PAGEDOWN20, modifier SHIFT1/CTRL2/ALT4/META8; pointer MOUSE0/TOUCH1/PEN2, button PRIMARY0/SECONDARY1/MIDDLE2, accessibility INCREMENT2/DECREMENT3/SET4. Inapplicable fields zero; unsupported future output vocabulary requires a new schema rather than silently mapping to mouse/key/UNKNOWN evidence. New wrappers retain unknown future schema as unsupported rather than guessing. Output records are copies, not submitted event authority; accept reads only receipt+explicit value. ## Queue, identity and receipt authority Proposed lazy private app sidecar: one pointer in private app, a bounded pointer index for `(max_nodes+1)` typed owners, queue and owner thread/epoch state. No old node-record growth, eager queue allocation or new old-constructor branch. Allocate sidecar/index/queue in one checked aligned block on successful enable; per-new-node owned model/presentation/config/value allocated independently. Formula is `sizeof(private_header)+aligned((max_nodes+1)*sizeof(owner_pointer))+ capacity*sizeof(request)` plus explicit alignment padding; exact header/owner sizes require production `sizeof` receipt, not an invented ABI promise. Queue payload at default4096 is1,212,416bytes; opt-in only, retained until app destroy. One-node pure state160 +presentation112 observations do not imply private-owner allocation size. Allocation failure leaves previous state untouched. Before each writable model submission, check overflow-safe `3*frame_event_count+1` free request slots, using actual public `cui_frame_events`; reserve/release unused budget around that one synchronous reduction. Count all events, including ones not ultimately eligible. No allocation/overwrite/drop-oldest on callback, no foreign callbacks while stepping. Preflight failure occurs before this node's Base/state/input/callback/paint, sets bridge frame_error CAPACITY; previously processed nodes/events remain real. It is not whole-frame rollback. Small custom queues can conservatively reject even when fewer requests would have emitted. With current max_nodes1024 / dispatch512,4096 covers an initially empty queue's conservative bound plus at most one synthetic cancel per preceding model; this is source-derived, not a permanent public Core capacity promise. Backlog can still exhaust it. No new target-dispatch introspection or copied reducer logic. Epoch proposed: private process counter starts1, issued only to successful new sidecar opt-in, never pointer-derived or reused. Protect uint64 counter using C11 atomic_flag (always lock-free flag primitive), saturating at UINT64_MAX; exhaustion CAPACITY. No global receipt registry. Production must verify actual native/WASM implementation/link support before advertising versions bit0. Node identity remains full slot+generation plus semantic ID in evidence. Receipt revision starts1; source/config/owner replacement invalidates old authority. Record first/last **actually emitted contiguous** request sequence per current submission plus last accepted sequence; no sequence wrap. A receipt is an integrity-checked process-local snapshot, not a cryptographic capability against malicious in-process code. Matching an unissued guessed sequence must reject. Poll copies one record and consumes once; exact-size invalid fails before any cleanup. Removed/reused node origins may be pruned on valid poll, matching current bridge stale-origin policy; live but expired receipts remain readable snapshots. EMPTY preserves out. Already copied records outlive later polls/frames/app destroy; using a destroyed C app pointer remains invalid, never a supported accept call. Accept requires owner thread, outside stepping/Core frame (after-frame allowed), valid completed Core snapshot, matching nonzero epoch/live full node/source/ revision/latest admitted painted state-frame and emitted range, sequence strictly larger than last accepted, valid full pair in CURRENT domain/kind and writable current policy. Accept updates owner +last accepted only; it schedules future paint using existing bridge invalidation/host wake policy, never alters prior commands. Owner may choose a valid pair different from proposal. In the same submission, accepting UPDATE does not invalidate later COMMIT. No autoaccept on phase, poll, input consume or callback success. Captured CANCEL is readable old kind/domain; explicit adjusted current-valid acceptance is possible, never blind. Invalidate windows on failed begin/end/current invalidity even after error clear; request copies already emitted remain readable, not acceptable. Geometry-only recovery must not renew: require actual model state-frame==submission frame plus successful completed snapshot; next healthy admitted state-frame can reopen. No rollback/replay of already performed callbacks or earlier owner acceptance. Existing b24 layout-only rule remains: no renewal or expiry solely from a layout-only visit. **Proposed clarification requiring root review:** ordinary completed omission revokes acceptance, whereas retaining a layout-only copy does not grant new authority. Removal/reparent/policy change invalidate regardless. No frame-wrap collision: sequence never reuses, emitted window empty if no new requests; zero-generation phase never creates a receipt. ## Thread and callback policy: explicit decisions The old bridge does not enforce portable thread identity. Do not pretend existing `bridge_ready` already rejects wrong-thread typed calls. Proposal: capture a private C11 `_Thread_local` tag address on first successful enable; new API, new-kind common mutation branches and new-model step path require same tag (plus serialized lifetime/no concurrent calls). Owner OS thread stays alive through destroy, preventing thread-exit/tag reuse from becoming an ownership-transfer API. On wasm single-thread targets, one explicit constant owner is sufficient only when host cannot share it across threads. No portable thread dependency or platform types leak publicly. **Root decision required:** approve/probe this private TLS policy and epoch atomic_flag before implementation, or explicitly revise the earlier guaranteed wrong-thread rejection to a caller precondition. Unsupported TLS/target mode must advertise versions0 rather than claim enforcement. No locks around Core/callbacks, new dispatcher, old thread checks, thread migration or public host callback added. No process-race guarantee for destroying a handle concurrently with any API. Go already locks the creating OS thread and checks a private platform token in `bindings/go/cui/native.go`; Rust already documents creating-thread ownership. Reuse their authority rather than insert a second wrapper owner or transfer API; the new C check closes the current direct-C gap only. Existing C `step` never invokes foreign change callbacks. Python `step` only steps; dispatch is separate. JS `step` steps then `_dispatch`; step_only doesn't. Go Step and Rust step also only step; their Dispatch/dispatch/pump/run compose callbacks in existing phases. Preserve these differences and ALL legacy order. Propose new `dispatch_slider_requests` methods and explicitly call them after legacy dispatch in existing combined helpers/run callbacks. No global original ordering between the two queues; each queue is FIFO. Do not silently interleave or retime old callbacks. Manual polling never dispatches. A legacy callback that advances an app may expire later typed receipts; do not change old behavior or replay stale requests to conceal that fact. During new typed callback only, wrapper guard rejects nested step/run/typed dispatch, keeping accept/config operations explicit and outside active Core. External owner/userdata mutation and enqueueing later work are permitted. New request records are owned immutable copies; closure registration lives until removal/dispose. No C callback pointer retained. Python/JS exceptions and Rust/Go panic cannot cross C: callbacks are after FFI return; native after-frame trampoline uses existing catch/latch/rethrow/error-on-return policy. The failed callback's already-popped request stays consumed, no automatic accept/retry; later queue entries remain available. Dispose semantics remain the existing deferred native run contract; never use app after destroy returns. ## Five authoring surfaces and real tests | Consumer | Proposed additive authoring and owned mapping | | --- | --- | | Python | `slider_model(key, config, confirmed).on_request(fn)`, frozen tagged value/domain/input/request/receipt dataclasses, `app.accept_slider_request(request.receipt, pair)`; float doubles, int identities, no ctypes storage retained. Optional symbol group allows old library loading and errors before mount on use. | | JS | `slider_model(key, config, confirmed).on_request(fn)`; addon fieldwise copies, frozen tagged objects; number doubles and bigint ALL64-bit identities/frame/index/source/sequence, uint32 node fields. Reject unsafe Number identity, no JSON transport. Explicit app accept and typed dispatch. | | TS | Match JS in both declaration entrypoints, discriminated Single/Range, bigint receipts, typed callback+explicit accept. Positive and negative compile tests plus actual JS UI runtime, not types-only closure. | | Go | `SliderModel(key, config, value).OnRequest(fn)`, uint32 tags,uint64 IDs,float64 complete pairs; App.AcceptSliderRequest returns error, copied cgo output, existing error latching/mount ordering retained. Optional symbols preserve old dynamic loads. | | Rust | Builder/owned Single/Range and config/request/receipt records using f64/u64; explicit Result accept; owned copy before callback and no RefCell/mutable App borrow held across callback. Static matching SDK; optional dynamic symbol group fails cleanly on old libraries. | Each language needs a genuinely mounted UI example (Row/Column +Single and Range, real callback and accept/reject policy, next-frame accepted paint), not a launcher or a print-only poll demo. Runtime tests use current bridge and an independently preserved pre-feature shared library to prove old symbols/loaders still work. New feature missing returns BACKEND_UNAVAILABLE without silently using Value/range. All existing legacy builders and callbacks keep their routes/timing. Current manual injection gaps: `cui_bridge_queue_key` accepts only keys1..8 (Tab through Down), and `queue_pointer` carries only mouse phase/x/y. Native SDL can deliver richer Core events, but old foreign injection cannot prove Home/End, PageUp/Down or contact identity. Do not widen old validation invisibly or call a mouse event a touch test. Separate reviewed additive versioned key/contact input records forwarding existing Core queue (no dispatcher) or actual native host fixtures are required for those all-five tests. Their exact API is OUTSIDE this receipt slice; mark omitted until approved. Similarly typed SET injection helpers are not Linux AT-SPI delivery proof; native precision/host options remain separate. Verification plan for C slice: native/ILP32-layout/actual wasm ABI static asserts, old-size/default-loader/legacy trace parity, output byte snapshots on every failure, input aliasing, all value/domain extremes from existing pure oracle; actual new Styled paint/bounds/current-vs-requested pair, both axes/kinds, reverse/log/step/rejection/disabled/readonly, held capture config CANCEL, omission/recovery/current layout failure+clear, same-frame UPDATE→COMMIT ordered accept, foreign app/node reuse/revision/source/frame/sequence/guessed-unissued rejection, epoch/revision/sequence exhaustion, queue preflight/backlog/retention, post-failure readable-but-unacceptable snapshots, wrong-thread policy and callback exceptions/reentrancy in each runtime. First frames have real generation only. Headless native always private Xvfb; browser headless. No whole-family claim from C helpers: source palette/gradient consumers, real native numeric delivery, vertical registered-scroll admission and all-five installed UI authoring remain independent requirements. On implementation, update exact guide/usage metadata, binding coverage/source lists/SDK/dist/skill, preserve78 and run usage6/skill18. Proposed ownership: bridge worker owns header/new private model queue module, bridge internal sidecar/render integration and focused C tests; language workers own only their wrapper/runtime example/tests after C ABI approval; Core/native and vertical-layout owners remain independent. Integrator alone owns shared `tests/web/test_browser.py`/Pages workflow and canonical integration/push. ## Review resolution and portability probe receipt (2026-11-01) Root approved kind81, fixed records, independent FIFO, explicit acceptance, legacy timing preservation and ordinary completed omission expiry. Native owner TLS plus saturating atomic_flag epoch policy is now bounded-probe verified; compatible bridge production still waits for root's review of this checkpoint. Record layout calculations above remain calculations until production ABI tests. Approved target policy is conservative and explicit, **not** an assumption that WASI cannot have shared memory. The pinned linker demonstrably supports it. Proposed private implementation guard, exercised by the test-only fixture: ```c #if defined(CUI_BRIDGE_SLIDER_NO_TLS) #define OWNER_SUPPORTED 0 #elif defined(__wasm__) #if defined(CUI_BRIDGE_SLIDER_WASM_UNSHARED) && CUI_BRIDGE_SLIDER_WASM_UNSHARED == 1 && \ !defined(__wasm_atomics__) && !defined(_REENTRANT) #define OWNER_SUPPORTED 1 #else #define OWNER_SUPPORTED 0 #endif #else #define OWNER_SUPPORTED 1 #endif ``` - Native portable C11 TLS/atomic_flag: supported where these compile; actual runtime proof here is Linux GCC, not Windows/macOS runtime evidence. An unsupported compiler/build sets private `CUI_BRIDGE_SLIDER_NO_TLS` and keeps new versions0/stubs BACKEND_UNAVAILABLE. Do not fall back to a constant owner. - **Default WASM versions0**. Only explicit `CUI_BRIDGE_SLIDER_WASM_UNSHARED=1` opts a trusted unshared builder in, provided atomics/reentrant macros are absent. This flag is a build assertion, not a runtime capability query or public record field. It requires final-artifact verification: memory is nonshared and no imported shared memory can replace it. - The C preprocessor cannot detect another translation unit's flags or a later linker `--shared-memory`; compile flags alone never prove final host ownership. Unverified generic WASM SDK consumers must retain versions0. Known builds must run postlink verification on their actual final module before advertising this opt-in. The probe's actual default module had imports[] and nonshared exported memory; it used the compiler's `_Thread_local`, no replacement token. - Atomics/pthread/shared WASM remains versions0 even with the unshared assertion. No Worker TLS initialization, thread tag uniqueness across Workers, native shared-memory ownership enforcement or threads-disabled fallback is claimed. The support-disabled production path must not allocate/issue epochs/enable kind81; old bridge routes remain available. No more shared-Worker work is required for this v1 slice. - The owner OS thread must stay alive until app destroy. No ownership transfer, dead-thread tag reuse, concurrent API/destroy or synchronization of Core from another thread is supported. Native worker threads in the probe stay alive while their distinct tags are checked; it does not use recycled thread IDs. ### Reproducible bounded evidence Test-only sources are `tests/fixtures/bridge_owner_primitives_probe.c` and `.cjs`. They include no bridge/Core implementation or public declarations. No production allocator/epoch test hooks are added. Native compile is strict C11/O2/warnings as errors with `-DPROBE_NATIVE=1 -DPROBE_EXPECT_SUPPORT=1 -pthread`; only the probe's C11 thread harness needs pthread linkage. The intended production primitives do not introduce a C11 thread-library dependency. Four simultaneously live owners, 4000 unique epoch values and MAX-1/MAX/exhausted output-atomic behavior passed. Execution used the standard private-Xvfb wrapper with a CTest script invoking this windowless binary, not the desktop. Pinned Zig executable is the installed0.16.0, compiled with `-target wasm32-wasi -mexec-model=reactor -std=c11 -O2 -Wall -Wextra -Wpedantic -Werror`. Export probe owner/match/epoch/seed, support and feature-epoch functions plus memory. Explicit unshared build adds `-DCUI_BRIDGE_SLIDER_WASM_UNSHARED=1 -DPROBE_EXPECT_SUPPORT=1`; actual Node/WASI reactor runtime observed support1, nonshared memory, stable own tag, wrong-tag rejection and exact uint64 saturation. The default/unasserted guard compiled to an object with `-DPROBE_EXPECT_SUPPORT=0` and a successful static assertion. It was deliberately not silently opted in. Zig's `-fsyntax-only` wrapper first diagnosed an unused implicit `-c`; the check was rerun as a real strict object compile, without suppressing warnings or modifying primitive behavior. Shared characterization adds `-matomics -mbulk-memory -pthread`, the same unshared assertion, `-DPROBE_EXPECT_SUPPORT=0`, linker `--shared-memory --import-memory` and exports `__wasm_init_tls`, `__tls_size`, `__tls_align`. Strict compile/link succeeded. Actual Node instantiation imported shared memory with the module's exact257-page minimum/maximum; too-small/too-large trial import limits were correctly rejected first. Runtime verified SharedArrayBuffer, support0 and feature-epoch rejection0. It did NOT call raw shared TLS primitives or invent a Worker initialization protocol. Node emitted its existing experimental WASI warning; no C source warning was suppressed. All artifacts reuse existing `build-focused`; no new checkout/build tree, engine build, dependency installation or heavy skill suite. Native/default/shared three final cached links and the additional default-policy object terminated successfully. Logs and artifact/source hashes are recorded externally under `/home/matteo/.cache/cui-current-validation/bridge-owner-*`; the signed handoff receipt identifies the exact commit. No performance/benchmark claim. Future production should first implement this approved supported-target C slice, then prove real records/receipt rules and frozen legacy behavior. Richer bridge input, five foreign authoring routes, native AT precision/delivery, vertical registered-scroll and actual V2 gradient adapters remain separate open work. ### Production admission (2026-11-01) Root approved the supported-target compatible C slice after the guard probes. Factory signature is corrected before shipping: explicit full parent handle follows app and precedes key. There is no public attach/reparent API; implicit root would break nested composition. Factory validates actual Row/Column parent and retains existing key/ancestry/allocation atomicity. Other records/signatures and all old ABIs stay unchanged. Required proof includes nested Row/Column UI. The unshared runtime fixture now asserts memoryShared==false, rather than merely logging it. Actual final-module postlink verification must enforce that condition. The unshipped CMake helper from the ABI checkpoint is removed before implementation: defining a feature on a shared bridge target while verifying one consumer cannot certify every other final consumer. No shared-WASM CMake linkage/automatic capability claim is made. Instead the trusted opt-in recipe is explicit and applies to EACH final module: compile the actual bridge TU with `-DCUI_BRIDGE_SLIDER_WASM_UNSHARED=1` and no atomics/reentrant flags, link a valid wasm32 final module, run the normal engine/link validation, then run `python scripts/verify_slider_unshared_wasm.py FINAL.wasm` before delivery, and independently inspect actual runtime Memory.buffer in the host proof. Re-linking, embedding in another final host or transforming requires repeating those checks. Do not distribute a pre-opted-in archive/shared bridge as if unrelated consumers were already verified; generic SDKs remain default versions0. A dedicated build variant/automation requires separate review rather than global compile policy. `scripts/verify_slider_unshared_wasm.py` inspects imported and defined memory descriptors, rejects shared/memory64/multiple/missing/ambiguous memory and malformed descriptor data; it is a memory-policy checker, not a full module validator. Successful normal final-module validation is a prerequisite. Four offline tests pass, actual pinned unshared artifact passes and actual shared artifact fails. The runtime fixture additionally asserts actual Memory.buffer is not shared. No renderer negotiation or automatic supported-host discovery is inferred. ### Implementation review resolutions The private epoch counter is scoped to one loaded bridge image / unshared WASM module instance, not a registry across independent duplicate libraries/modules. All handles and receipts must stay within the matching instance and app; cross-image mixing is unsupported. Same-image app epochs never reuse/wrap. This supersedes the proposal's overly broad “process counter” wording; no registry, random nonce or security boundary is added. Any failed actual bridge step, including later-node preflight/facade failure or native rendering after successful Core end, revokes all typed receipt windows. Queued copies remain readable; presentation/bounds return CORE_ERROR unchanged. A retained private failure bit survives diagnostic clear and geometry/layout-only recovery until a healthy ordinary admitted model state-frame. Invalid argument rejection before submission does not expire existing authority. Already delivered application effects are never rolled back. Outer named thumb bounds are rem-sized interaction/layout geometry, not the inner rem-2 painted surface/rings. Disabled source omits thumb paint but keeps track/fill paint and their actual positive bounds. Unsupported future producer tags/modifiers or incoherent numeric evidence fail publication atomically; a failed map latches observable frame error and suppresses remaining publication, so an unissued sequence gap cannot become an acceptable interval. ### C implementation evidence (2026-11-01) The additive C-only kind81 implementation is verified, pending integration; this is not completion of native AT, five typed builders, bridge touch/SET injection, vertical registered-scroll admission or actual V2 adapters. The original proposal above is retained as review history; implemented consumer authority is `include/cui/cui_bridge.h` and `docs/BRIDGE_SLIDER_MODEL.md`. Strict GCC C11/O2/Wall/Wextra/Wpedantic/Werror, linked to the integrator's existing engine without rebuilding it, and private-Xvfb CTest:11/11 passed. Public UI proof composes nested Row/Column, Single/Range and both axes; verifies original-order keys, immutable current/evolving intent, explicit alternative full-pair owner acceptance, double retention, readonly/disabled policy, capacity and expiry. Test-only same-TU proof covers lazy allocation failure, actual Core normalized SET .75→domain75/raw .75,64-bit target identity, failed Core clear/recovery, later-node CAPACITY with valid Core snapshot, simulated native render failure through actual step/end/render/finish, phase0 observation/receipt preservation, ordinary omission, removal/reuse, revision/epoch exhaustion and failed-map gaps. The simulated host proves control flow, not physical SDL/hardware failure. Independent frozen legacy trace from exact `ecb97d5e` bridge TU/private/public headers linked to the SAME engine matched candidate and preserved pre-typed binary byte-for-byte in three distinct executable processes. SHA256: `e2ce75ffe88a98e784acead4e5269175e1565a70e7081b6924b9850f89790415`. The preserved binary's source revision is unknown; no revision is inferred. No LD_LIBRARY_PATH/LD_PRELOAD; each executable has its intended absolute rpath. The portable regression retains that independently captured trace and normalizes only CRT `%a` spelling, comparing exact represented doubles without tolerance. Actual LP64 object sizes: private app1280→1288 (+8), old node73136 unchanged, lazy header56 (failure bit fits padding), per-new-owner472. Enable block is `align_up(56+(max_nodes+1)*sizeof(pointer),alignof(request))+capacity*296`; default256nodes/4096requests uses1,214,528bytes, allocated only on enable. Existing constructor allocation count is unchanged; its private allocation grows8. Node keys/names retain existing separate allocation policy. Pinned Zig0.16 wasm32-wasi strict actual bridge TU policy assertions passed: default0, explicit unshared1, atomics/pthread0. Fixed record ABI assertions also compiled/linked and ran in actual Node WASI (24/32/72/56/72/296/32/16byte records). The earlier real memory/TLS probes remain the supported-mode evidence; these object checks are not a final application renderer/AT/runtime proof. Canonical SDK/agent generation, usage6, skill18 and format/amalgamation/SDK/skill freshness all passed. No new dependencies or build/output tree were created. --- ## Proposed versioned bridge notification views Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/BRIDGE_TYPED_EVENTS_SLICE.md # Proposed versioned bridge notification views Status: design only at `e7202949`. Nothing below is shipped. This extends the [binding audit](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_BINDINGS.md) and [event contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_CONTRACT.md), without synchronous foreign request hooks, callback retiming, global routing or 78-family parity claims. Root reviews ABI/export ownership before implementation. ## Preserve the actual boundary The [C bridge](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_bridge.h) queues snapshots while components reduce/mutate. Foreign callbacks run after the completed step/render, not inside native component dispatch. Preserve FIFO **enqueue order**, scene traversal, per-family aggregation and programmatic notifications. Do not reinterpret notification returns as acceptance or claim chronological input order across components. Concrete source problems motivating an additive view: - [`bridge_data_table_change`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/bridge/cui_bridge.c) snapshots row, column, sort column/direction and reason into JSON, while putting column in `checked` and row in `value`. [Python](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/python/cui_bridge/__init__.py), [Node addon](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/node/addon.c) and [Go](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/go/cui/native.go) convert checked to bool, losing columns above one. [Rust](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/rust/src/lib.rs) retains `checked_raw`, but still lacks a typed table event. Fix the new view; retain legacy bool behavior for compatibility. - Node uses `napi_create_double((double)frame_sequence)` and TypeScript declares `frame: number`; exact uint64 identities above `2^53-1` are lost. A new `frame: bigint` is required, while old events keep Number. Frames are context-local identities, not wall time or global order. - Every wrapper currently polls into 4097 bytes. C `poll_event_ex` supports capacity retry, but wrappers do not generally implement it. Text is an owned queued snapshot, not necessarily the latest getter value. Preserve that snapshot across delayed delivery. - A supported origin handle can remain queued while a selected-item handle becomes stale. Selected slot/generation is historical evidence, not an owning live node reference; never resolve it to a reused slot without generation checks. ## Exact additive C surface proposed Keep `CUI_BRIDGE_ABI_VERSION`, existing options/layouts, `cui_bridge_event`, `cui_bridge_event_ex`, polling symbols and statuses unchanged. Introduce an independently versioned schema with fixed-width discriminators; public enums are named constants, not ABI-sized enum fields. This V1 layout is frozen once shipped. Future larger layouts use a new suffix and capability bit, not extension writes into old caller buffers. ```c #define CUI_BRIDGE_NOTIFICATION_V1 1u #define CUI_BRIDGE_NOTIFY_ACTIVATE 1u #define CUI_BRIDGE_NOTIFY_CHANGE 2u #define CUI_BRIDGE_NOTIFY_LIFECYCLE 3u #define CUI_BRIDGE_PAYLOAD_NONE 0u #define CUI_BRIDGE_PAYLOAD_BOOLEAN 1u #define CUI_BRIDGE_PAYLOAD_SCALAR 2u #define CUI_BRIDGE_PAYLOAD_TEXT 3u #define CUI_BRIDGE_PAYLOAD_SELECTION 4u #define CUI_BRIDGE_PAYLOAD_TABLE 5u #define CUI_BRIDGE_PAYLOAD_SURFACE 6u #define CUI_BRIDGE_PAYLOAD_LEGACY 7u #define CUI_BRIDGE_NOTIFY_HAS_FRAME 1u #define CUI_BRIDGE_TABLE_SELECTION 1u #define CUI_BRIDGE_TABLE_SORT 2u typedef struct { uint32_t reason, row, column, sort_column, sort_direction; } cui_bridge_table_notification_v1; typedef union { uint32_t boolean_value; /* exactly 0 or 1 */ double scalar_value; cui_bridge_node selected; cui_bridge_table_notification_v1 table; uint32_t surface_result; /* existing ACCEPTED/CANCELLED/CLOSED values */ } cui_bridge_notification_value_v1; typedef struct { uint32_t struct_size, schema_version; uint32_t kind, payload_kind, flags, node_kind; cui_bridge_node node; uint64_t frame_sequence; uint32_t text_length; /* source bytes, not including copied NUL */ cui_bridge_notification_value_v1 payload; cui_bridge_event_ex legacy; /* complete old scalar/handle snapshot */ } cui_bridge_notification_v1; CUI_BRIDGE_API uint32_t cui_bridge_notification_v1_size(void); CUI_BRIDGE_API uint32_t cui_bridge_notification_versions(void); /* bit0: V1 */ CUI_BRIDGE_API cui_bridge_status cui_bridge_poll_notification_v1( cui_bridge_app *, uint32_t struct_size, cui_bridge_notification_v1 *out, char *text, uint32_t capacity, uint32_t *required_capacity); ``` Caller passes exact `struct_size`; mismatch/null arguments return existing `INVALID_ARGUMENT` before consuming anything or changing outputs. The successful output contains size/version for defensive FFI checks. Empty union members are zeroed; consumers read only the payload selected by `payload_kind`. Size query includes platform ABI padding; do not manually pack structs. Each language FFI checks its native layout against the query before first use. Capability discovery is optional-symbol lookup: old libraries lacking these symbols keep working for old APIs, while explicit V1 registration/poll reports unsupported cleanly rather than silently decoding V1 from legacy values. V1 uses bridge handles, not Core `cui_id`: they are different identity domains. It deliberately exposes **no event index, pointer/device/key source or activation snapshot** in this first bridge slice. Its only metadata presence bit is `HAS_FRAME`, set when the captured frame sequence is nonzero. Programmatic operations outside a frame leave it clear; do not invent a frame or source. A later evidence transport needs its own versioned layout and enqueue-time capture. The shared native metadata helper does not recover evidence already discarded by the bridge. `legacy` preserves every existing numeric/raw selected field. The same returned UTF-8 text serves both typed and legacy views. No getter or JSON reparsing reconstructs the new payload at poll time: private queued records capture typed fields and node kind at the original enqueue point, alongside the old snapshot. Array slots remain bounded by existing `max_events` (default256/max4096); typed payloads add fixed per-slot storage, not another queue or hidden event fanout. Initial supported mapping is intentionally narrow: | Existing event source | V1 kind/payload | Boundary | | --- | --- | --- | | Any existing CLICK enqueue | ACTIVATE/NONE | Preserve each existing enqueue, including simple click adapters lacking input evidence. | | Checkbox/Switch/Toggle committed CHANGE | CHANGE/BOOLEAN | Already-applied bridge-owned bool, not a request or tri-state. | | Scalar numeric control CHANGE | CHANGE/SCALAR | Only explicitly audited numeric producers, not every overloaded `value` field. | | Input/Textarea/Editor/OTP text CHANGE | CHANGE/TEXT | Owned UTF-8 snapshot; does not add submit/completion channels. | | Single selected-item CHANGE | CHANGE/SELECTION | Full captured handle, which may be stale by delivery. Multi-selection remains legacy until a bounded typed representation is designed. | | DataTable selection/sort | CHANGE/TABLE | Capture all five fields directly where JSON is currently constructed; preserve sentinel values and raw legacy/JSON unchanged. | | Existing surface CLOSE | LIFECYCLE/SURFACE | Existing close result, not an application veto. | | Every other existing notification | Existing channel/LEGACY | Preserve generic fields/text. Date/time/color/questionnaire/speech/dock/scroll and other overloaded producers are not guessed into scalar/text semantics. | Exact numeric/selection producer allowlists and their fixture names must be committed before enabling those mappings. Unsupported variants still deliver lossless LEGACY payloads. No notification is synthesized where none previously existed, and setters retain their individual event/no-event behavior. ## Polling, copying and failure V1 and both old poll functions drain the **same** queue. Mixing them consumes whichever event is next; this is not broadcast or independent cursors. `poll_event` retains its existing skip/filter behavior. Typed polling skips stale origin handles just as `poll_event_ex` does; it does not drop a valid origin solely because the selected handle is stale. Success copies complete text including NUL, publishes the fixed output and dequeues once. `CAPACITY` sets only required capacity and leaves destination/fixed output and the live event unchanged; stale-origin cleanup may already have occurred. Allocation/copy failure must never deliver a misleading partial typed payload. Existing enqueue failures can follow component mutation; step is not transactional and no rollback claim is added. Preserve existing producer limits (common text payloads fit4096 bytes). Do not impose a new4096 truncation in polling merely because wrappers historically used4097. A V1 wrapper starts with4097 and retries the same event only after `CAPACITY`, using the returned required size and a documented new-view safety ceiling proposed as **1MiB including NUL**. This is an explicit wrapper allocation policy, not a claim about all existing producer limits. Greater required sizes raise a typed payload-limit error without consuming that event; users can drain it through a capable C consumer or close the app. Reject zero/overflowing required size and a second inconsistent capacity response rather than spinning. Queue count, transient wrapper allocation and text bytes must be reported separately. C text belongs to caller storage after polling. Python/JS/Go/Rust publish owning strings and scalar/handle copies; callbacks receive owned immutable/read-only records or callback-borrowed references to them. Deferred consumers retain/copy the language object as appropriate; no queued C text pointer crosses FFI. Node references are optional convenience resolution and never replace the captured handle. ## Exact language entry points proposed Use a discriminated owning `NotificationV1` in each language with variants `Activation`, `BooleanChange`, `ScalarChange`, `TextChange`, `SelectionChange`, `TableChange`, `SurfaceClose`, `Legacy`. Every variant includes captured origin handle, optional live node, exact frame plus presence, and complete `legacy` fields/text. TableChange exposes integer `row`, `column`, `sort_column`, `sort_direction`, `reason`; selection exposes the raw selected handle plus optional validated live node. ```python # Frozen dataclass union; Python ints preserve uint32/uint64, text is str. NotificationV1 = Activation | BooleanChange | ScalarChange | TextChange | SelectionChange | TableChange | SurfaceClose | LegacyNotification App.poll_notifications_v1(self) -> Iterator[NotificationV1] Widget.on_notification_v1(self, callback: Callable[[NotificationV1], None] | None) -> Widget ``` ```ts // JS runtime implements the same names; uint32 fields use exact Number. type NotificationV1 = ActivationV1 | BooleanChangeV1 | ScalarChangeV1 | TextChangeV1 | SelectionChangeV1 | TableChangeV1 | SurfaceCloseV1 | LegacyV1; interface NotificationBaseV1 { readonly schemaVersion: 1; readonly kind: string; readonly handle: Readonly<{slot: number; generation: number}>; readonly node?: Node; readonly hasFrame: boolean; readonly frame: bigint; readonly legacy: Readonly; } interface TableChangeV1 extends NotificationBaseV1 { readonly kind: 'table-change'; readonly reason: 'selection' | 'sort'; readonly row: number; readonly column: number; readonly sortColumn: number; readonly sortDirection: number; } // Other union members declare only their typed bool/number/text/handle/result. App.prototype.poll_notification_v1(): NotificationV1 | undefined; Node.prototype.on_notification_v1(callback: ((e: NotificationV1) => void) | null): this; ``` ```go // Tagged owning value; typed payload structs, uint64 Frame, uint32 table fields. type NotificationV1 struct { Kind NotificationKindV1; Handle Handle; Node *Node; Frame uint64; HasFrame bool Legacy LegacySnapshotV1 Boolean *BooleanChangeV1; Scalar *ScalarChangeV1; Text *TextChangeV1 Selection *SelectionChangeV1; Table *TableChangeV1; Surface *SurfaceCloseV1 } func (a *App) PollNotificationV1() (NotificationV1, bool, error) func (n *Node) OnNotificationV1(callback func(NotificationV1)) *Node // Exactly the Kind-selected field is nonnil; constructors are wrapper-owned. ``` ```rust // Owned enum with common MetadataV1 { handle, node: Option, frame: u64, // has_frame: bool, legacy: LegacySnapshotV1 }; strings are owned String. pub enum NotificationV1 { Activation(MetadataV1), BooleanChange(MetadataV1, bool), ScalarChange(MetadataV1, f64), TextChange(MetadataV1, String), SelectionChange(MetadataV1, RawHandle), TableChange(MetadataV1, TableChangeV1), SurfaceClose(MetadataV1, SurfaceResult), Legacy(MetadataV1), } pub fn poll_notification_v1(&mut self) -> Result>; pub fn on_notification_v1(&mut self, node: Node, callback: F) -> Result<()> where F: FnMut(&NotificationV1) + 'static; pub fn clear_notification_v1(&mut self, node: Node) -> Result<()>; ``` These are new methods; do not change existing Event/ChangeEvent fields or callback signatures. JS BigInt cannot be JSON.stringify'd directly: document a caller-selected decimal-string serializer for the new view, never silently coerce it to Number. TS fixtures target an explicit BigInt-capable library/runtime. Python requires no arbitrary-integer shim. Go/Rust retain native uint64. ## Dispatch, handlers and compatibility Old manual poll methods remain unchanged and consume without callback dispatch. New manual poll does likewise. Registering a new notification handler enables typed draining for normal dispatch, but not a second queue: one native V1 dequeue produces the existing legacy language object plus the typed object. Invoke a currently registered legacy channel callback first, then the new notification callback for that event, then advance to the next event. If no new handlers exist, preserve the old drain path. Typed registrations on an old library fail immediately before consuming anything. This preserves existing Python/Go step-versus-dispatch separation, JS step auto-dispatch and Rust step/dispatch/frame distinction. Run remains after successful frame/render. Existing dispatch return counts retain each language's current legacy meaning; do not add typed listener invocations into them or claim they are portable event counts. If a future caller needs typed-delivery counts, add a separately named result later. One retained new callable per node; registering replaces it, passing None/null/nil or Rust clear removes it. Snapshot the chosen callable before invoking it. Legacy callback may alter the new registration: lookup the new handler **after** the legacy callback, so replacement/removal applies to the same event, matching ordinary sequential application mutation rather than invoking a freed closure. A legacy exception stops before the new callback; the consumed event is not replayed. A new callback exception likewise stops dispatch after consumption. Promises/coroutines are not awaited; callback returns cannot reject already-applied state. After each callback, revalidate app-open and origin handle before invoking another callback. A legacy removal/close suppresses typed delivery for that event; do not resolve a replaced slot to a new node. During native run retain its existing deferred-close/rethrow contract. Standalone dispatch close retains each wrapper's supported behavior; raw C destruction is never called twice. New-handler closures are retained language objects until replacement, explicit clear, removal or app teardown. Implementation must clear new registrations for the entire removed subtree; do not copy Rust's existing descendant-retention omission into the new map. Do not silently change legacy handler ownership in the same commit. External references to removed Node objects may still retain their *legacy* handlers per existing behavior. App identity/generation checks precede registration. Active callback local ownership keeps the current callable alive through return even if it unregisters itself. Manual recursive dispatch/step semantics currently differ. Do not change legacy calls to add a global guard in this slice. New typed-only APIs reject nested typed polling/draining during their own dispatch with the language's existing invalid-state error; this is a local adapter guard, not proof every legacy nesting path is safe. The exact mixed legacy-dispatch nesting behavior needs explicit compatibility tests before enabling typed handlers there. If preserving it cannot be demonstrated, split automatic fanout integration for review; ship manual V1 polling first rather than retiming callbacks or weakening ownership rules. ## Independently reviewable implementation slices and proof 1. **C V1 queue snapshot/poll only:** ABI size/offset probe for unchanged old structs; exact new-size negotiation; unknown/malformed arguments; old/new poll interleaving, stale origin/selected handles, CAPACITY retry/no partial outputs, FIFO snapshots across later value mutations, queue/allocation failure without false rollback. DataTable columns0/1/2/large index and sort transitions prove no bool loss. Table typed snapshots match old JSON at enqueue time without parsing it at delivery. 2. **One wrapper at a time, manual typed poll:** each existing legacy test remains unchanged. Offline native/test-double payloads exercise uint64 frames at `2^53-1`, `2^53`, `2^53+1`, `UINT64_MAX`, full handles/generations, empty/multibyte/4096-byte text, capacity retry/limit/malformed-required failures and retained snapshots after later frames/removal. Node must assert `typeof frame === 'bigint'` and exact value; no loop running billions of frames. C test doubles/injected conversion fixtures provide the edge values without production test hooks. 3. **Retained typed registration/fanout per wrapper:** legacy-first order, replacement/clear/self-clear, subtree removal, app close, exception/panic, missing handlers and independent legacy counts. Preserve programmatic event/no-event behavior and run/manual-step differences. Explicitly test mixed legacy/new nested calls and stop for architectural review if current behavior cannot remain safe. 4. **Typed producer expansions later:** date/time/color, multi-selection, questionnaire/speech/dock and optional Button input evidence require separate bounded schema/capture tests. Do not advertise them from generic JSON or latest getters. No synchronous requests in this plan. 5. **Docs/export proof:** update human and LLM guides, wrapper declarations, native symbol/version capability checks, distribution/SDK generator manifests and consumer examples together. Native tests use the invisible wrapper; browser tests run headless. Freeze dependencies, no desktop sessions or network required. A manual V1 poll and two concrete lossless conversions are useful before all wrappers or payload families are complete. Track those omissions explicitly; notification typing does not grant source-controlled rejection, uniform callback counts, cross-language reentrancy or full family parity. --- ## Bridge scalar, text and selection notification checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/BRIDGE_VALUE_NOTIFICATIONS_SLICE.md # Bridge scalar, text and selection notification checkpoint Status: **C opt-in poll, four-producer SCALAR, four-producer plain TEXT and five-producer SELECTION slices implemented in this branch**; see [the scalar guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_VALUE_NOTIFICATIONS.md). Python owning value polling is implemented in this branch; see [the Python guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_VALUE_NOTIFICATIONS_PYTHON.md). JS/TypeScript owning value polling is implemented in this branch; see [the JS guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_VALUE_NOTIFICATIONS_JS.md). Go owning value polling is implemented; see [the Go guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_VALUE_NOTIFICATIONS_GO.md). Rust owning value polling is implemented; see [the Rust guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_VALUE_NOTIFICATIONS_RUST.md). Original read-only audit: `7bb03cd8`; the implementation preserves ABI/layout, generated SDKs and timing. This extends [the shipped V1 guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_NOTIFICATIONS.md) and [original bridge checkpoint](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/BRIDGE_TYPED_EVENTS_SLICE.md). All new names below require review. Preserve the 78-family manifest and queued notification boundary; this is not foreign synchronous veto, a new queue or direct-C event-facade forwarding. ## Blocking compatibility decision: reserved is not automatically deployable [The C header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_bridge.h) freezes `cui_bridge_notification_v1`, its union, exact-size query and optional symbols. Tags SCALAR=2, TEXT=3 and SELECTION=4 already have space; TEXT uses the existing separate UTF-8 buffer, SCALAR the reserved double and SELECTION the reserved slot/generation handle. Existing flags only express frame presence. No struct, ABI-version, old event layout, existing flag or union size change is needed. However, current [Go `PollNotificationV1`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/go/cui/native.go) and [Rust `decode_notification_v1`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/rust/src/lib.rs) reject reserved/unknown tags **after the C poll has consumed the record**. Python's [decoder](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/python/cui_bridge/__init__.py) and [JS view](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/node/index.cjs) instead fall back to Legacy; they do not expose those typed values. A capability bit alone cannot protect an old consumer calling the old poll. Do not start emitting reserved tags from `cui_bridge_poll_notification_v1` unconditionally. Recommended additive opt-in, retaining the existing schema: ```c /* Bit positions are payload tags, not node kinds. Only 2, 3, 4 accepted. */ #define CUI_BRIDGE_VALUE_SCALAR_V1 (1u << CUI_BRIDGE_PAYLOAD_SCALAR) #define CUI_BRIDGE_VALUE_TEXT_V1 (1u << CUI_BRIDGE_PAYLOAD_TEXT) #define CUI_BRIDGE_VALUE_SELECTION_V1 (1u << CUI_BRIDGE_PAYLOAD_SELECTION) CUI_BRIDGE_API uint32_t cui_bridge_notification_value_payloads_v1(void); CUI_BRIDGE_API cui_bridge_status cui_bridge_poll_value_notification_v1( cui_bridge_app *, uint32_t struct_size, uint32_t enabled_payloads, cui_bridge_notification_v1 *out, char *text, uint32_t capacity, uint32_t *required_capacity); ``` The query advertises implemented value categories; callers request only categories their decoder understands. Unsupported/reserved mask bits fail INVALID_ARGUMENT before queue cleanup/consumption, with outputs intact. Mask zero returns the existing initial-allowlist view. The old V1 poll permanently retains its initial typed allowlist: a newly captured value tag is returned there as LEGACY with the unchanged complete legacy fields/text. The new poll also downgrades unrequested value tags to LEGACY. This is selecting an already-captured view, not reconstructing a value at poll time. Existing CLICK/BOOLEAN/TABLE/SURFACE behavior is unchanged in both polls. Both drain the same queue as all legacy polls. Keep `notification_versions()` bit0 and the size contract unchanged. Optional new symbols plus the category query negotiate value support; do not overload schema-version or frame flags. A new layout or richer security/selection metadata would need its own reviewed version. An alternative is V2 with all wrapper upgrades; simply changing old V1's default producer tags is incompatible with shipped Go/Rust decoders. ## Actual producer and model evidence All rows refer to [`src/bridge/cui_bridge.c`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/bridge/cui_bridge.c). `bridge_change` owns enqueue-time copies; `bridge_render_node`, `bridge_render_group` and specialized render functions determine when it runs. There are only legacy CLICK, CHANGE and CLOSE event names; wrappers' `on_change` is not direct C's typed CHANGE/COMMIT/SUBMIT contract. | Producer / source seam | Actual stored snapshot and timing | Proposed treatment | | --- | --- | --- | | Slider / `bridge_render_node` | Component uses local float, writes node double, then one `bridge_change` for aggregate changed. | Initial SCALAR allowlist. Copy `node->value` directly, preserving the float-to-double result; not full double-precision slider interaction. | | NumberInput / same | `cui_number_input` mutates node double; enqueue only `result.changed`. Internal edit model exists but is explicitly excluded from text snapshots. | Initial SCALAR allowlist; do not treat numeric draft text or invalid drafts as TEXT. | | Rating / same | Local float promoted to node double, aggregate changed. | Initial SCALAR allowlist with the same precision caveat. | | Pagination / same | `size_t page` written to node double; setter validates integral page in configured total. | Initial SCALAR allowlist, documenting discrete page semantics; no invented integer subtype. | | Input, Textarea, Editor / same | Legacy component aggregate `.changed`, followed by enqueue; edit bytes copied by `bridge_change`. Editor uses its bound edit storage. | Initial plain TEXT allowlist. No submit notification, before/after offsets or per-edit multiplicity is available at this seam. | | InputGroup / `bridge_render_input_group` | Input changed enqueues parent text; addon activations independently enqueue CLICK on the child. | Initial plain TEXT allowlist; retain input-before-addon enqueue order and unchanged addon click view. | | RadioGroup, Tabs, Select / `bridge_render_group` | Existing legacy aggregate returns; final Core item ID mapped back to a direct child slot in `node->value`, then one enqueue. | Initial SELECTION allowlist. Capture the validated full selected handle at enqueue, not a Core ID or reconstructed current selection. | | List / same | One aggregate activation can occur even when selected ID repeats. Final mapped slot survives. | Initial SELECTION snapshot only; explicitly retain the existing CHANGE event name and repeat notifications, not per-command/per-transition claims. | | Stepper / same | Current step mapped to direct child slot after aggregate change. | Initial SELECTION allowlist, with step identity distinct from numeric page/index. | | Combobox / same | Query aggregate enqueues before selected-slot mapping; selection aggregate may enqueue again after mapping. Both records currently contain query text and a selected handle. | Defer: a node-kind-only tag switch cannot truthfully distinguish query versus selection reasons. A later private reason discriminator at these exact enqueue calls can classify without changing order/count; no JSON parsing or query inference from selection changes. | | Menu and DropdownButton / same | Aggregate menu command maps last leaf to child slot; Dropdown primary action separately enqueues CLICK. | Remain LEGACY CHANGE. A handle-shaped value does not turn a command into selection; direct C's new per-command facades are not used here. Separate command notification design required. | | Tree, Carousel, Command, Sidebar, Dock, Settings | Specialized reducers and/or callbacks use differing child/index/reason models; `bridge_change` opportunistically captures a direct child handle. | Remain LEGACY pending individual producer audits. Do not classify every nonzero `value` as selection. | | TextView | Selection anchor/cursor changes enqueue selected text, not edit-model change. | Remain LEGACY; TEXT-change naming would conceal a different event meaning. | | OTP, Speech | OTP `.changed` copies value; speech provider callback copies transcript plus status/event type. | Remain LEGACY pending security/event-specific review; no new sensitive-text promise. | | TimeField, ColorPicker, Calendar, DatePicker | Formatted strings plus time/color/date encodings; dates use YYYYMMDD numeric encoding, color uses packed color. | Remain LEGACY; neither generic scalar nor edit text conveys their actual model contracts. | | Questionnaire, resizable items, disclosure/hover and other `bridge_change` sites | JSON or mixed checked/value/status snapshots. | Remain LEGACY; no blanket generic-value allowlist. | | Progress and Attachment progress | Model setters exist, but rendering does not enqueue a progress CHANGE. | Do not create events to populate a typed category. | Selection capture already validates slot <= max_nodes, live generation and direct parent equality in `bridge_change`. The bridge limit is1024 nodes; slot and generation remain **uint32**, never a Core uint64 `cui_id`. Selection has no previous item, reason, input index or copied activation. The initial allowlist must treat node value0 as explicit empty handle `{0,0}`; a nonzero value that fails the existing child validation stays LEGACY rather than being mislabeled an intentional clear. Do not resolve historical selected handles to a replacement slot generation. `bridge_change` copies `checked`, double `value`, optional selected handle and text before advancing queue count. Typed capture must occur alongside that same snapshot and preserve allocation-failure and queue-full behavior. No observer adoption, callback retiming, per-event replay, getter reconstruction or sorting by input index belongs in this slice. ## Numeric, text and security boundaries [Numeric setters](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/bridge/cui_bridge.c) reject nonfinite values. `set_range` restricts Slider bounds/step to float-compatible magnitude (±16777216); NumberInput retains double storage. Capture the **actual committed value**, including its precision, without decimal JSON round trips, integer truncation or JS BigInt conversion. All language scalar views use IEEE binary64 (`float`, `number`, `float64`, `f64` respectively). Exact uint64 frame sequence remains Python int / JS bigint / Go uint64 / Rust u64, independently of scalar values. Do not use scalar double to transport arbitrary integer IDs. Current bridge Input options expose disabled state, not password/masked/content-purpose configuration; searching the canonical bridge header/implementation finds no secure-text option. `bridge_change` unconditionally copies the underlying edit bytes. In contrast, [direct C Input events](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_text_input_events.h) redact text when masked/password purpose is set. The bridge does not consume that facade and does **not inherit its redaction**. Initial TEXT support is explicitly plain Input/Textarea/Editor/InputGroup only; no claim of secure input support. Future secure configuration must fail closed for notification text in legacy and typed views, including `legacy.text`; redacting only the typed field would still leak. Adding redacted-versus-empty metadata cannot silently repurpose V1 flags (existing Go/Rust validate them); review a versioned extension first. Do not implement password support by later getter checks that miss already-queued secret copies. Plain edit buffers are4097 bytes including NUL, NumberInput128; OTP separately allocates4097. TextView has4097 source and8192 rendered capacity, speech has separate transcript storage. These are producer limits, not a universal V1 text cap. Preserve UTF-8 byte lengths, empty strings, owned snapshots and NUL-inclusive capacity arithmetic. Before enabling any additional producer, prove its length fits uint32 and `length+1` without overflow at enqueue and poll; never narrow unchecked `size_t`. Poll remains allocation-free, truncates nothing and parses no JSON. Existing wrappers start at4097 and retry once up to1MiB including NUL. Preserve this explicit policy, error propagation and no live-record consumption on C CAPACITY; wrapper decode errors after successful C consumption are not retryable. Queue-full failure can follow applied mutation and leaves prior records; no rollback claim. Preceding stale origin cleanup can occur before CAPACITY, as today. Typed storage uses existing fixed per-slot union plus existing text allocation, not another queue or new per-event typed allocations. Result copies own no live nodes. ## Language surface and compatibility matrix Keep existing manual polls and legacy dispatch unchanged, including their initial allowlist and current timing. Add explicit opt-in methods below, using the new optional C symbols, exact-size query and requested category mask. Do not auto-select them from `step`, `run` or `dispatch`. | Consumer | Shipped current V1 / reserved-tag behavior | Proposed new owning manual API | | --- | --- | --- | | C | Initial allowlist; raw fixed union and caller text storage. | New value-poll symbol above; SCALAR=`payload.scalar_value`, TEXT=separate complete UTF-8 copy, SELECTION=`payload.selected`. All remain CHANGE. | | Python | Frozen dataclasses; reserved/unknown tags fall back to Legacy. Optional symbols support older libraries. | `App.poll_value_notifications_v1() -> Iterator[ValueNotificationV1]`; union of existing classes plus frozen `ScalarChangeNotificationV1(value: float)`, `TextChangeNotificationV1(text: str)`, `SelectionChangeNotificationV1(selected_handle: tuple[int,int], selected_node: Node | None)`. | | Node JS / TS | Frozen records; reserved/unknown fall back to legacy. Addon preserves exact bigint frames; canonical declarations in `bindings/typescript/index.d.ts`, Node `.d.cts` re-exports. | `App.poll_value_notification_v1(): ValueNotificationV1 | undefined`; new union extends existing `NotificationV1` with `scalar-change/value:number`, `text-change/text:string`, `selection-change/selectedHandle:NotificationHandleV1,selectedNode?:Node`. Keep existing union/API unchanged. Addon must read the typed union double/handle, not legacy getter state. | | Go | Owning `NotificationV1`; reserved/unknown tags error after consumption. Dynamic optional-symbol path and bundled SDK builds both exist. | `App.PollValueNotificationV1() (ValueNotificationV1, bool, error)`; new type wraps existing notification or typed scalar/text/selection variant with float64/string/full Handle. Do not silently add incompatible cases to callers' established contract. | | Rust | Owning enum; reserved/unknown tags produce protocol error after consumption. New enum variants could also break downstream exhaustive matches. | `App::poll_value_notification_v1(&mut self) -> Result>`; **new enum** `Existing(NotificationV1)`, `ScalarChange(MetadataV1,f64)`, `TextChange(MetadataV1,String)`, `SelectionChange(MetadataV1,RawHandle)`. Do not modify the exhaustive old enum for this slice. | These are proposed signatures; compile-ready naming/type details should follow each wrapper's existing conventions during its review. Shared metadata and complete legacy snapshots remain available in every variant. Text ownership is independent of source removal/app destruction. Optional selected-node wrappers are conveniences resolved by exact slot+generation where supported, not owning nodes; retain the handle if stale. Rust can retain its raw-handle convention rather than invent a resolvable live node. Older libraries: new optional symbols absent => explicit unavailable error without draining through an old API; legacy functions continue to work. Libraries with only part of the reviewed allowlist advertise category support accordingly; new wrappers request only compiled-known advertised bits. Unknown future mask bits are never automatically enabled. Unknown payload/kind combinations from a malformed provider are protocol errors; do not coerce them to a valid scalar/selection. Old methods on a newer library receive downgraded LEGACY value records and continue working. This compatibility policy needs real tests, not a version comment. Canonical wrappers and [Go/Rust SDK generation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/scripts/generate_go_sdk.py) must land in separately reviewable commits. Bundled C headers/sources/provenance and exports must match; dynamic wrappers must prove old-library availability separately. No hand edits to generated SDK copies. Current guide's statement that Go/Rust availability is independent is not evidence they are missing: [Go implementation/tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/go/cui/notifications_v1_test.go) and [Rust implementation/tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/rust/tests/notifications_v1.rs) already ship initial manual views. Update human/LLM documentation and generated skill/index resources through integrator-owned workflows after API review. ## Independently reviewable implementation and proof 1. **C opt-in plus SCALAR**: old-symbol downgrade, capability/mask validation, explicit four-kind producer allowlist. Own canonical bridge header/implementation/private payload only as needed, new value-notification fixture and guide. Existing V1 ABI bytes/size and legacy APIs remain fixed. Prove NumberInput double values beyond float precision, Slider/Rating exact promoted float, Pagination integer page; no events from setters/render-only progress. Invalid mask/size leaves queue/output untouched; old/new/legacy interleaving remains one FIFO. 2. **C plain TEXT**: explicit four-kind allowlist at existing enqueue points, no added submit events. Prove non-ASCII UTF-8, empty versus nonempty,4096-byte boundary, delayed copies versus subsequent edit, originating removal/app destruction, exact capacity/no partial outputs, queue-full and allocation failure without false rollback. Assert unchanged event counts for multiple edits within one frame. Document unsupported secure configuration; a synthetic secure-model future guard test is not evidence of a shipped secure bridge API. 3. **C SELECTION**: explicit RadioGroup/Tabs/Select/List/Stepper allowlist. Prove selected slot+generation, clear0, stale selected removal/reuse, final-state aggregation including a return to the initial value where legacy emits nothing, List same-item repeat, disabled/inert behavior. Menu/Dropdown, Combobox query+selection, Command and JSON producers remain LEGACY. Test invalid nonzero child identity stays LEGACY, without fabricating a clear. 4. **Owning wrapper updates**, Python, Node/TS and Go/Rust independently reviewed against those C capabilities. Real queue tests must cover all enabled categories, shared old/new drain, lifetime copies and selected-generation behavior. TS strict narrowing includes the new union while old union source fixtures remain valid; Rust compile fixture preserves old exhaustive matching. Regenerate SDKs only through integrator workflow after canonical source/exports are wired. 5. **Protocol/compatibility matrix**: reuse/extend the separately owned [test-only native provider](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/tests/notification_v1_fixture.c) in a reviewed test commit, not producer code. Deterministic records cover uint64 frames `2^53-1`, `2^53`, `2^53+1`, UINT64_MAX; full uint32 handle extremes; binary64 values not exactly representable in float; reserved/unknown tags/kinds; absent optional symbols; wrong native size; capability masks; empty/large text; capacity0/non-increasing/repeated/>1MiB responses. Distinguish these conversion/protocol records from real input and real enqueue tests. Old Rust/Go wrappers against new C must successfully consume newly classified producers through the old symbol as LEGACY. Existing evidence to retain: [C V1 tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_bridge_notifications.c), [Python real/protocol tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/python/test_notifications_v1.py), [Node real queue tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/node/test/notifications-v1.test.cjs), [Node provider tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/node/test/notifications-v1-protocol.test.cjs), [TypeScript fixture](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/node/test/notifications-v1.types.ts), and Go/Rust tests linked above. They establish the initial allowlist, not the proposed value expansion. Native validation uses strict C11/C++ header checks and `python scripts/test_local.py --build-dir build` only; browser checks stay headless. No tests or production changes are authorized by this checkpoint alone. --- ## Bridge hidden-window contract checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/BRIDGE_WINDOW_VISIBILITY.md # Bridge hidden-window contract checkpoint Keep existing cui_bridge_options layout, ABI version, constructor and visible creation defaults. Add cui_bridge_window_options containing uint32_t struct_size, version (1), initially_hidden (0/1), a size query, and a separate cui_bridge_create_with_window_options(base, window, status). NULL window options mean visible defaults. Validate the independent record before allocating. Headless hidden=1 returns BACKEND_UNAVAILABLE; zero/default headless is unchanged. SDL receives the hidden flag in its constructor, before any frame. Add set_window_visible(app, uint32_t) and get_window_visible(app, uint32_t*). Invalid output pointers/flags fail, and errors preserve query outputs. Existing bridge_ready rules apply: NULL invalid, closed CLOSED, active stepping invalid. Use only the owning native UI thread. After-frame run dispatch may change/query visibility because Core stepping has ended. No window is shown by run or step. Rendering-only Sokol/SDL_GPU hosts remain caller-owned and outside this bridge. Python initially_hidden, JS/TS initiallyHidden, Go InitiallyHidden, and Rust WindowOptions/new sdl_with_window_options retain existing visible defaults. Expose set_window_visible/window_visible (Go SetWindowVisible/WindowVisible). Python/Go resolve new symbols optionally so default apps still load older ABI1 libraries; feature requests return unavailable without a show-then-hide fallback. Native proof checks actual SDL hidden flags before and after the first frame, explicit visibility transitions, lifecycle guards and all five language runtimes, including separately compiled and executed TypeScript, only under private Xvfb. Validation completed on Linux X11/private Xvfb: portable bridge argument/lifecycle checks, native C actual-SDL before/after-first-frame checks, and Python native callback test passed (3/3). Focused authoring runner passed all five runtimes plus Python/Go missing-export compatibility tests (7/7). The shared Linux test-only interposer checks constructor flags, actual SDL flags and independent X11 server map state at creation and first presentation. Explicit visibility controls run inside application handlers dispatched after the completed Core frame in the native callback; Rust uses run_with and C uses after_frame directly. Closed queries preserve C outputs/reject in builders. TypeScript 5.8.3 was compiled and executed. No dependencies downloaded; one existing focused bridge build, nice19, single CPU, Go -p1/GOMAXPROCS1 and Cargo -j1. Sokol/SDL_GPU caller-owned windows, Wayland/Windows/macOS runtime, physical GPU and published packages remain outside this proof. Missing-export fixtures model old ABI1 dynamic symbol surfaces; they are not historical release binaries. --- ## Button state-style refinement audit Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/BUTTON_STATE_REFINEMENT_AUDIT.md # Button state-style refinement audit Design checkpoint, 2026-10-20. **Proposal, not implementation or parity promotion.** CUI baseline: `ebcf5211`. Frozen upstream kit 0.7.1: `87d10ae5e1299d1be18670a37570c5402f952e34`, verified against `/tmp/cui-upstream-reference`; see [baseline](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/upstream-baseline.md). Only this document changes. The manifest's “complete source state-style refinement” row remains `not_started`; this does not mean hover and click painting are absent. All 78 component entries remain untouched. ## Source authority All upstream links below pin the frozen commit, not moving main: - [Component Button](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/crates/component/src/button/button.rs): custom variant fields 40–47, compound hover helpers 355–368, eligibility 505–521, render 600–880, palette resolution 900–1376. - [Base Button](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/crates/base/src/button.rs): semantic style API 59–78, resolution 141–150, selected/disabled tests 447–497. - [Shared state resolver](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/crates/base/src/state_style.rs): instance, active value states, disabled ordering; refinements only replace supplied fields. - [Focus painting](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/crates/component/src/styled.rs): `FocusLine` and `focus_style`, 235–296, plus outer-band `focus_ring` immediately following. CUI authority: `include/cui/cui_components.h:98–165`, `include/cui/cui_theme.h:73–77`, `src/components/cui_components.c` (`cui_button_paint_state`, `cui_button_paint`, metadata and submit helpers), and `src/theme/cui_theme.c:54–82`. Line references describe this checkpoint. ## Frozen contract and present coverage | State or layer | Frozen behavior | Current CUI / remaining work | | --- | --- | --- | | Normal, hover, active | Per-variant background, border, foreground; hover/active only while interactive and neither selected nor open | Existing palette has normal/hover/active backgrounds and outline equivalents. Pointer hover and pressed paint already work. Foreground and border cannot be independently supplied per state. | | Selected / open | `selected || open`; chosen selected style suppresses pointer hover/active refinements | Both flags already select active presentation. Most variants agree structurally; Ghost still uses hover-dependent foreground and its selected fill must be checked separately against source `secondary_active`. | | Disabled | Last semantic layer; no shadow; variant-specific background/border alpha, muted foreground at 0.5 | Inertness and foreground exist. Filled border uses blanket 0.5 instead of source primary/danger/warning/success/info/custom 0.15 and secondary 1.5. Default and outline have separate handling already. | | Loading | Inert, normal colors except selected/open presentation, whole-control opacity 0.8 unless disabled; disabled wins | Existing paint clears hover/pressed for loading and uses whole-box opacity 0.8. Preserve this, including selected/open combinations; do not conflate loading and disabled colors. | | Ghost hover | Accent background, half alpha in dark mode; accent foreground. Active uses button-active fill and normal Ghost foreground | CUI uses full accent in either mode and hover foreground even when pressed/selected. Explicit state precedence needs correction. | | Link / Text | Transparent; Link normal/hover/active foreground, always underlined; Text foreground alpha 0.9/1/0.7 | Existing special cases implement these basic transitions; custom palette bypass has only one foreground. Keep real link role and underline behavior. | | Focus | Existing border tinted ring; borderless Ghost edge line, Link/Text outside line, filled inside foreground line at alpha 0.6. Theme outer ring optionally adds band | CUI uniformly replaces border with focus color and width 2. Visibility/hide switch exists, geometry and theme ring mode do not match. | | Instance refinement | Component clones caller root style, applies it after normal defaults, and replays it inside selected and disabled styles | No Button paint/refinement callback. Geometry options and custom palette cover a subset; no general final root/content style layer. | | Semantic refinement | Base exposes selected and disabled builders; shared resolver applies instance → selected → disabled | No corresponding Button public semantic style facade. Base contract differs from Component replay described above; do not blindly copy checkbox ordering and claim both. | | Compound group hover | Internal helper joins named group; idle member gets hover background at 0.5, held flag supports open compound control | No Button option. Helpers are `pub(crate)`, so this is compound integration scope, not a public standalone Button builder requirement. | | Custom shadow | Custom variant requests shadow; theme shadow gate, disabled removes it | No Button shadow field; existing box/draw primitives should be evaluated before proposing any renderer extension. | The foreground/border limitation is independent of default theme fidelity. CUI's theme constructor derives hover/active using RGB scale 0.9/0.75 and outline alpha 0.1/0.2/0.4. Frozen source consumes distinct theme tokens and uses OkLab mixing in several outline/custom paths. Existing palette overrides can supply exact background values, but that is not proof that defaults match all frozen light/dark themes, gradients, or alpha composition. Upstream `Background` supports more than solid CUI `cui_color`; gradient parity remains an explicit separate limitation. Do not silently label RGB scaling as OkLab. The private `content_style` helper (source 301–307) refines the inner content row and icon size for compound controls. It is not a standalone public API. Arbitrary `Styled` modifiers include layout, opacity, typography and other upstream fields; a bounded CUI style facade must name its supported subset instead of claiming an unrestricted upstream style engine. ## Independently reviewable implementation slices 1. **Built-in state correction, no new API.** Resolve normal/hover/pressed, selected/open, disabled and loading explicitly before painting. Fix dark Ghost alpha, Ghost selected/pressed foreground, and disabled border alpha. Audit custom, outlined Ghost/Link/Text too: source selects outline style before selected special cases. Preserve existing aggregate activation bool, callback order, event multiplicity, focus eligibility and explicit toggled semantics. Test all variants across light/dark and outlined/filled; include hover+pressed, hover+selected, open+loading, selected+disabled, recovery and custom alpha. Assert actual software pixels/draw colors and semantic states, not just resolver output. State expectations must cite the source formulas. 2. **Compatible opt-in refinement facade.** Propose a Button-specific portable paint record and callbacks using existing component `user` conventions, borrowing the established checkbox paint-facade pattern where useful. Support root box and foreground first, named instance/selected/disabled layers, then explicit hover/active/focus customization if required. Resolve whether API models Base ordering or Component caller-style replay before coding; document both and test conflicts on the same field. Defaults must retain the reviewed built-in resolver; callbacks may alter paint, never activation reduction. Cover border, foreground, alpha, radius and explicit zero/transparent values; do not use zero as “unset.” Scope geometry changes carefully because layout/hit-test/semantic bounds must agree. Test callback order and single invocation, disabled precedence, loading opacity and bounded content. A separate additive header can avoid concurrent public header ownership, subject to root review. 3. **Focus rendering.** Implement source border/edge/inside/outside decisions and optional outer band with existing Core draw facilities where possible. Specify theme switch and opt-in compatibility before changing defaults. Verify keyboard focus, pointer focus policy, custom edges/corners, clipped ancestors, transparent fills, and no geometry shift at multiple densities. GPU-specific checks remain deferred when unavailable under Xvfb. 4. **Compound hover and custom shadows.** Audit consumers before public API: internal source group-hover is a cross-control presentation input, not evidence for a new global dispatch architecture. Prefer explicit bounded borrowed state or group-composition paint input. Test idle half-hover, actual hovered/pressed child priority, held/open, disabled/loading and lifetime. Shadow addition requires theme gate, disabled suppression and clipping/opacity tests; keep it separate from state callbacks. 5. **Token/color fidelity follow-up.** Compare frozen theme token generation with CUI registry/defaults, including OkLab mixing and non-solid backgrounds. Decide supported portable representation and compatibility policy separately. This audit does not authorize theme-wide changes or claim every preset is pixel-identical. State callback support alone cannot close this limitation. Slices 1–3 are useful standalone Button work. Slices 4–5 have compound/theme ownership implications and need their own approval. Keep shared XS through 9XL sizing and current CUI extensions; do not introduce a second size scale. ## Evidence and validation boundary Inspected existing `tests/unit/test_button_behavior.c`: it exercises interactive hover/click/focus, disabled/loading, selected semantics, variant/size loops and custom normal/hover/active backgrounds (around 268–286). Existing `test_button_passive_lifecycle.c`, `test_button_activation_blocker.c`, `test_button_callback_events.c`, `test_button_click_event.c`, `test_button_click_snapshot.c`, content/label/artwork/numeric tests and their web/integration counterparts provide regression anchors. Their existence is not evidence for the full cross-product above. This docs-only checkpoint did not run native/browser tests or claim new runtime verification. For production slices, strict C11 warnings and affected tests must run through `python scripts/test_local.py --build-dir `; browser probes run headless against actual WASM. Root owns CMake registration, metadata/matrix promotion, generated SDK/distribution and consumer-skill refresh. Reconcile source evidence and remaining limitations feature by feature before changing this row; neither hover support nor a callback API proves full Button parity. --- ## Button paint refinement: source audit and proposed next slice Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/BUTTON_STYLE_COMPLETION.md # Button paint refinement: source audit and proposed next slice Historical design checkpoint, 2026-10-31; audited CUI baseline `b9c2f3d1`. The approved first shadow-aware facade has since been implemented; use [BUTTON_STYLES.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BUTTON_STYLES.md), `include/cui/cui_button_styles.h` and `src/components/cui_components.c` for its actual bounded contract. The remaining background/focus/text/border proposals below are not production APIs. The Button ledger's “complete source state-style refinement” remains pending. Editor stays deprioritized. Original review findings and proposed follow-on seams follow. ## Pinned evidence This audit used the ORIGINAL upstream kit v0.7.1 commit `87d10ae5e1299d1be18670a37570c5402f952e34`, as required by [upstream-baseline.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/upstream-baseline.md), rather than current upstream. Only individual reference files were fetched; no checkout or dependency install. | Source | Relevant evidence | | --- | --- | | [Component Button](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/crates/component/src/button/button.rs) | `Styled` delegates to Base; render captures instance refinement, installs variant pointer defaults, replays instance within selected and disabled; gradient variant tests; custom variant shadow flag | | [Base Button](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/crates/base/src/button.rs), [state resolver](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/crates/base/src/state_style.rs) | Base resolves instance, selected, disabled; this is different from Component's caller-instance replay | | [Component styled helpers](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/crates/component/src/styled.rs) | `focus_style`, `FocusLine`, external ring and inside/edge/outside borderless focus lines | | [Workspace manifest](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/Cargo.toml) | Pins upstream dependency package `upstream-pre` exactly `0.3.8` | | [Dependency style](https://docs.rs/crate/gpui-pre/0.3.8/source/src/style.rs), [color](https://docs.rs/crate/gpui-pre/0.3.8/source/src/color.rs), [Styled](https://docs.rs/crate/gpui-pre/0.3.8/source/src/styled.rs) | Concrete paint fields, shadow/background ordering, fixed two-stop gradient, sRGB/Oklab interpolation choice, text decoration | Reproducible SHA-256 of raw pinned Component Button: `e4423f371ec5e954f0ecb4cd459ee24ef5a158affa6d44dc63e62c5df463d61e`; Base Button: `ff3026d04f12afe3e6aeb3cc3d95b25c5ea6eb65884258fea1b973ad6d08255e`; state resolver: `f7e1f85c0215e3cd84df4b6fbce34938a33d275c9db392bdc9025670454760b1`. The dependency pages above are the pinned published version, not a claim that upstream implementation code is present in CUI. Findings below are independent design analysis; no upstream implementation or documentation is copied wholesale. ## Actual coverage and gaps | Paint concern | Pinned source | CUI baseline / remaining work | | --- | --- | --- | | Background, border color, foreground | Instance and semantic/pointer refinements; normal/hover/active variant palettes | Existing six-mask C facade supports solid RGBA colors; preserves Component replay | | Radius, per-corner radius, opacity | Arbitrary `StyleRefinement`; absolute/rem lengths | Existing facade permits finite nonnegative radii and opacity 0..1; logical-pixel bounded subset, no rem refinement | | Shadows | Owned vector, explicit empty-list reset; DROP before background and INSET after background; border after content | Core already copies up to eight mixed layers. Button facade has no shadow field; post-submission setter does not participate in state refinement | | Default shadow | Custom variant's shadow boolean, gated by theme shadow and not disabled; most variants have no builtin shadow | Do not add a shadow to all Buttons. A shadow-aware facade alone does not complete custom-variant/theme default-shadow policy | | Gradients | `Background` has exactly two stops, angle, sRGB/Oklab choice; real normal/hover/active/outline/disabled gradient tests | Theme/Button palettes and facade are scalar colors. `cui_effect_linear_gradient` is a raster helper, not an element background contract | | Other background paint | Source Background also exposes slash pattern and checkerboard | No matching Button/root refinement API; retain explicit remaining scope | | Border paint | Color, per-edge absolute/rem widths, solid/dashed style | Existing options support per-edge widths; callback widths are inspection-only. No arbitrary border-style refinement | | Focus | Theme-dependent border tint or separate outer ring; borderless inside/edge/outside line | CUI currently changes border color and width to 2, then focused callback. This is a real remaining paint gap, not fixed by adding shadows | | Text paint | Inherited foreground, background, underline/strikethrough thickness/color/wavy; Link builtin underline | CUI facade exposes foreground only. Arbitrary text decoration/background remains pending | | Font/geometry | Source also permits font family/features/fallbacks, size/weight/style, line height, whitespace, clipping, size, margin/padding, flex/grid, visibility, cursor | These affect measurement/layout or framework behavior. They are not covered by a paint-only completion claim | Custom variant color setters in source take HSLA colors; gradient support comes through Background-valued theme tokens or Styled background, not an invented gradient custom-color setter. Source background opacity transforms both gradient stops. Byte RGBA and premultiplied-sRGB raster interpolation are not evidence of full HSLA/Oklab or renderer parity. ## Recommended first production slice: owned shadow refinement Add new records/functions alongside the existing ABI. Reuse existing phase/info, options, scalar presence-bit values and root ownership; do not enlarge any existing public struct. Suggested signatures (names require review): ```c enum { CUI_BUTTON_SURFACE_SHADOWS = 1u << 6 }; typedef struct { unsigned rejected_phases; /* one bit per existing phase, zero on entry */ } cui_button_surface_status; typedef struct { cui_button_style_paint paint; size_t shadow_count; cui_box_shadow shadows[CUI_BOX_SHADOW_MAX]; } cui_button_surface_paint; typedef struct { unsigned fields; /* old six scalar bits plus SHADOWS */ cui_button_surface_paint value; } cui_button_surface_patch; typedef void (*cui_button_surface_fn)(void *user, const cui_button_style_info *info, const cui_button_surface_paint *current, cui_button_surface_patch *out); typedef struct { cui_button_surface_fn instance, hovered, active, selected, disabled, focused; void *user; } cui_button_surface_styles; bool cui_button_surface_ex(cui_context *, cui_id, const cui_theme *, cui_str, cui_button_options, cui_button_surface_styles, cui_button_surface_status *); void cui_button_surface_paint_only(cui_context *, cui_id, const cui_theme *, cui_str, cui_button_options, cui_button_surface_styles, cui_button_surface_status *); ``` `CUI_BOX_SHADOW_MAX` is the existing public eight-layer capacity. The optional status output reports rejected phase patches independently of activation; its pointer is borrowed only through the call and never retained. No gradient placeholders, union with unowned pointers, callback registry, event routing or retained next-widget style. New functions share the existing private submit/painter path; Base runs exactly once for the active function. Existing legacy, styled, event and group routes keep their existing signature and timing. Do not pretend that new facade overloads exist for event/group APIs. A surface calculation starts with the ordinary default paint and an empty shadow list. First slice adds no builtin shadows. Disabled explicitly clears shadows before its callback, then replays the instance patch: an explicit instance list can restore them, matching the source's disabled clear/replay rule. Enabling the source custom-variant/theme shadow default is a separate additive option review. ### Exact proposed phase and reset rules 1. Resolve normal builtin paint; invoke instance once and capture its validated value patch by copy. 2. Only when not disabled/loading/selected/open: choose pressed over hover, apply that builtin color layer, then its callback. No hover callback while pressed. Shadow lists carry through a builtin color-only layer. 3. If selected OR open: apply selected builtin colors, selected callback once, then replay the captured instance patch, without recalling instance. 4. If disabled: apply disabled colors, clear shadows, disabled callback, instance replay. Otherwise loading multiplies resolved root opacity by 0.8. 5. Existing focus-visible and hide-focus-ring gates apply existing focus paint, then focused callback. No new focus event or eligibility rule. This preserves the documented CUI bounded precedence, including loading multiplication; it does not claim all upstream engine hover/active/focus-visible combinations or arbitrary source opacity conflicts have been reproduced. Source Component focus helper uses its own focused-handle/theme gates, whereas CUI's facade uses its existing focus-visible gate; keep this distinction explicit. An absent scalar bit inherits the preceding value; a present zero/transparent value replaces it. CORNERS false restores uniform-radius selection. An absent SHADOWS bit inherits the complete preceding list; present count zero clears DROP and INSET; present nonempty replaces the complete list, never appends or merges by index. Instance replay uses those exact presence bits, including explicit clear. There is no implicit “reset scalar to theme” sentinel: omit its bit or supply the desired value. Each submission recomputes defaults; supplying zero styles next frame removes all facade refinements without retained state. Callbacks are borrowed synchronous pure calculations, as in the existing API. They cannot call CUI, dispatch/consume input, mutate owner/options/styles, submit children or reenter. `current`, `info`, `out`, callback/user references expire at return. Fixed arrays are copied before later callbacks and before content runs; unused array entries are ignored. No borrowed layer, font, image or gradient resource pointer survives a callback. The private painter's copied frame-owned shadow payload follows existing Core draw-list/resource lifetime, never a stack pointer. No allocation/resource is added for absent/empty decoration. Validate a candidate patch into a local copy before publishing any field. Unknown bits, count over eight, invalid kind, nonfinite values, sigma outside [0,256], offsets/spread outside [-4096,4096], opacity outside [0,1] or radius/corner outside [0,16384] discard the whole new-facade patch; preceding paint survives and later eligible callbacks continue. Present radius rules are deliberately bounded for the NEW facade; the old facade's finite-nonnegative contract stays unchanged. Validate the effective shadow corner shape too, including radii supplied through options, before accepting a nonempty list. An unsupported options-derived shape rejects the whole phase patch and sets its `rejected_phases` bit without dropping ordinary Button paint. Every invalid phase patch sets its bit; absent callbacks do not. No Core error is introduced for these authoring errors. Pure invalid callback patches follow the existing non-poisoning policy; genuine Core frame/capacity failures remain real frame errors. CSS factory validation remains explicit: radius [0,512] becomes sigma radius/2, never reinterpret sigma. Apply a valid nonempty list to the actual caller-id root while open, using the existing copied shadow mechanism with final resolved corners. No extra layout node, ID, input target, rectangle cache, previous-frame bound or default-path custom paint. Radius affects decoration only; hit tests stay rectangular. Ancestor masks, inherited opacity, DROP/background/INSET/border ordering and resource ceilings remain [ELEMENT_SHADOWS.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/ELEMENT_SHADOWS.md)'s contract. Do not alter existing renderer ordering in this slice to claim upstream's border- after-content equivalence: overlapping/overflowing child paint needs its own oracle and renderer checkpoint. A later explicit root shadow setter replaces the facade's list; the retained bridge override, applied after owner paint, also wins as documented in [BRIDGE_SHADOWS.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_SHADOWS.md). ### Passive and custom content boundary The passive function inspects the independently registered owner's interaction and paints once: no event reduction, semantics registration or activation/hover callback manufacture. Active callbacks retain current accepted-event order; style calculations still occur in the paint stage after action callbacks. Capture the facade descriptor locally before calling user action/content code. Styles cannot revive disabled/loading activation or change aggregate results. Leading/trailing content, replacement content, children, artwork/loading slots, label ellipsis and caret keep existing precedence and exactly-once submission. The root shadow encloses the final root geometry, including custom children; it does not target anonymous slots or paint them twice. Foreground remains the existing label/artwork ink, not a forced recolor of arbitrary child submissions; caret keeps its builtin normal foreground at 0.75 alpha. Content callbacks run with their current signatures/context and may submit children under existing rules; they are not pure style callbacks. Clipping/content-overflow, intrinsic measurement, layout-only loading work and suppressed lifecycle behavior stay unchanged. No private source `content_style` API is claimed. ## Follow-on renderer checkpoints, before any COMPLETE label 1. **Background paint:** separately review an owned tagged solid/two-stop-linear descriptor, fixed two stops by value, explicit sRGB/Oklab enum, finite angle [0,360], finite stop positions [0,1]. Source permits two stop values; pin reversed/equal-stop behavior against source renderer before choosing reject or normalization. Atomic replacement includes both stops, angle and color space; absent background inherits, transparent solid explicitly clears the gradient. No stale gradient survives a solid replacement or disabled reset. Numeric RGBA representation versus source HSLA conversion needs an explicit precision contract. Reject unknown kinds/spaces transactionally. 2. **Gradient seam:** existing effects angle 0 is left-to-right, 90 top-to-bottom; source 0 points toward top and rotates clockwise. Existing helper spans projected pixel-center bounds and interpolates premultiplied sRGB. Do not relabel it as source parity. Review source projection, degenerate bounds, hard stops, alpha and Oklab before adding a Core root background primitive. Raster fallback must declare cache ownership, invalidation on resize/DPI, per-surface/aggregate pixel and byte ceilings, frame lifetime and allocation failure policy. Suggested ceiling no larger than existing shadow limits (16384 per side, 16M pixels), but total frame budget needs separate approval. No new Core payload/draw command or silent image allocation is approved here. 3. **Remaining paint:** slash/checkerboard parameters, decoration/underline and strikethrough, border style/width effects, theme/custom default shadows and source focus rings need explicit owned descriptors and independent tests. Border-width/font changes require measurement-aware design; never mutate paint widths while hit/semantic/layout geometry still describes old widths. 4. **Framework gaps:** arbitrary Styled layout, font resources/fallbacks, rem resolution, child inheritance/private compound styling, hover-group engine, fluent conditional builders, user upstream handlers and framework focus/event integration remain separate. No capture/bubble or dispatch architecture is introduced. Even paint completion alone cannot establish complete Button source parity, much less all 78 components. ## Required implementation evidence Before changing the shared painter, capture independent pre-change legacy software fixtures with library hash/source provenance. Cover legacy simple, options, existing styled, passive, event and grouped Button routes, including real queued pointer/key/AT requests and multiple accepted events in one frame. Compare normalized owned command semantics, geometry/hit bounds, event consumption, callback order/counts and deterministic stub-font software pixels; never expected snapshots generated from the new implementation itself. New tests must exercise every phase and overlapping selected/open/disabled/ loading/focus flags; instance once with replay twice; pressed suppressing hover; clear versus absent list; mixed DROP/INSET ordering; all eight layers and nine rejection; presets/CSS factory; transparent/zero scalars; transactional mixed valid/invalid patches and ignored unused storage; callback buffer mutation and content overwrites; custom asymmetric corners, move/resize, clipped ancestors, root opacity, custom content overflow, layout-only/suppression and resource failure. Check empty/no-op facade draw lists/pixels exactly against legacy. For opted-in shadows compare ordinary-only independent software output and actual shadow samples/order; legitimate extra clip commands are not permission to relax ordinary pixels or ancestor-mask correctness. Test post-owner/bridge replacement explicitly. Keep diagnostics active under NDEBUG. Browser fixture runs headless with independent software reference samples, DPI, resize and clips. Native portable renderer checks use private Xvfb through `python scripts/test_local.py --build-dir EXISTING_DIR`; no desktop window and no GPU parity claim from Xvfb. Future builds require the allocated single focused build directory, nice 19, one available CPU and -j1. This checkpoint runs no build. C bindings first; Python/JS/TS/Go/Rust currently author static copied root shadows for the documented bridge subset, not these proposed phase callbacks or arbitrary Button state refinement. Do not expose foreign callbacks until lifetime, exception, reentrancy and thread rules are reviewed; a later typed six-phase owned descriptor is preferable as the first foreign authoring slice. Existing static bridge style still applies last and can mask a C phase shadow. Add explicit capability/version checks, deep-copy/reset/error tests and all five language fixtures before claiming binding parity. On production approval update authoritative headers, SDK/ amalgamation, metadata/ledger limitations and skill guidance through generators, then run required freshness and installed-skill tests; preserve all 78 entries. ## Decision requested Approve only the shadow-aware additive facade, optional rejection status and shared-painter test scope. Keep background/focus/ text/border renderer seams as separately reviewable checkpoints. This signed design is evidence of an audit, not a production API or a completed parity row. --- ## Proposed Button style facade Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/BUTTON_STYLE_FACADE_SLICE.md # Proposed Button style facade Historical design checkpoint. The bounded implementation has since landed in the integration branch; use [the current API guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BUTTON_STYLES.md) for implemented names, behavior and remaining limitations. The proposal below records its review scope. **Design only; no API below exists yet.** This checkpoint follows the built-in state corrections in `2dceccce`. Production approval covers only that earlier slice. This document proposes an additive portable C11 facade; it neither changes the parity matrix nor completes arbitrary upstream `Styled` support. ## Contract selected for review Model **Component Button caller-instance replay**, not the Base control's instance → selected → disabled precedence. Frozen authority is upstream kit 0.7.1 `87d10ae5e1299d1be18670a37570c5402f952e34`: [Component Button lines 600–809](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/crates/component/src/button/button.rs) clones caller instance style, applies it after defaults, and replays it inside the selected and disabled semantic layers. Consequently an explicit instance background can keep its color while disabled. A disabled callback is not a permission or activation override. [Base Button](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/crates/base/src/button.rs) uses the [shared state resolver](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/crates/base/src/state_style.rs): selected then disabled replace instance values. CUI's existing Checkbox facade also invokes instance, checked/mixed, disabled sequentially. Button will reuse its initialized paint-record and `user` conventions, **not its precedence**. Documenting this distinction is necessary; this proposal cannot satisfy both conflicting contracts simultaneously. ## Proposed public surface Proposed new `include/cui/cui_button_styles.h`, including existing component types. No platform or Clay types, heap allocation, ownership transfer or additional input dispatch. Names remain subject to review. The production record is named `cui_button_style_paint` because `cui_button_paint` is already a legacy C function. ```c typedef struct { cui_box root; /* Resolved box; geometry is inspection-only. */ cui_color foreground; /* Label and inherited icon/content ink. */ } cui_button_style_paint; enum { CUI_BUTTON_PAINT_BACKGROUND = 1u << 0, CUI_BUTTON_PAINT_BORDER = 1u << 1, CUI_BUTTON_PAINT_FOREGROUND = 1u << 2, CUI_BUTTON_PAINT_RADIUS = 1u << 3, CUI_BUTTON_PAINT_CORNERS = 1u << 4, CUI_BUTTON_PAINT_OPACITY = 1u << 5 }; typedef struct { unsigned fields; cui_button_style_paint paint; } cui_button_paint_patch; typedef enum { CUI_BUTTON_STYLE_INSTANCE, CUI_BUTTON_STYLE_HOVER, CUI_BUTTON_STYLE_ACTIVE, CUI_BUTTON_STYLE_SELECTED, CUI_BUTTON_STYLE_DISABLED, CUI_BUTTON_STYLE_FOCUS } cui_button_style_phase; typedef struct { cui_id id; cui_button_style_phase phase; bool hovered, pressed, focus_visible; bool selected, open, disabled, loading; } cui_button_style_info; typedef void (*cui_button_style_fn)(void *user, const cui_button_style_info *info, const cui_button_style_paint *current, cui_button_paint_patch *out); typedef struct { cui_button_style_fn instance, hovered, active, selected, disabled, focused; void *user; } cui_button_styles; bool cui_button_styled_ex(cui_context *, cui_id, const cui_theme *, cui_str, cui_button_options, cui_button_styles); void cui_button_styled_paint(cui_context *, cui_id, const cui_theme *, cui_str, cui_button_options, cui_button_styles); ``` `styled_ex` uses the existing Button submit/reduce/metadata path exactly once, returning its existing aggregate bool. Existing option callbacks run at their existing activation gates/order. `styled_paint` is the corresponding passive paint seam: it must not register input, submit semantics or reduce events. Zero styles give the same output as the corresponding existing API. This is not an implicit wrapper around `cui_button_ex` followed by a second paint call. No new event-observer overload is included in this slice; existing event and composition integrations need a separate explicit compatibility review before claiming they can accept these style callbacks. `current` is fully initialized for this phase. `out` starts zero on every call. Only `fields` grants write presence: a zero field mask means no refinement; transparent black, zero opacity, zero radius and all-zero corners remain explicit valid values when their bits are present. Do not infer presence by comparing the result with defaults, or by testing colors/numbers for zero. Allowed root writes are background, border color, uniform radius, corner radii and opacity. CORNERS copies `root.custom_corners` and `root.corner_radii` together; false explicitly restores uniform radius. OPACITY uses `root.opacity` as the explicit value and sets `root.custom_opacity=true`, including for zero. It does not copy an ambiguous zero-initialized `custom_opacity` flag. If both radius and corners are supplied, existing box corner precedence applies. Foreground copies one RGBA value. Every other `cui_box` member is inspection-only and never copied from a patch: width/height, padding, gaps, border widths/edges, clipping, alignment, offsets, inertness, layout-only, grow/percentage flags and caps. Neither font sizing nor content layout is exposed. This prevents a callback from changing the paint box while measurements, hit targets, semantic bounds and slot layout still use the old box. Border thickness remains under existing options; border color is independently customizable. Radius/corners change decoration only; existing rectangular hit testing is unchanged. The API must not promise shape-aware hit testing. Reject a whole patch if it has unknown presence bits or a present numeric field is nonfinite, negative radius/corner, or opacity outside 0..1. Ignore it without poisoning the Core frame, preserve the preceding paint, and continue later eligible callbacks. Read-only writes are ignored, even if their values are invalid. A patch mask is bounded and captured by value for replay; no pointer into `out` survives the call. ## Exact resolution and callback timing A private common resolver must separate defaults from patch application and must not reconstruct presence by diffing mutable records. A callback runs at most once per submission, including `instance`; replay reapplies its captured patch without calling application code again. 1. Initialize normal built-in paint from the existing options/theme, after existing sizing/content measurement decisions. Invoke `instance`, validate and capture its patch, then apply it. 2. If interactive, not selected/open and pressed, apply built-in active paint and the `active` callback patch. Otherwise, if interactive, not selected/open and hovered, apply built-in hover paint and `hovered` patch. Pressed suppresses hovered. No instance replay occurs in these pointer layers: these are explicit opt-in interaction refinements. 3. If selected or open, apply built-in selected paint, then invoke/apply `selected`, then replay the captured instance patch. The callback runs once when both selected and open are true. `info.selected` and `info.open` retain their separate option values; neither implies toggled semantics. 4. If disabled, apply built-in disabled paint, then invoke/apply `disabled`, then replay the instance patch. This follows selected when both are true. Fields not supplied by instance retain the disabled result. A disabled handler's background loses to an explicit instance background; this is the chosen Component replay contract, not a bug or Base-style precedence. 5. If loading and not disabled, apply the existing whole-control 0.8 fade to the resolved paint. Loading suppresses hovered/active callbacks but does not invoke disabled. It can still invoke selected for selected/open. Fade composes with explicit root opacity (0.5 becomes 0.4); disabled skips this fade. This explicit CUI composition rule is scoped behavior, not a claim about every upstream arbitrary opacity modifier conflict. 6. Apply existing focus paint, then invoke/apply `focused` only when its existing focus-visible and hide-focus-ring gates permit. No instance replay follows it. Focus remains the final decoration layer; this slice does not change focus geometry or add the source outer-ring theme mode. Here “interactive” means neither disabled nor loading. Raw hover/pressed flags in `info` are the stable interaction snapshot used by the resolver; they do not override eligibility. Focus uses existing behavior, including a retained focus-visible state during loading/disabled transitions. `focused` must not be advertised as a disabled-eligibility escape. Keep the legacy resolver's focus gates until the separately reviewed focus slice changes them. Callbacks are synchronous, borrowed for this submission only. `user`, function pointers and all pointed-to data must remain valid until the call returns; none is retained across frames. `current`, `info` and `out` are temporary and must not escape. Callbacks may read their owner model and fill paint patches. They must not call CUI APIs, queue/consume events, submit children, change the owner model, options or styles, or trigger reentrant submission in the same frame. The callback intentionally receives no `cui_context *`. This is a paint calculation, not dispatch or an owner event callback. It cannot intercept, cancel, duplicate or manufacture activation. Existing slot callbacks retain their existing separate content contract. ## Intended usage (proposed API only) This C11 example is intended to compile against the future header. It is not an example of an API available in the current SDK. ```c #include "cui/cui_button_styles.h" typedef struct { cui_color hover, selected, disabled; } save_style; static void save_hover(void *user, const cui_button_style_info *info, const cui_button_style_paint *current, cui_button_paint_patch *out) { const save_style *s = user; (void)info; (void)current; out->fields = CUI_BUTTON_PAINT_BACKGROUND; out->paint.root.background = s->hover; } static void save_selected(void *user, const cui_button_style_info *info, const cui_button_style_paint *current, cui_button_paint_patch *out) { const save_style *s = user; (void)info; (void)current; out->fields = CUI_BUTTON_PAINT_BACKGROUND; out->paint.root.background = s->selected; } static void save_disabled(void *user, const cui_button_style_info *info, const cui_button_style_paint *current, cui_button_paint_patch *out) { const save_style *s = user; (void)info; (void)current; out->fields = CUI_BUTTON_PAINT_BACKGROUND; out->paint.root.background = s->disabled; } static bool save_button(cui_context *ui, const cui_theme *theme, save_style *style, bool selected, bool disabled) { return cui_button_styled_ex(ui, 42, theme, cui_string("Save"), (cui_button_options){.selected = selected, .disabled = disabled}, (cui_button_styles){.hovered = save_hover, .selected = save_selected, .disabled = save_disabled, .user = style}); } ``` With no instance background patch, selected/disabled callbacks determine their respective backgrounds; disabled wins when both are active. Adding an instance background patch deliberately pins that color across both semantic states. Owner state updates happen after `save_button` returns true or in existing activation callbacks, never inside these style handlers. ## Implementation acceptance and limits Production work requires approval of this exact contract first. A private Button common hook must serve legacy and styled submissions without copying or reordering the activation loops. Do not add capture/bubble handling, retained style state, a new size enum or a theme change. This is a bounded paint facade: arbitrary upstream layout/typography/gradient/shadow/child `Styled` modifiers and private compound `content_style` are explicitly unsupported. Required tests: zero-style equivalence with legacy draw lists/results; explicit transparent/zero values and no-mask preservation; instance once with value replay, selected/open once and disabled ordering; instance collision wins versus selected/disabled, pointer callbacks win their interaction layer; pressed suppresses hover; loading/disabled eligibility and recovery; opacity composition; focus gate/order; rejected numeric/unknown-mask patches; ignored geometry and border-width writes; identical actual bounds, semantic bounds, hit targets and slot layout; actual software pixels plus text/border draw colors; passive paint has no semantics or reduction. Compare pointer, keyboard and AT multiplicity/callback order with legacy APIs. A real usage fixture must compile the owner example against the actual new header after implementation. Run affected native tests only through the private headless wrapper, strict portable C11 warnings, and headless browser tests if web integration changes. This docs-only checkpoint runs no runtime suite. Root owns canonical test registration, public metadata, generated SDK/distribution and skill refresh. --- ## Calendar keyboard and localization audit Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/CALENDAR_KEYBOARD_LOCALIZATION_AUDIT.md # Calendar keyboard and localization audit Design checkpoint only. No API or implementation below is shipped by this document. ## Authority and method CUI baseline: `19e390c4`. Frozen upstream source: `87d10ae5e1299d1be18670a37570c5402f952e34` (0.7.1), inspected from the existing local checkout, without network or moving-main assumptions. | Frozen file | SHA-256 | | --- | --- | | `crates/base/src/calendar.rs` | `23f747d81667c1f68a54ca827863d556e167fe500a25eec4049d1c90a7d3cd6e` | | `crates/component/src/time/calendar.rs` | `842e291959ebec26887599289a3e1b52da24870be785ef415efa11f824321251` | | `website/component/calendar.md` | `e9a388c6b802b26c63cf44620059546929d3cf8b02403708badbb71fc8262f8b` | Source locations below refer to that revision. This is source/test inspection, not a new runtime validation. No tests, generated resources, global parity records or production files changed. ## Frozen contract and existing CUI evidence | Area | Frozen behavior | CUI baseline and consequence | | --- | --- | --- | | Keyboard | Base `calendar.rs:635–827` installs click handlers and tracks the state's root focus handle. There are no Calendar-specific key bindings, action handlers or key-down handlers in this module. The comment at 259–261 calls `activate_date` a pointer/keyboard path, but does not implement keyboard traversal. The website introduction promises comprehensive keyboard navigation without a key table. | `src/base/cui_picker.c:235–554` already implements ordered traversal, focus movement and activation. Do not invent an upstream arrow-key contract from the website sentence. | | Day navigation | No explicit traversal keys in frozen Calendar. | Arrows move 1/7 days; Ctrl/Meta arrows move months/years; PageUp/Down move months (Ctrl/Meta years); Home/End use configured week start. Disabled dates are skipped with a bounded 366-iteration search. Enter/Space use the existing interaction activation path. Multiple queued events use the updated cursor. | | Picker navigation | Month/year click transitions; independent month and year toggles for a single-month view. Month view disables previous/next; year pages obey configured year range. | CUI has days/years/months, 20-year pages and keyboard grid traversal, Escape back to days, but only the year-header public ID (part 5). Year selection leads to month selection; no independent month-header toggle. | | Localization | Component `calendar.rs:12–30,89–107` supplies translated month/weekday labels through Base's `label(kind,value)` callback. First weekday defaults Sunday and is separately configurable, not derived from locale. Other values are decimal numbers; navigation is chevrons. | `cui_date_locale` already supplies borrowed month/weekday strings, seven builtin tables (US/GB English, Italian, French, German, Spanish, Japanese), navigation/root/picker labels and numeric date order/separator. Explicit locale normally chooses week start; `first_weekday_override` restores caller control. NULL locale preserves legacy ISO names/week-start behavior. This is an intentional CUI contract, not identical ambient rust-i18n state. | | Accessible names | Base `with_label` sets aria-label even after decorative children replace text (509–512). Day names override labels to ISO full date (775). Header/month/year names are their labels. | Days already use full dates via `cui_date_format_locale`, with selected/parent semantics and a roving tab stop. Navigation, root and picker labels are localized. CUI's localized full date is useful but differs from frozen ISO day names; preserve defaults and offer an explicit override only if needed. | | Neighboring dates | All dates returned in week rows are rendered, muted when outside that displayed month, and remain selectable unless the matcher disables them (755–784). IDs include panel offset and week index. | CUI computes 42 cells but deliberately submits/paints only in-month dates; other cells are empty. Existing public day ID depends only on date, so simply rendering duplicates across panels is unsafe. | | Today | State captures host local date at construction (183–197). Item state marks today (770); Component gives unselected today accent paint. | No supplied today date or today-specific paint. Core should accept a host-supplied civil date, never acquire wall-clock/timezone state. | | Selection/events | `activate_date` emits Selected for every enabled complete selection, even an already selected date. Earlier second range endpoint restarts the range rather than swapping it (237–267). | Preserve CUI legacy range behavior and `.changed/.activated/.navigated` aggregate. Existing typed CHANGE observers notify actual final endpoint changes once at outer return; they are not frozen Selected events. Do not relabel them as such. | | Bounds/layout | Source has configurable year range (default today ±50), unrestricted month count (facade clamps effective width count to at least one), item styling and Small/default/Large sizes. | CUI Gregorian years 1–9999, min/max/predicate policies, one-to-three months, custom cell size. These bounds and style limitations remain explicit; this audit does not erase them. | Frozen Calendar does **not** implement week-number columns or hover range previews. Those may be separate product extensions but cannot be cited as missing frozen Calendar features. CUI's manifest limitation currently groups them with genuine today/neighbor gaps. ## Evidence already present `include/cui/cui_picker.h:20–83` is the public authority. `tests/unit/test_picker.c` covers Gregorian grids over forty years/all week starts, locale formatting/truncation/fallback, locale week-start override, year/month grids and boundaries, bounded selection, ordered queued keys, Enter/Space activation, roving semantics, custom month and picker labels, and cell-size presentation. Its Base-only build also exercises behavior independently of Styled paint. `tests/web/test_date_locale_year.py` drives actual WASM with mouse and CDP touch for Calendar and DatePicker in seven locales: twenty-year grid geometry, localized month/weekday paint, actual selected date, localized trigger semantics and Escape transitions (28 cases in the fixture). It is not proof of every keyboard combination. `tests/unit/test_picker_events.c` compares legacy and typed operations, including ordered changes, disabled policy, navigation and observer restrictions. None of these suites was rerun for this documentation-only checkpoint. The manifest's `keyboard/localized semantics: not_started` conflicts with these APIs/tests and the separate tested ordered-keyboard feature. Root should reconcile it feature by feature after reviewing evidence, without claiming full Calendar parity or removing any of the 78 entries. ## Proposed cohesive implementation Recommended next production scope: an additive **Calendar presentation options** facade in a new header, delegating to the existing reducer and semantics, with opt-in direct month toggle and supplied-today styling. This yields visible source-backed improvements while keeping the existing keyboard and locale API authoritative. Neighboring-day interaction is a separate slice because it needs occurrence identity and ordered hit-target mapping. Proposed names/types are illustrative until API review: ```c typedef struct { bool month_toggle; /* zero preserves year-then-month path */ cui_date today; /* invalid/zero means no today decoration */ } cui_calendar_presentation_options; /* base/styled _ex counterparts take existing options plus this record. */ ``` The extra month header needs a new documented part ID, a live eligibility check, selected/open semantics, keyboard activation, and deterministic focus restoration to the current month. It must not reuse the existing year part or change its meaning. Only expose the source's independent toggles for one-month mode; preserve legacy multi-month headers. Today paint must lose to selected paint, retain disabled contrast, and not change selection, cursor, eligibility or event emission. Existing default calls retain exact semantics and pixels. A standalone today paint helper is an alternative if adding an extended submission path would duplicate reducer code; prefer one shared private implementation. Alternative A (smallest): append opt-in fields to `cui_calendar_options`. It avoids facade proliferation and naturally reaches DatePicker, but changes public struct ABI, canonical bindings and generated layouts; it also touches a shared public header. Alternative B (recommended): a new extension header with `_ex` functions and an independent record leaves legacy struct layout and caller defaults intact. DatePicker support must be an explicit corresponding extension, not silently inferred through unrelated options. Alternative C: caller-controlled state view plus custom Base composition needs no API, but does not supply a reusable Styled month toggle and is not a complete solution. Do not add a new keyboard enum or dispatcher: retain CUI's portable keys/modifiers and existing reducer ordering. Expand focused tests for modifier/month-end/leap-day/week-start navigation, blocked policies, years 1/9999, multiple keys followed by activation, root versus child focus and AT activation. These should establish the actual CUI contract; they cannot retroactively prove a frozen key binding that is absent. ## Localization extension decision Current tables already cover the frozen component's month/weekday translation capability for those supplied languages. Adding every frozen translation file is data coverage, not a keyboard architecture change. Applications can supply other languages today. Numeric date order is not a locale engine: arbitrary patterns, non-Gregorian calendars, localized numerals, grammatical month forms, RTL layout and OS locale lookup remain unsupported. If custom accessible day labels are required, prefer a bounded formatter callback in the extension record, with `void *user`, date plus item kind/context, caller-provided output buffer/capacity, and required-byte-count excluding NUL. Enforce safe termination, UTF-8 boundaries, a documented maximum, overflow/error fallback, and identical semantic/paint decisions where appropriate. A returned borrowed `cui_str` callback is simpler but exposes temporary storage and frame-lifetime hazards; avoid it. A separate accessible-date formatting helper is the smallest alternative but does not customize submitted Calendar names. No callback is necessary merely to finish the existing locale-table coverage. ## Separate neighboring-date slice Offer explicit opt-in rendering/activation; retain empty cells by default. Define occurrence IDs containing panel/cell plus a helper mapping to civil date, while keeping `cui_calendar_day_id` stable for legacy in-month dates. Decide a unique roving occurrence when a date appears twice, avoid duplicate accessible IDs, and keep keyboard movement based on civil dates rather than panel order. Pointer/AT activation resolves the occurrence to a date through the same bounded policy checks. Test adjacent panels, click versus queued keyboard targets, minimum/maximum and year-edge invalid cells, selected range paint and software pixels. This deserves its own reviewed API checkpoint before production. ## Lifetimes, events and bindings All proposed records/callbacks are borrowed for the outer submission; do not retain callback/user in state. Existing locale table/strings must remain alive while options are used, and any resources referenced by frame paint/semantics must survive consumption. Formatters and disabled predicates must be pure with respect to active UI/state and cannot recursively submit, free or rebind resources. Host supplies today; no platform or Clay types enter public APIs. Existing `cui_picker_events.h` wrappers call the legacy operation once and observe final applied selection, UNKNOWN source, no fabricated input index. Navigation, month-view toggles and today decoration must remain silent to CHANGE. Preserve exact callback timing and per-event live policy checks; no capture/bubble/dispatch changes. If a Selected-style activation observer is later needed, design it separately with honest multiplicity/source evidence rather than stretching CHANGE. The generic bridge currently constructs Calendar options with disabled state and owns Calendar state; it does not expose the complete native locale/policy contract. New C APIs do not imply Python/JS/TS/Go/Rust option support. Root must register sources/tests and separately refresh exports, SDK, metadata and skill resources after integration. Binding marshalling must copy strings or document ownership and must not store ephemeral native callback pointers. ## Proposed verification and approval boundary Production requires explicit root ownership approval. Suggested first slice: new extension header, Calendar-only private implementation changes, focused native tests and compiling consumer guide. Run strict portable C11 Release builds and relevant Base/Styled/picker-events tests through the private Xvfb wrapper; verify zero-extension legacy draw/semantics equivalence, actual software pixels for today precedence, mouse/key/AT month toggle, disabled and multi-month paths, and bounded lifetimes. Follow with a focused actual-WASM fixture only when root registers exports. No canonical build/metadata edits are part of this audit. ## File ownership needed for production A new `include/cui/cui_calendar_presentation.h` can carry the additive facade without changing `cui_picker.h`. Implementation still needs Calendar-only private seams in shared `src/base/cui_picker.c` (ordered reduction, header target IDs and semantic submission) and `src/components/cui_picker.c` (header composition and today paint). Root must reserve those regions; new source files alone cannot safely add header activation to the existing reducer. The pure locale formatter remains in the existing Base file and should not be duplicated. Tests can be new `tests/unit/test_calendar_presentation.c` plus a standalone worker fixture and `docs/CALENDAR_PRESENTATION.md`; canonical registration remains root-owned. Existing event wrappers will need a separately reviewed extended counterpart if the new facade is offered with typed observers; do not silently route an extended call through an old wrapper that drops options. Neighboring dates require another explicit ownership grant for those same Calendar-only seams. --- ## Calendar neighboring-date occurrence design Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/CALENDAR_NEIGHBORING_DATES_SLICE.md # Calendar neighboring-date occurrence design Proposal only, independently reviewable after implementation commit `f7ce2aed`. No neighboring-date API or behavior is implemented by this checkpoint. Frozen authority remains upstream `87d10ae5e1299d1be18670a37570c5402f952e34`; see `CALENDAR_KEYBOARD_LOCALIZATION_AUDIT.md` for exact source digests. ## Source-backed gap Frozen `crates/base/src/calendar.rs:741–784` renders each date in each displayed month's week rows. Outside-month dates are muted, not automatically disabled. The predicate still controls activation. The occurrence ID includes date, panel offset and week index. Each day receives an ISO full-date accessible name. Component paint applies muted foreground before range/selected/today decoration (`crates/component/src/time/calendar.rs:174–214`). Source `apply_date` (222–234) recenters to the selection's start date, including after range changes. Its earlier second range endpoint restarts the range rather than swapping endpoints. CUI already calculates all 42 cells, but semantics and Styled paint omit outside-month dates. `cui_calendar_day_id(root,date)` is intentionally date-based, so reusing it for every visible cell would create duplicate semantic/layout IDs across panels. The private target resolver currently scans neighboring dates too, but that does not provide a submitted, painted or accessible neighboring cell. The new month-toggle/today slice did not change this behavior. ## Recommended additive contract Add a zero-default `neighboring_days` opt-in to the new presentation record, with an explicit rebuild note if its layout changes after publication. Keep legacy `cui_picker.h` and existing functions unchanged. If root has already frozen the new record ABI, use a separately versioned extension record instead; do not silently change installed ABI. The current one-to-three month bound and six-row Gregorian grid remain. A context-free query helper should return the actual cell's date and ID, so hosts, tests and Base composition do not reproduce private hashing: ```c /* Proposed only; names and signature require review. */ typedef struct { cui_date date; cui_id id; bool neighboring; } cui_calendar_cell_info; bool cui_calendar_cell_resolve(cui_id root, cui_date first_month, unsigned first_weekday, unsigned panel, unsigned cell, cui_calendar_cell_info *output); ``` Inputs require a nonzero root, valid first month, panel 0..2 and cell 0..41. Normalize the first month's day to 1 and first weekday modulo seven, matching existing grid behavior. Return false with zero output for invalid inputs, invalid boundary cells or unrepresentable panel months; NULL output also returns false. No allocation, context, locale or callback. A cell query describes geometry, not whether the caller enabled neighbors or submitted that panel. No platform types enter the API. In-month cells keep **exactly** `cui_calendar_day_id(root,date)`. Neighboring cells use a dedicated private namespace encoding date plus panel, avoiding existing date/month/year/navigation namespaces. Encode within checked/bounded integer arithmetic; document that IDs are root-scoped and stable for the same date/panel, and that neighboring and canonical occurrences intentionally differ. Do not use only cell index: after navigation the same index must not activate a different civil date from an already queued event. Test namespace collisions exhaustively across all 126 cells in representative months and boundaries, and verify practical nonzero IDs under supported root constraints (the existing XOR-derived IDs can theoretically produce zero for particular roots; either follow the library's documented ID collision constraints honestly or introduce an explicit checked query failure, never claim mathematical global uniqueness). Alternative: return occurrence IDs for every cell, including in-month dates. It is simpler internally but breaks the established day-ID contract and focus integrations, so reject it for this compatible slice. Rendering neighbors as passive labels avoids duplicate IDs but fails the frozen selectable-neighbor contract and is not completion of this feature. ## Semantics, paint and focus Submit each valid enabled-neighbor occurrence once as a button, using the existing localized full-date naming, selection details and root parent. Keep CUI's localized names; frozen ISO-only names remain a documented difference. Disabled neighbors are submitted disabled. Outside-year invalid cells stay empty. Paint real day numbers with muted foreground for unselected neighboring dates; selected/range paint keeps the existing CUI primary/on-primary treatment, disabled foreground remains muted, and today uses the newly implemented precedence. This does not attempt arbitrary upstream item refinement. Exactly one day tab stop belongs to the civil cursor: prefer its in-month canonical occurrence. Neighboring occurrences are excluded from sequential Tab, while pointer and AT activation remain available. Keyboard date movement continues using the existing civil-date reducer and rebases the displayed month when necessary, then focuses the canonical day ID. This is CUI's explicit keyboard behavior, not an inferred frozen keybinding. No keyboard dispatch architecture change is needed. On pointer/AT activation of an eligible neighbor, apply the existing CUI single/range selection reducer once. If the chosen date is within another displayed month, retain the displayed window and focus that canonical occurrence. If it lies outside the displayed window, rebase the window to that date's month and focus the canonical occurrence. This makes activation visible and avoids focus pointing at a removed neighbor. This recentering policy is compatible with CUI's existing endpoint-swapping range model; it deliberately differs from frozen `apply_date` always centering on range start. Do not change the legacy range model as a side effect. For split reducer/submission, the helper must identify the same dates and IDs in both paths. The reducer matches queued targets against the original displayed-grid snapshot for that outer call, preserving existing queued-input ordering while applying live min/max/disabled policy on every activation. A preceding navigation event must not reinterpret an old occurrence ID as another date. A stale occurrence absent from the snapshot is ignored. No synthetic event insertion, capture/bubble changes or retained hit-test map is required. ## Events and lifetime limits Navigation alone remains `.navigated`; valid neighbor activation has existing `.activated` and actual final selection `.changed` behavior. No CHANGE event for focus or window rebasing alone. Existing typed observer wrappers do not accept presentation options: do not claim this feature reaches those wrappers. A separately approved `_ex` observer wrapper would call the extended operation once and preserve the existing final-applied CHANGE contract, borrowed user data and outer-return timing. Frozen Selected multiplicity is still a distinct contract and is not supplied by CHANGE. Cell-info records are copied values. Presentation options contain no retained callback or allocation. Locale strings, disabled predicate/user resources, state and selection retain existing borrowed submission/frame-consumption requirements. Predicates must remain pure with respect to active UI. Rejecting or omitting a neighbor must not retain pointers to temporary grid arrays. Hosts may omit the entire widget after frame consumption without additional cleanup. ## Required focused verification Use the existing private Release fixture and Xvfb test wrapper, strict C11 warnings and compiling guide. Add actual software-pixel and semantic evidence, not only helper tests: - Single, two and three months: exactly one semantic/layout ID per valid cell occurrence; same date has distinct neighbor IDs but a stable canonical ID. Different week starts and leap months. - Mouse, Enter/Space on a programmatically focused occurrence, and queued AT actions select the correct date; ordinary sequential Tab still uses only one canonical cursor. Validate supported focus behavior rather than declaring neighbors inaccessible to keys. - Neighbor→header and navigation→neighbor queued sequences preserve original target identity; repeated date occurrences cannot redirect selection. Disabled policy changes after prior semantics reject activation live and recover after policy removal. - Dates before minimum/after maximum, all dates disabled, year 1/9999, panel overflow and invalid helper inputs remain bounded and safe. - Selected endpoints/interior ranges, unselected muted neighbors, disabled selected neighbors, today neighbors and light/dark themes have the documented actual draw colors/pixels. - Zero opt-in is byte-equivalent in observable draw/semantic content and software pixels to legacy; no new callbacks or selection changes from merely displaying neighbors. Omission/reappearance retains caller state and consumes no borrowed grid storage later. A focused headless actual-WASM test follows root export registration; no broad browser gate or source-status promotion from native tests alone. ## Ownership request and review boundary Proposed production ownership: new helper declarations and presentation opt-in in `include/cui/cui_calendar_presentation.h`; Calendar-only helper/target-resolution/reduction/submission regions in `src/base/cui_picker.c`; Calendar-only day-cell paint in `src/components/cui_picker.c`; focused tests/worker fixture and `docs/CALENDAR_PRESENTATION.md`. Preserve ColorPicker, TimeField, legacy DatePicker and legacy public picker header. DatePicker opt-ins are a separate extension because its current composition passes zero presentation options. Canonical registration, bindings, generated artifacts and all 78 parity entries remain root-owned. Root approval is required before implementing this proposal. Completion would address selectable neighboring cells under the stated CUI bounds, not full Calendar source style, locale, event or unrestricted-month parity. --- ## Calendar selection and view policies Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/CALENDAR_SELECTION_POLICIES_SLICE.md # Calendar selection and view policies Design checkpoint only; no proposed declarations or behavior below are implemented. CUI authority is verified integration `9628efc3`. Frozen source authority is `87d10ae5e1299d1be18670a37570c5402f952e34`, inspected locally without moving-main assumptions. Public option names describe behavior and contain no upstream branding. ## Exact source and baseline behavior Frozen `crates/base/src/calendar.rs` SHA-256: `23f747d81667c1f68a54ca827863d556e167fe500a25eec4049d1c90a7d3cd6e`. | Decision | Frozen implementation | CUI baseline | | --- | --- | --- | | Earlier second endpoint | `select_date:237–257` completes a pending range only when value >= start; otherwise starts a new pending range at value. A completed range's next activation also starts a new pending range. | `cui_picker_select` uses `state.selecting_end`; a second endpoint is accepted and endpoints are swapped if reversed. Next activation after completion starts another range. | | Authoritative phase | Frozen Date's optional endpoints determine pending/completed state. No separate pending flag. | Caller-owned `cui_calendar_state.selecting_end` controls whether valid start is treated as pending, even if externally supplied endpoints do not match that flag. | | Year selection | `select_year:385–388` changes current year and returns directly to Day, retaining current month. | Accepted year selection opens Months, then accepted month selection opens Days. | | Recentering | `apply_date:222–234` stores accepted date and sets current year/month from its start. `select_date` calls it on each accepted activation, including incomplete range starts. | Legacy day selection does not itself always recenter. Neighbor presentation focuses the activated canonical day and recenters only when outside the currently displayed window; keyboard navigation has its separate visible-window rules. | | Endpoint validation | `Matcher::is_match:118–124` tests both completed range endpoints; `apply_date` rejects the whole proposed selection if either is disabled. `select_date` first checks the newly activated date too. | The live activation check tests the newly activated date; an earlier accepted start can remain after policy changes. Interior range dates are not individually constrained. | | Events | `activate_date:261–267` emits Selected for a complete accepted selection, including repeated complete activation; incomplete changes still notify state. | Aggregate `.changed` compares final endpoint values, `.activated` records accepted activation, and existing CHANGE wrappers notify zero/one actual final change at outer return. These are distinct contracts. | Existing evidence: `tests/unit/test_picker.c` tests endpoint sorting, queued day keys, year→month flow and disabled/date bounds; `tests/unit/test_picker_events.c:range_and_chooser` proves sorted reverse range plus silent year/month navigation; `tests/unit/test_calendar_presentation.c:neighbor_routing/neighbor_edges_and_space` proves original-grid pointer/key/AT multiplicity, earlier-end swapping, canonical focus and current recenter behavior. These tests must stay as zero-policy regressions. This checkpoint inspects them; it does not rerun runtime suites. ## Recommended additive API boundary Use a **new** `include/cui/cui_calendar_behavior.h` and value-only options record. Do not resize the presentation record that now has verified integration/distribution and matching-header/library requirements. Keep existing Calendar functions unchanged and delegate new functions to one private common reducer. Proposed API only: ```c typedef enum { CUI_CALENDAR_RANGE_LEGACY = 0, CUI_CALENDAR_RANGE_RESTART_EARLIER } cui_calendar_range_transition; typedef enum { CUI_CALENDAR_YEAR_OPEN_MONTHS = 0, CUI_CALENDAR_YEAR_OPEN_DAYS } cui_calendar_year_destination; typedef enum { CUI_CALENDAR_RECENTER_LEGACY = 0, CUI_CALENDAR_RECENTER_ACTIVATED_DATE, CUI_CALENDAR_RECENTER_SELECTION_START } cui_calendar_recenter_policy; typedef struct { cui_calendar_range_transition range_transition; cui_calendar_year_destination year_destination; cui_calendar_recenter_policy recenter; } cui_calendar_behavior_options; cui_calendar_result cui_calendar_reduce_with_behavior(cui_context *, cui_id, cui_calendar_state *, cui_date_selection *, cui_calendar_options, cui_calendar_presentation_options, cui_calendar_behavior_options); cui_calendar_result cui_base_calendar_with_behavior(cui_context *, cui_id, cui_calendar_state *, cui_date_selection *, cui_calendar_options, cui_calendar_presentation_options, cui_calendar_behavior_options); cui_calendar_result cui_calendar_with_behavior(cui_context *, cui_id, const cui_theme *, cui_calendar_state *, cui_date_selection *, cui_calendar_options, cui_calendar_presentation_options, cui_calendar_behavior_options); ``` No submit-only behavior variant is needed: `cui_calendar_submit_ex` submits the already reduced state and selection, using the same presentation options. Policies affect reduction, not stored callbacks or styling. Keep public declarations portable C11 and C++ compatible, without platform/Clay types. Zero options are exactly the current reducer, draw and semantic path; an explicit activated-date policy cannot substitute for zero because current legacy behavior conditionally retains a multimonth window. Normalize each unknown enum value independently to its zero legacy value, preserving other valid fields. Document and test this fallback for negative casts and large values. Alternative: reject the complete operation on any invalid enum, with an explicit validity result. That is stronger validation but needs another result type and risks unrelated maintenance/focus suppression; independent fallback fits the existing forgiving Calendar options better. Alternative API: append fields to `cui_calendar_presentation_options`. It is fewer function names but makes behavioral policy look like paint configuration and changes that public record's ABI. A versioned record/size-tagged API could support future fields, but adds machinery to a bounded three-policy extension. Booleans are representable but give less readable call sites and no distinct three-state recenter choice. Prefer the independent typed record above. ## Range transition contract `RANGE_LEGACY` preserves the existing flag-based transition exactly. In range mode, `RANGE_RESTART_EARLIER` treats the valid endpoint shape as authoritative **on activation**, so supplied partial ranges can reproduce the source transition. It does not silently rewrite caller selection or phase merely because an option changes or another frame is rendered. | Before accepted day activation | Restart-earlier result | | --- | --- | | No valid start, with or without end | start = activated date; end = zero; selecting_end = true | | Valid start and no valid end, activated < start | start = activated date; end = zero; selecting_end = true | | Valid start and no valid end, activated >= start | keep start; end = activated date; selecting_end = false | | Valid completed endpoints | start = activated date; end = zero; selecting_end = true | Equal start/end completes a one-day range. Invalid civil endpoints are treated as absent for transition inference; arbitrary invalid dates are a CUI input concern absent from the frozen typed date representation. When `range=false`, the range policy has no effect and existing single selection remains. Existing bound/predicate checks apply before acceptance. Restart is an applied incomplete selection: `.activated=true` and `.changed` reflects actual final endpoints, not completion alone. Restart-mode completion changes the absent end into a valid date even when both endpoints equal. Zero legacy mode still preserves its phase-only/same-value edge cases with inconsistent caller flags; do not manufacture CHANGE for phase alone. This full transition mode intentionally includes endpoint-shape inference. A narrower policy that changes only the earlier comparison while still consulting `selecting_end` is an alternative, but cannot reproduce a supplied pending range without extra host synchronization. If root chooses the narrower alternative, expose a separate explicit phase policy later and document that limitation instead of claiming the source transition is covered. ### Additional endpoint-validation gap The three requested policies do not alone reproduce source behavior when a pending start becomes disabled before completion. Do not hide that difference inside range restart or recentering. A separately approved fourth field can use: ```c /* Optional addition for review; not required to ship the three-policy slice. */ typedef enum { CUI_CALENDAR_VALIDATE_ACTIVATED_DATE = 0, CUI_CALENDAR_VALIDATE_RANGE_ENDPOINTS } cui_calendar_range_validation; ``` With explicit endpoint validation, build a candidate selection in local values, recheck both endpoints for a completed candidate using current min/max/predicate policy, and commit selection plus phase only if accepted. Incomplete candidates validate their activated start. Rejection preserves selection/phase and reports no accepted activation; previously applied cursor navigation can remain. No interval-wide scan: interior disabled dates remain allowed. Zero retains existing live activated-date-only validation. Include this policy only after review; choose whether to include its field before freezing the new record ABI. If approved later, use a versioned or separately extended record rather than silently resizing an installed record. Until then the remaining gap must stay documented and implementable, not silently called complete. ## Year destination and focus `YEAR_OPEN_MONTHS` preserves year→month behavior. `YEAR_OPEN_DAYS` affects only accepted year-item activation, not highlight traversal, page navigation, month-header toggling or external state changes. Keep the displayed civil month, change its year, and return to Days without modifying selection. Clamp the previous civil cursor's day to the valid day count in that month/year. Prefer that enabled date; otherwise scan at most that month's 31 dates for the first enabled date. If none is enabled, keep the displayed month and a valid civil cursor, but focus the year header rather than a disabled/missing day. Do not jump to another month merely because it contains an enabled date: the frozen year selection preserves month. The existing year-enabled predicate still rejects years with no enabled date anywhere. This explicit CUI focus rule makes the new path usable; frozen Calendar does not define a roving day cursor/key traversal contract to copy. Accepted year activation reports `.navigated=true`, `.activated=false`, `.changed=false`; selection observers stay silent. Test leap-day clamping, current-month-all-disabled versus whole-year-disabled, bounds, years 1/9999 and header focus restoration. ## Recentering and cursor policy Apply recenter policy only after accepted **day selection**, including a new incomplete range start. Header navigation and external selection assignments do not implicitly recenter. - `RECENTER_LEGACY`: exact current behavior, including conditional neighbor window retention and legacy keyboard navigation. No change merely because the new function is used. - `RECENTER_ACTIVATED_DATE`: always put the activated date's month first, even if it was already in panel two/three; focus its enabled canonical day. - `RECENTER_SELECTION_START`: always put the resulting selection start's month first. In single mode the resulting start is the activated date. For ranges this uses the committed start after restart/swap, not the previous start and not necessarily the activated endpoint. For explicit selection-start recentering, make the civil cursor agree with the visible anchor and focus the canonical start when enabled. If an old retained start is now disabled under activated-date-only validation, keep its month visible and choose the first enabled visible day in a bounded ≤93-date search; if none, focus the year header and retain a valid civil cursor. This avoids the existing tail-normalization path undoing the requested recenter, and avoids focus pointing to an endpoint outside the displayed window. A subsequent queued arrow key may then navigate using the existing updated cursor rules. No global key listener or forced focus event injection. Recenter reports `.navigated` only when it actually changes the displayed month or cursor/focus destination; acceptance still sets `.activated`. `.changed` depends only on final endpoint values. Preserve the existing year-edge bound for displayed panels and never create dates beyond 1..9999. Selected/disabled/today/neighbor paint precedence remains unchanged. ## Ordering and callback compatibility cases Keep the outer call's original displayed-grid occurrence mapping. Each event applies live policy to the updated selection/phase, with no deduplication of actual activations and no reinterpretation of a previous cell index after recentering. Calendar options/behavior are copied values for the call; predicates remain borrowed and pure. Inactive/disabled/policy-rejected events cannot apply a transition. Do not change core capture, focus-event preprocessing or dispatch architecture. Required cases before production completion: 1. Pending Feb 20 → activate Feb 10: zero sorts to Feb 10–20 and completes; restart produces pending Feb 10. A following Feb 15 in the same queue completes Feb 10–15. Reverse-order and equal-endpoint cases use actual pointer, Enter/Space and AT routing. 2. Supplied start + no end with selecting_end=false, and supplied completed endpoints with selecting_end=true: zero preserves flag semantics; restart mode follows the documented endpoint shape. Mode changes alone emit nothing and change no endpoint. 3. Two/three visible months with endpoint in another panel: legacy retains the window, activated-date recenters that month, selection-start recenters committed start. Neighbor→header and navigation→neighbor retain original target identity. Repeated activation still runs transitions, rather than collapsing to one event. 4. Year activation with direct-days policy preserves selection and month; returning to days does not consume a second synthetic activation. Queued events targeting old year/month cells are handled only by the existing live view rules, never retargeted as day clicks. 5. Live start/policy changes between earlier frames and completion; rejected newly activated date; optional complete-endpoint validation; no enabled anchor day; widget disabled/inert/passive; omission/reappearance; boundary years and invalid enum fallback. 6. Zero-policy observable draw/semantic/software-pixel equivalence, Base-only and split reduction/submission, plus existing picker and event suites unchanged. No artificial tests that only mirror helper arithmetic. Existing `cui_picker_events.h` wrappers invoke legacy functions once and notify final applied endpoint changes zero/one times at outer return. They do not take the proposed policy or presentation options. Do not silently change them or claim a bridge. If separately approved, additive extended observer counterparts can reuse `cui_date_selection_handler` and borrowed `user`, call the new operation once, and retain UNKNOWN metadata/no fabricated input index and outer-return timing. Observe incomplete restart changes; silence same-value/phase-only changes, year navigation and recentering. Do not invoke observers per internal transition or reinterpret source Selected as CHANGE. Existing callback mutation/lifetime restrictions and teardown-after-frame-consumption remain. ## Lifetimes, bindings and production boundary The new record and payloads contain copied portable values; no retained callback or allocation is introduced. Caller owns state and selection. Existing borrowed locale strings and disabled predicate/user resources must survive their documented submission/frame-consumption intervals. Policy implementation must not retain temporary candidate or grid pointers or call application code from painting. Language builders currently do not expose presentation options, and this proposal adds no bridge marshalling. DatePicker composition and its close-on-completion phase behavior remain separate: applying range restart there eventually needs an explicit DatePicker extension and tests, not reuse of a Calendar-only API name. Public C functions do not imply binding coverage or browser verification. Suggested reviewable production slices: (1) common bounded behavior record and range transition, (2) year destination plus explicit recenter/focus with combination tests, (3) optional endpoint validation and extended observer wrappers only if separately approved. All share the same private Calendar reducer; no alternate dispatcher or duplicated public implementation. Ownership needed: new header, Calendar-only private Base seams, new focused tests/worker fixture and consumer guide; canonical registration/dist/SDK/metadata/skill refresh follow root approval. Preserve all 78 entries and keep source-specific incomplete items explicit until tested. No production edits are authorized by this checkpoint. --- ## Canvas gallery mesh adapter Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/CANVAS_MESH.md # Canvas gallery mesh adapter The gallery currently routes mesh command 6 through its rectangle fallback. Implement a host-only JavaScript raster consumer before exposing Popover arrows. No Core API, public API, native adapter or existing legacy surface changes belong to this slice. Gallery controls follow in a separate slice. Decode mesh count, origin, scale, linear premultiplied color and XY/ST through additional `gallery_command` fields. Check the count before allocating a vertex array. Copy values during the current frame; never retain WASM memory views. The renderer prepares every mesh before target dimension assignment or clear, alongside the existing shadow preflight. Preparation owns independent triangle rasters and expires on the next preparation. Failure leaves the target intact. The supported host transform is finite positive uniform scale plus translation, which covers the gallery's DPR mapping. Reject other matrices explicitly. Require source-over and finite global alpha in 0..1; verify state at drawing. Convert XY to physical pixels; leave ST unchanged. Use the software adapter's double edge equations, orientation correction, top-left inclusion, pixel-center clipping, physical ST derivatives, .001 solid threshold and zero-gradient coverage rule. Unpremultiply finite linear RGB, clamp, then encode sRGB; alpha zero produces zero RGB. Out-of-gamut input is valid. Quantize coverage alpha to nearest byte. Prepare one tightly bounded Canvas raster per visible nondegenerate triangle. Use reusable ImageData scratch and retain only uploaded canvases. Draw triangles in command order through Canvas source-over, preserving overlap rather than flattening a mesh into an intermediate image. The prepared pixel mask owns nested clips and backing-viewport clipping; temporarily remove gallery clip states exactly as the existing shadow path does. Draw at identity transform, without smoothing, then restore caller state. Mesh color already includes Core ancestor opacity; the host must not apply that opacity again. Bound a frame to 131072 commands, 262144 vertices, 64 nested clips, 4096 prepared triangle canvases, 100 million candidate pixel visits, and 32 MiB accounted owned raster bytes (all retained canvas backing plus peak reusable ImageData scratch). Validate finite derived arithmetic before integer conversion or allocation. Browser/driver object overhead is outside this byte accounting and is constrained separately by the canvas-object bound. Reject resource exhaustion before clear. Degenerate and offscreen geometry is valid empty output but still consumes input-count budget. Headless Canvas tests cover DPR1/2, analytic ST including zero gradient, winding, shared edges, degenerate triangles, color conversion, transparent alpha zero, ordered translucent overlap, fractional nested clips, translation, transform and capacity rejection, payload lifetime, expired prepared frames and unchanged target after preparation failure. Require exact edge/clip/coverage masks; compare color compositing against explicit Canvas reference vectors with only measured per-vector rounding allowances. A real Core-emitted ancestor-opacity mesh must prove opacity is applied once. Later Popover gallery tests consume actual CUI mesh commands, never substitute DOM geometry. Exact upstream raster parity remains outside the claim. --- ## High-precision ColorPicker state: design checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COLOR_HSLA_ENTRY_DESIGN.md # High-precision ColorPicker state: design checkpoint Design only, based on CUI `bffef3c6`. No declarations, production changes, source metadata, generated files or completed-parity claims accompany this checkpoint. This extends the decisions in `COLOR_PICKER_SOURCE_AUDIT.md`, without changing the shipped byte-RGBA ColorEntry contract. ## Exact source evidence Frozen upstream kit revision: `87d10ae5e1299d1be18670a37570c5402f952e34`. Inspected `crates/base/src/color_picker.rs`, its embedded tests, the styled `crates/component/src/color_picker.rs`, and Base Slider. The frozen workspace pins `upstream-pre = 0.3.8`; Cargo.lock checksum is `d7f0bc3ebba070f8981b3f8e905a12f47d27794a30d029e59cdb9edf7a4b3360`. The existing cache `/home/matteo/.cache/cui-validation/upstream-pre-0.3.8.crate` matches that checksum. Its `src/color.rs` supplies the actual Hsla/Rgba conversions below. No dependency was installed or fetched. `Hsla` has four `f32` members, normalized hue/saturation/lightness/alpha. The `hsla` constructor clamps each member to 0..1; the public struct also permits direct construction. Its equality compares components with `total_cmp`, so source equality is not rendered-color equivalence. Hue 0 and 1 can represent the same red while remaining different stored values; hue is meaningful state even on an achromatic color. Do not erase it by a render-time RGB conversion. HSL-to-RGB uses chroma `(1 - abs(2*l - 1))*s`, intermediate `x = c*(1 - abs((h*6)%2 - 1))`, offset `m = l-c/2`, and six hue sectors (sector 6 uses sector 0). RGB channels are clamped; alpha passes through. RGB-to-HSL uses min/max/delta, lightness `(max+min)/2`, a lightness-dependent saturation denominator, and hue sectors with positive remainder for red. Achromatic RGB converts to hue zero. These are encoded RGB channel operations; ColorPicker does not perform an sRGB transfer-function conversion here. The picker hex parser accepts optional hash, exactly 3/4/6/8 ASCII hex digits, nibble duplication, and default alpha 1. It first divides bytes by 255 as f32, then converts float RGB into HSL. The actual input pattern requires hash but admits incomplete drafts. No decimal HSL/RGB text grammar or arbitrary CSS parser is implemented by this picker. The general upstream Rgba parser is not its authority. The picker formatter converts HSL to float RGB and truncates each `channel*255` to an integer. It emits uppercase six digits when alpha >=1, otherwise eight. The source test requires `.5` alpha to format as `7F`, not `80`. Near a byte boundary, float arithmetic can affect truncation; exhaustive byte-exact round trip claims would be inappropriate without measured proof. ## What precision preservation actually means Source `update_value` writes the supplied Hsla directly to committed value, preview and sliders. Its programmatic hex write suppresses the resulting Input Change callback: that display must not become a new source color. Slider events read the four slider values, assign the float color, format hex, emit Change, and deliberately do not rewrite the active sliders. Thus a color such as `{.h=.1234567, .s=.2345678, .l=.3456789, .a=.5}` survives synchronization and ordinary rendering without an implicit byte round trip. Explicit hex entry is different. `commit_hex` always parses the supplied string, even if it is the unchanged programmatically formatted display. Pressing Enter can therefore intentionally quantize that float color. For example displayed alpha `7F` commits as `127/255`, rather than retaining `.5`. Enter on displayed black can reset latent hue through RGB-to-HSL. A new API must not quietly make unchanged-display Enter bypass parsing while calling that source parity. Valid text Change previews and updates the sliders without committing. Invalid or incomplete text leaves the last valid preview/committed values untouched. Palette selection closes first, then synchronizes and emits Change; slider updates emit without closing. Same-value explicit selection/update can emit. Programmatic set/clear and initial default synchronization emit no Change. `preview_color` changes preview/display; `clear_preview` restores committed display. Source preview restoration is separate from rewriting the committed selection. No general validation/veto engine is present. ## Existing CUI boundaries `cui_color` is byte RGBA. `cui_hsv` uses hue degrees and brightness, not normalized HSL lightness; its byte conversions round. `cui_color_entry_state` owns a bounded draft/editor with optional byte committed/preview values. Its Enter commits bytes, and its silent sync uses the existing byte formatter. All of these remain ABI and behavior compatible. Do not reinterpret their members or add hidden precision storage to the existing structs. `cui_plot_hsla` already has normalized float components, but it is a Plot shader seam, with `cui_plot_linear_rgba` and linear premultiplied raster output contracts. It must not become a dependency of Base ColorPicker or imply an encoded/linear color-space identity. `cui_theme_color_parse` supplies theme-oriented syntax and byte output; it is not a precision-preserving entry model or source picker parser. ## Proposed additive API and acceptance decisions Provisional dedicated header `cui_color_hsla_entry.h`, with prefixed new types: `cui_color_hsla { float h,s,l,a; }`, explicit optional `cui_color_hsla_value { bool present; cui_color_hsla color; }`, and an owned `cui_color_hsla_entry_state`. These are portable C11 with no platform/Clay/Plot types. Use C float to retain source-scale precision; do not promise identical f32 bits on every C platform or compiler contraction setting. Stored accepted components are copied directly, never reconstructed from their display. All present input components must be finite and in inclusive 0..1. Reject invalid values transactionally; no implicit wrapping, clamping, step snapping, hue normalization, negative-zero canonicalization, or RGB conversion on acceptance. This checked C boundary is explicitly stricter than calling upstream's clamping constructor or constructing its public struct directly. If clamping convenience is later useful, it needs a separately named operation and tests. In particular, keep hue 1 and latent hue on zero saturation/lightness. Pure checked conversions expose normalized float encoded RGBA separately from `cui_color` bytes. Named byte export is a lossy presentation boundary, not model ownership: use source-style truncation for the source display/export helper; leave legacy rounding conversion unchanged. Every conversion validates first and writes outputs only on success. New source-style hex parse/format functions use the picker grammar and float HSL conversion above. Formatter capacity includes NUL; report required payload length and make insufficient-capacity output atomic (unlike the legacy formatter's intentionally retained truncated-copy contract). Inputs and output storage must be disjoint. No locale-sensitive parsing. The owned state retains optional full-precision committed/preview values, ten-byte hex draft, editor, input view state, draft validity and dirty state. Zero-init and checked init; address-stable/noncopyable until idempotent destroy after render consumption, as with ColorEntry. No foreign-owned string pointers persist. Init and silent owner-sync copy the float selection directly and format its display without invoking hex-preview callbacks. Dirty owner-sync conflicts unless explicit replacement is requested; allocation/format failure preserves selection, draft, editor identity, history and preview. Successful replacement resets input history. Typed operations distinguish these paths: - **Set/admit hex draft:** empty or hash plus 0..8 ASCII hex digits in the actual field; pure parser may omit hash. Complete text parses to float preview only. Incomplete retains previous preview; invalid admission is atomic rejection. - **Commit hex draft:** parse current draft at that explicit operation, including unchanged display; complete result commits parsed float HSL. Same-value commits succeed/count. Incomplete never commits or requests close. Empty is incomplete, not an implicit clear selection. - **Preview HSLA:** validate and retain supplied float preview, format display without feeding it back into parsing, and leave committed value unchanged. Dirty draft replacement requires an explicit replace-draft decision. - **Restore preview:** restore committed optional value and display silently, without recomputing HSL through bytes. Distinguish preview restoration from owner-sync and from commit. - **Commit HSLA:** accept the supplied float color directly, for a future palette or slider owner. Distinguish SELECT (request close) from UPDATE (keep open) in the typed outcome. Formatting is derived display only; active slider values must not be rewritten by a display-feedback path. Explicit absence/clear is a separate owner operation, not transparent black. First implementation review must finalize names, return structs and the precise transactional allocation order before declarations. Do not implement two competing models by nesting byte ColorEntry and treating its bytes as authoritative. Reuse existing Input primitives and private acceptance logic only where their contracts fit; leave shipped ColorEntry source, structure and observer semantics unchanged. ## Events, acceptance and lifetime Pure model operations return typed outcome/selection/close-request facts; they create no fabricated frame or user-input metadata and call no UI observers. The new real Input facade uses existing per-event Input CHANGE/SUBMIT notifications internally, preserving queue order and explicit hex quantization. It does not rescan raw Enter, accept consumed/IME-owned keys, or add dispatch/capture policy. Disabled/readonly/passive frames cannot produce commit observations. Same-value commits and multiple accepted submits count independently of handler presence; incomplete attempts and admission rejection remain distinct outcomes. For consistency with ColorEntry, the external hex-field observer is one copyable summary after final semantics (Base) or paint (styled), with full-precision previous and final selections and completed/rejected counts. UNKNOWN source and actual eligible frame only; no invented input index or attribution of the whole summary to one activation. This is not a claim to emit every upstream entity event. Direct pure operations give their caller each result; future slider/palette UI must preserve per-accepted-operation evidence before choosing an outer summary. Freeze options and handler slots at submission entry. Payloads own scalar values; handler/user, labels and palettes remain borrowed until outer return. Callbacks can update a separate application owner for next submission, not mutate/free live entry, descriptors, active sliders or context, and cannot recursively submit UI. Teardown waits for draw consumption. Source close-before-Change timing belongs to a future popup coordinator: an accepted SELECT outcome must apply close before its outer notification. The model alone requests close and claims no actual popup. ## Staged implementation and required headless proof 1. Review and implement float primitives plus owned model and actual editable field. Compare source formulas/known vectors, not the legacy HSV converter. Test finite/range rejection (NaN/infinity/out-of-range), hue endpoints, achromatic latent hue, optional absence versus transparent, and preservation of supplied non-byte-aligned floats across sync, render, preview and restore. Formatting must not change those stored components or create commit callbacks. 2. Exercise all source hex widths/cases and malformed/incomplete/non-ASCII input; assert failure leaves outputs intact, capacities 0 through required+1 and guard bytes, exact opaque/translucent formatting, `.5 -> 7F`, and explicit unchanged-display Enter producing `127/255`. Check representative RGB/HSL sectors, black/white/grey, bounded conversion error and near-byte-boundary truncation. Do not assert universal bit-identical floating arithmetic or byte-exact parse/format round trips without evidence. 3. Test the actual field's pointer/caret/key routing and textbox name/readonly semantics, invalid admission, preview without commit, repeated/consumed Enter, same-value/multiple submits, text after Enter, disabled/readonly/passive frames, owner conflict/replacement/history behavior, copied payload lifetime and a real callback-driven next-submission owner example. Theme paint must leave floats and draft unchanged. Native AT announcements remain outside semantic snapshots. 4. Then review Palette/HSLA tabs: four normalized .01-step slider controls and source selected swatch semantics, with full-precision owner sync and no active slider feedback. Review popup trigger naming, focus, scoped Enter/Escape, disabled Confirm and open Cancel behavior, close ordering, and theme featured palettes separately before production. These must consume this float owner, not downgrade its selection through `cui_color` for state updates. Use strict C11/C++ header consumers, assertion-enabled Release fixtures, actual standalone and CUI_ALL compilation, and the invisible-Xvfb test wrapper with home-cache TMPDIR. Retain existing ColorEntry, Picker, Picker Events and Input regressions. No dependency installation or desktop test is required. Subsequent approved integration must regenerate source metadata, SDK/dist and consumer skill with explicit precision boundaries. Handwritten Python, Node/TypeScript, Go and Rust support needs separate typed owned-string/float APIs and language tests; copied SDK headers alone do not establish builder support. No eye-dropper service, full popup, tabs, theme parity or native AT parity is completed by this design. ## Exact first implementation contract (review gate) The following declaration-shaped API supersedes provisional naming above. Shared primitives live in `cui_color_hsla.h`, depending only on `cui.h`; the owned field API lives in `cui_color_hsla_entry.h`, including those primitives and existing Input declarations. Neither header depends on byte ColorEntry or Plot. ```c typedef struct { float h, s, l, a; } cui_color_hsla; /* Encoded, unpremultiplied channels; explicitly not Plot linear RGBA. */ typedef struct { float r, g, b, a; } cui_color_encoded_rgba; typedef enum { CUI_COLOR_HSLA_OK, CUI_COLOR_HSLA_INVALID_ARGUMENT, CUI_COLOR_HSLA_CAPACITY } cui_color_hsla_status; typedef enum { CUI_COLOR_HSLA_HEX_INVALID, CUI_COLOR_HSLA_HEX_INCOMPLETE, CUI_COLOR_HSLA_HEX_COMPLETE } cui_color_hsla_hex_status; typedef struct { cui_color_hsla_status status; size_t required; /* Payload bytes, excluding NUL; 7 or 9 for valid color. */ } cui_color_hsla_format_result; bool cui_color_hsla_valid(cui_color_hsla); cui_color_hsla_status cui_color_hsla_from_rgba(cui_color_encoded_rgba, cui_color_hsla *out); cui_color_hsla_status cui_color_hsla_to_rgba(cui_color_hsla, cui_color_encoded_rgba *out); cui_color_hsla_status cui_color_hsla_from_color(cui_color, cui_color_hsla *out); /* Explicit source-style truncating export, never updates a retained model. */ cui_color_hsla_status cui_color_hsla_to_color(cui_color_hsla, cui_color *out); cui_color_hsla_hex_status cui_color_hsla_parse_hex(cui_str, cui_color_hsla *out); cui_color_hsla_format_result cui_color_hsla_format_hex(cui_color_hsla, char *out, size_t capacity); typedef struct { bool present; cui_color_hsla color; } cui_color_hsla_value; typedef enum { CUI_COLOR_HSLA_ENTRY_OK, CUI_COLOR_HSLA_ENTRY_INVALID_ARGUMENT, CUI_COLOR_HSLA_ENTRY_CONFLICT, CUI_COLOR_HSLA_ENTRY_INCOMPLETE, CUI_COLOR_HSLA_ENTRY_ALLOCATION_FAILED, CUI_COLOR_HSLA_ENTRY_EDIT_ERROR } cui_color_hsla_entry_outcome; typedef enum { CUI_COLOR_HSLA_COMMIT_SELECT, /* Successful commit requests close. */ CUI_COLOR_HSLA_COMMIT_UPDATE /* Successful commit leaves open policy alone. */ } cui_color_hsla_commit_kind; typedef struct { cui_color_hsla_entry_outcome outcome; bool committed, close_requested; cui_color_hsla_value previous, value; } cui_color_hsla_commit_result; typedef struct { char draft[10]; cui_edit *edit; cui_input_state input; cui_color_hsla_value committed, preview; cui_color_hsla_hex_status status; bool dirty; } cui_color_hsla_entry_state; cui_color_hsla_entry_outcome cui_color_hsla_entry_init( cui_color_hsla_entry_state *, cui_color_hsla_value); void cui_color_hsla_entry_destroy(cui_color_hsla_entry_state *); cui_color_hsla_entry_outcome cui_color_hsla_entry_sync( cui_color_hsla_entry_state *, cui_color_hsla_value, bool replace_draft); cui_color_hsla_entry_outcome cui_color_hsla_entry_set_draft( cui_color_hsla_entry_state *, cui_str); cui_color_hsla_entry_outcome cui_color_hsla_entry_preview( cui_color_hsla_entry_state *, cui_color_hsla, bool replace_draft); cui_color_hsla_entry_outcome cui_color_hsla_entry_restore( cui_color_hsla_entry_state *, bool replace_draft); cui_color_hsla_commit_result cui_color_hsla_entry_commit_hex( cui_color_hsla_entry_state *, cui_color_hsla_commit_kind); cui_color_hsla_commit_result cui_color_hsla_entry_commit_value( cui_color_hsla_entry_state *, cui_color_hsla, cui_color_hsla_commit_kind, bool replace_draft); typedef struct { bool disabled, readonly; float width; /* Styled Input width; Base caller supplies layout. */ } cui_color_hsla_entry_options; typedef struct { cui_input_result input; bool submitted; /* Eligible active field submission, not an Enter count. */ bool draft_changed; size_t commit_count, rejected_commit_count, close_request_count; cui_color_hsla_hex_status status; cui_color_hsla_value previous, committed, preview; cui_component_event_metadata event; } cui_color_hsla_entry_result; typedef void (*cui_color_hsla_entry_commit_fn)(void *, const cui_color_hsla_entry_result *); typedef struct { cui_color_hsla_entry_commit_fn on_commit; void *user; } cui_color_hsla_entry_handler; cui_color_hsla_entry_result cui_base_color_hsla_entry( cui_context *, cui_id, cui_str name, cui_color_hsla_entry_state *, cui_color_hsla_entry_options, cui_color_hsla_entry_handler); cui_color_hsla_entry_result cui_color_hsla_entry( cui_context *, cui_id, const cui_theme *, cui_str name, cui_color_hsla_entry_state *, cui_color_hsla_entry_options, cui_color_hsla_entry_handler); ``` All required pointer outputs must be nonnull except parse's output, which may be NULL for validation. Present float values require finite normalized channels; absent optional values ignore their color and store zeroed color. Parse grammar and admission remain as specified above. Parse failure writes nothing. Conversion failure writes nothing. Format validates color and output arguments before any write: NULL with capacity zero is a length probe (CAPACITY with required 7/9), NULL with nonzero capacity is INVALID_ARGUMENT, and insufficient capacity leaves all destination bytes unchanged. Invalid format arguments return required zero. All input/output extents must be disjoint. No malloc is needed for primitives. Initialization requires a zeroed state; double init and use-after-destroy return INVALID_ARGUMENT. State members remain read-only to callers, address-stable and noncopyable. Init/sync/preview/restore/direct-value commit use this replacement transaction: validate state/value/mode and dirty conflict first; format the new display into a local ten-byte array; save the old owned draft locally; copy the candidate into the final owned buffer and allocate a fresh editor bound to that final address. No user callback or UI submission runs during this synchronous temporary buffer replacement. On allocation failure restore every old buffer byte and keep the old editor, selection/history, input state and float values. Only after allocation succeeds destroy the old editor, install the new editor, zero retained Input view state, then publish float/model fields. Destroy remains idempotent. These operations are forbidden during submission and before prior render consumption. There is no allocation after the transaction's publish point. Successful sync sets committed=preview=the copied optional owner value, sets the formatted draft/status and clears dirty. Preview replaces only preview/display and clears dirty, retaining committed. Restore applies committed to preview/display and clears dirty. Neither operation commits or invokes a handler. A dirty draft conflicts unless replacement was requested; even an equal owner value cannot silently erase a dirty draft. Set-draft uses editor's atomic whole-content operation, marks dirty, and parses complete text into preview only; failure leaves all model fields unchanged. It may preserve editor undo history, unlike replacement sync. Commit-hex validates kind, reparses the exact current draft regardless of dirty, and on COMPLETE publishes parsed committed=preview and clears dirty. It does not rewrite editor bytes/history while Input borrows them. Failure returns committed false/close_requested false and copied unchanged previous/value; incomplete has INCOMPLETE outcome, malformed state/text has INVALID_ARGUMENT. Direct-value commit uses the replacement transaction and copies the supplied floats, never hex-parsing their display. Successful SELECT sets close_requested true, successful UPDATE sets it false; both set committed true even for equal values. Neither changes or owns popup open state. Optional clearing occurs through silent owner sync only. The real hex field always uses SELECT for accepted Enter submits. Every successful submit increments commit_count and close_request_count, including same value; an incomplete accepted submit increments rejected_commit_count. Counts are bounded by the frame's input event count and independent of an installed handler. Close request count is evidence of requested policy, not completed popup dismissals. The inline field never closes a popup. A later popup coordinator must consume these requests before its own outer observer to match source close-before-Change timing; it must not pass an early inner observer through unchanged. `previous` snapshots committed at field entry; `committed` and `preview` snapshot the final model after ordered reduction. `draft_changed` tracks accepted text changes, not cursor motion or owner sync. `submitted` snapshots a valid active non-inert/non-layout-only submission with disabled/readonly false. Metadata kind is SUBMIT, target is field ID, source UNKNOWN, and HAS_FRAME is present only for that eligible submission; no INDEX/SOURCE/ACTIVATION flags are invented. Invalid arguments return input.error INVALID_ARGUMENT, submitted false and no metadata. An external observer is invoked once only when commit_count>0, after final Base semantics or styled paint. It receives the same copied summary returned to the caller. The handler and user are entry snapshots, borrowed through outer return. All previously stated mutation/reentrancy/render-lifetime restrictions apply. Production remains gated on review of this addendum. The first implementation must prove primitive reuse independently of the owned field, precision retention versus explicit hex quantization, transaction rollback, queue ordering and close request facts. Popup open ownership, HSLA sliders/tabs and foreign builders remain separate approved implementation slices, not declarations hidden in this model. --- ## ColorPicker source audit and additive proposal Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COLOR_PICKER_SOURCE_AUDIT.md # ColorPicker source audit and additive proposal Design checkpoint only. CUI baseline: `19e390c4`. Frozen reference: `87d10ae5e1299d1be18670a37570c5402f952e34`, inspected in `/tmp/cui-upstream-reference`. No production API or implementation is changed here. ## Authority and actual gap The frozen implementation is `crates/base/src/color_picker.rs` and `crates/component/src/color_picker.rs`, including their embedded tests; the website examples describe composition but do not override that code. CUI authority is `include/cui/cui_picker.h`, `include/cui/cui_picker_events.h`, `src/base/cui_picker.c`, `src/components/cui_picker.c`, and their event facades. The manifest's combined `keyboard/validation/theme` row is too broad to describe the remaining work. CUI already implements keyboard channel editing and themed painting. The genuine frozen-source gaps include editable validated hex drafts, separate preview and committed values, optional empty selection, popup trigger keyboard behavior, and the HSLA/palette tab presentation. These are not all one missing parser. An eye-dropper is not implemented in either frozen ColorPicker module; a repository search of frozen crates and website found no eye-dropper implementation. Native screen sampling is therefore a separate host capability, not evidence required to reproduce an upstream ColorPicker method. ## Frozen behavior ### Representation, entry, and notification timing The state owns `Option` committed value and preview, open state, active tab, an InputState entity, four SliderState entities, and retained subscriptions. HSLA channels are floating point; sliders use normalized ranges and step `.01`. An empty selection is distinct from transparent black. The pure internal hex parser accepts an optional leading `#`, lengths 3, 4, 6, or 8, and only ASCII hex digits. Short forms duplicate nibbles. Missing alpha means opaque. The actual text input has pattern `^#[0-9a-fA-F]{0,8}$`: it admits incomplete drafts but requires the hash, unlike the pure parser. No RGB function, CSS color name, decimal channel grammar, whitespace trimming, or arbitrary CSS parser is supplied. Formatting uses uppercase hex and omits alpha when opaque; float-to-byte conversion truncates (half alpha formats as `7F`). Input Change previews a valid draft and synchronizes sliders without committing. An invalid/incomplete draft leaves the previous preview and committed value unchanged. Enter attempts commit; invalid text does not close or commit. Selecting a palette color closes first, then updates value/preview, synchronizes input and sliders, emits Change, and notifies. Slider events update committed value and preview and emit Change while leaving the popup open. Slider feedback does not write back into the active sliders. Programmatic input writes have suppression to prevent feedback subscriptions from behaving like user edits. `set_value` and `clear_value` synchronize state without emitting Change. `preview_color` changes preview and input only; `clear_preview` restores preview from committed state. `update_color` emits without closing. Selection and update do not suppress same-value notifications. Thus upstream Change is not equivalent to CUI's aggregate net RGBA change callback. Initial default synchronization is deferred until render. Applications must retain the upstream entities/subscriptions. ### Keyboard and semantics The Base root is a Button role with expanded state and optional accessible name; an enabled supplied focus handle is a tab stop. In its ColorPicker key context, Enter toggles the captured open value through `on_open_change`. Disabled Confirm propagates. Escape while closed propagates; while open it stops propagation and requests close. Cancel has no separate disabled guard. This is scoped action routing, not a global scan of every Escape event. Swatches have stable independent focus handles, default RadioButton role, selected/toggled semantics, default hex names, and configurable tab participation. Disabled swatches omit interaction/focus listeners. Duplicate featured colors use slot IDs and remain separate focus stops. There is no explicit palette arrow-key grid-navigation implementation in these modules; do not invent one from the manifest. Slider and text editing also inherit their respective primitives. ### Theme and presentation The styled component provides Palette and HSLA tabs, preview and hex entry, optional visible/accessibility labels, field/compact triggers, placeholder, size, icon, and featured palette overrides. Default featured colors come from semantic theme colors. Other palette rows come from DEFAULT_COLORS. Theme tokens supply field borders, focus ring, foreground, muted placeholder, and radii; color tracks represent color values. Hovering a swatch previews on entry; its handler does not explicitly restore the preview on exit. No dedicated invalid/error status API or validation error message is present in this ColorPicker state/component. A future status UI must be identified as a CUI addition, not frozen parity. ## Current CUI behavior and proof already present CUI retains caller-owned RGBA bytes and `cui_color_state` (HSV, last color, initialization and drag bits). HSV brightness is not HSL lightness. Hue is degrees; conversion rounds channels. Replacing this state with HSLA or silently forcing eight-bit round trips would break existing behavior and lose upstream precision. The inline picker exposes hue, saturation/value plane, alpha, RGBA channels, and caller-supplied palettes. Arrow keys edit focused channels; Home/End reach limits. The plane uses Left/Right for saturation and Up/Down for brightness. Pointer capture retains dragging outside bounds; cancellation and disabled/readonly clear drag state. Palette selection preserves owner alpha when alpha editing is off. The legacy parser accepts only `#RRGGBB` and `#RRGGBBAA`; invalid input leaves the output unchanged. Its formatter's explicit alpha flag and required-length/bounded copy contract differ from upstream automatic formatting. Preserve both APIs. The styled picker paints after the Base reducer: themed surface, borders, focus, disabled text, discrete color tracks, palette and a read-only hex display. It has no editable hex field, popup root, optional empty value, preview/commit split, or HSLA tab. Theme changes must not be treated as selected-color edits. `tests/unit/test_picker.c` covers conversion/hex round trips, geometry, keyboard, palette, alpha preservation, captured plane dragging, disabled/readonly, and light/dark/high-contrast/terminal themes. `tests/unit/test_picker_events.c` compares Base/styled legacy and facade draw/state semantics, including net-zero edits, latent hue on black, owner synchronization, null handlers, passive frames and copied callback payloads. These are meaningful partial proofs, not popup/input or full platform accessibility evidence. Existing `*_color_picker_events` calls the legacy implementation once. Base observation follows reduction/semantics; styled observation follows painting. Only a net byte-color difference produces an observer call, with UNKNOWN source and actual frame metadata; same-color selection and within-frame net-zero edits are silent. Existing change_count counts delivered callbacks, not accepted input actions. Preserve this contract. Borrowed event payloads must be copied to retain them. A new entry/commit observer needs its own named result and must not retrofit these aggregate events into per-input evidence. ## Host eye-dropper and binding boundaries `web/gallery.js` already gates EyeDropper on secure context and browser support, opens it directly inside a trusted click, and owns AbortController/request identity. Completion validates exactly six hex digits, checks current component and disabled state, then calls `gallery_screen_color`. Route/disabled cleanup cancels outstanding requests. Stale completions cannot apply. `web/gallery.c` accepts bounded sRGB bytes and preserves alpha; the next picker submission synchronizes HSV. This is an external owner update, not a picker-input callback. `tests/web/test_browser.py` exercises this integration using mocked browser EyeDropper success, cancellation, malformed results, pending cleanup and unsupported availability. It does not prove real screen sampling, OS permission dialogs, or native backend support. No portable Core API should expose browser promises, platform handles, or pretend a host result contains pointer/key activation data. The bridge currently calls the legacy styled picker with alpha enabled, disabled state and width; it reports packed color changes through its existing callback. Python, Node/TypeScript, Go and Rust expose packed RGBA setters/getters and picker hit bounds. They do not expose this proposed draft/preview/commit model, source HSLA entities, popup entry, palette configuration, or portable eye-dropper service. Generated C headers in SDK bundles are not equivalent to handwritten builder support. Any later binding slice needs typed methods and owned UTF-8 strings, transactional validation, explicit callback lifetime rules and tests per language. ## Proposed cohesive additive slices (approval required) 1. **Validated hex entry and selection model.** Add a dedicated header and caller-owned state with explicit committed/preview presence and bounded draft storage, separate from `cui_color_state`. Add pure source-format hex operations under new names; retain strict legacy parser/formatter unchanged. Draft updates distinguish syntactically admitted incomplete text from a complete parsed color; no invalid draft overwrites the last valid preview or selection. Explicit commit, preview-clear and owner-sync operations have distinct results. Compose an actual existing CUI editable input, with valid Enter commit, not just a parser demo. Document the first slice's byte-RGBA precision limit; exact floating HSLA slider parity requires a separately reviewed representation rather than a hidden HSV substitution. Optional selection must remain explicit. 2. **Popup and source keyboard composition.** Build an additive styled facade using existing trigger, popover, focus and input routing, with explicit open ownership and palette selection/slider commit policy. Preserve the inline picker unchanged. Inspect accepted action routing before specifying Enter/Escape evidence; do not rescan consumed trigger events or introduce global Escape ownership. Match the source root's closed/open propagation and disabled Confirm distinction. Preview, commit, open-change, and aggregate byte-change events remain separate concepts. HSLA tab and source swatch semantics belong here only with genuine implementation and tests; otherwise document their omission. 3. **Theme/status and host integration.** Give the new facade explicit semantic theme presentation, optional featured palette, labels and empty placeholder. Draft validity feedback may be added as a documented CUI extension; no built-in arbitrary validator, veto engine, or source error taxonomy is implied. Keep async eye-dropper requests in hosts. A host can submit a validated owner value through a typed sync operation, with UNKNOWN origin unless actual evidence is supplied; absence of host support remains explicit. Do not bundle native screen capture or all five handwritten bindings into a C11 parser milestone. For implementation review, freeze selected value/options/handler slots at entry. Owned draft capacity, initialization/destruction, UTF-8/ASCII admission, overflow, and owner-sync conflict policy must be specified before code. Borrowed palette, labels and option strings remain stable until return, including callbacks. A callback may update the application model for its next submission, but may not mutate descriptors still borrowed for painting. Callback payloads contain copied values and bounded facts; no invented key, timestamp, input index or activation multiplicity. Define notification position relative to paint explicitly and test callback-driven owner changes. No new dispatch architecture is needed. ## Required implementation proof Use an isolated strict-C11 fixture through `scripts/test_local.py` with a private Xvfb and home-cache TMPDIR; compile public headers in C and C++. Test all 3/4/6/8 formats, optional hash versus UI admission, mixed case, incomplete drafts, invalid ASCII/non-ASCII/sign/space, bounded output and unchanged output on failure. Preserve legacy strict-parser and formatting tests. Include source truncation versus CUI rounding examples so precision is never accidentally claimed equivalent. Exercise the real editable field and frame lifecycle: typing previews without commit; invalid Enter stays open/unchanged; valid Enter commits/closes; palette selection and slider editing use their distinct policies; programmatic sync is silent; optional empty versus transparent selection; same-value and multiple accepted actions; disabled/readonly/passive frames; callback reentrancy and copied payload lifetime. Verify focus, named selected swatches, expanded state, popup Escape/Enter scope and propagation with preceding consumed actions. Compare legacy draw/semantics with all new opt-ins absent. Theme proofs should compare actual draw colors/geometry and semantic labels under existing themes while asserting value/draft stability. Headless semantic snapshots do not prove native AT announcements. Browser host tests should retain async stale, cancel, malformed and unsupported cases; real OS picking remains a separately reported manual/hardware boundary. Run existing picker and picker-event regressions alongside focused tests. Root registers tests and updates metadata, consumer skill and generated distributions after approved implementation; this checkpoint claims no additional completed parity. ## Approved first-slice API decisions The first implementation uses new `cui_color_entry.h` only; existing picker headers, HSV state, parser, formatter and events remain untouched. A public caller-owned `cui_color_entry_state` owns a ten-byte NUL-terminated draft buffer (`#` plus eight digits), an allocated `cui_edit`, and retained input view state. Zero-initialize before init; init returns failure transactionally; destroy is idempotent after successful initialization. The initialized state is address-stable and noncopyable because its editor borrows its buffer. Destroy only after frame render consumption. No state storage may be rebound during submission. Committed and preview values use an explicit `{present, color}` optional byte-RGBA value. Pure source-format parsing reports COMPLETE, INCOMPLETE (hex-only prefixes of unsupported short lengths), or INVALID; it accepts optional hash and writes the output only on COMPLETE. The real field additionally requires a leading hash (or empty draft), ASCII hex only, and at most eight digits. Disallowed edits are rejected transactionally by existing Input acceptance. Incomplete drafts remain editable and retain the last valid preview; they cannot commit. Empty draft is incomplete, not an implicit clear command. Explicit owner sync can clear selection. Owner sync takes an explicit replace-draft flag. A dirty draft conflicts unless replacement is requested; conflict or invalid arguments leave all model/editor state unchanged. Successful sync replaces draft with canonical uppercase bytes, updates committed/preview presence, and clears editor history through existing set-content behavior; it emits no UI callback. Canonical alpha is omitted only when opaque. Draft updates preview but never commit. A valid explicit commit copies preview into committed and clears dirty, including same-value commits; it does not rewrite editor text while Input is reducing events. Base and styled field facades use existing Input event reduction and its accepted, focused nonrepeated Enter submit notifications, not a second raw key scan. Internal change/submit observers update entry state in queue order, so text after Enter cannot retroactively change that commit. Multiple valid Enters produce a commit count independent of handler presence; incomplete submit attempts have a separate rejected-commit count. This count represents observed field submits, not every possible upstream activation. Disabled/readonly/passive submissions cannot commit. Pure model operations have typed outcomes; they do not fabricate UI events. The external handler is snapshotted by value and runs once only if at least one commit completed, after final semantics (Base) or paint (styled). Its pointer-free summary copies previous/final committed values and accepted/rejected commit counts; metadata is UNKNOWN with actual active frame only. It does not attribute the coalesced summary to one input index. The result reports counts even without a handler. Callback payloads may be copied; handler/user remain borrowed. Callbacks may update a separate owner model for next submission but may not mutate entry, input, context or borrowed label/options until return. Draft-change/preview status is available in the result, without inventing a separate source Change contract. The facade is an inline hex field with standard Input focus, selection, pointer, keyboard and semantic textbox behavior. It does not close anything and has no popup/open state, palette tab, HSLA sliders, or screen sampler. Before the next slice, review a float-HSLA optional selection representation (including conversion precision and source truncating formatter), popup action ownership/focus restoration, and palette/HSLA tab presentation. Byte RGBA is an explicit first-slice boundary, not the permanent replacement for those remaining frozen-source requirements. --- ## Combobox observer implementation checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMBOBOX_EVENTS_SLICE.md # Combobox observer implementation checkpoint Scope: Base and Styled single-selection Combobox, reusing immutable shared selection types and the [approved selection contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SELECTION_EVENTS_SLICE.md). Select/RadioGroup behavior stays unchanged; multi-selection and query/edit event facades remain outside this slice. Add `cui_combobox_event_result { cui_selection_event_result events; cui_combobox_result legacy; }`. New `cui_base_combobox_events` and `cui_combobox_events` match their legacy argument lists followed by `cui_selection_handler`. Missing observer preserves editing/selection and returns zero callback count. The typed payload captures actual `previous/value/item`; CHANGE notification is not an owner-rejectable request. ACTIVATION reason denotes selection confirmation, including Enter; it does not assert a Core activation snapshot. Append private observer/result parameters to the existing static Base combobox reducer. Legacy single/multi entry points pass no observer. The new Base wrapper initializes result bookkeeping and invokes that reducer once. At an existing Enter selection assignment, freeze actual frame/index/KEYBOARD facts, run the existing write/internal callback, capture the actual value, and notify only for a transition. Never synthesize HAS_ACTIVATION for this direct key path. Preserve single Enter loop break, later-text handling, filtering/scratch errors, matching count, query mutation and close timing. The Styled renderer gets optional private forwarding arguments; legacy calls supply none. New forwarding delegates once to Base events, retains that count, then uses the existing private Select list observer seam for the popup-list phase. No duplicate Base observation and no replay/sorting of events. Existing `.legacy.changed` assignments, including popup-path overwrite, remain exactly as implemented. Notifications count actual callback invocations even when the final legacy result collapses transitions or a handler changes owner state. Base input/query/Enter reduction precedes Styled popup-list reduction. Callback event indices can decrease across phases: retain truthful indices and phase order rather than promise global input-index order. Query-only edits, Enter without a matching candidate, navigation, external assignment and same-value confirmation emit no selection CHANGE. Genuine option activation snapshots are copied only if already available; otherwise retain real type/frame/index/source and omit HAS_ACTIVATION because list semantics normally register after reduction. Compound metadata target is the input; copied activation child target is unchanged. No early registration or Core routing change. Current OPTION accessibility ACTIVATE is unsupported; accessibility FOCUS is supported but does not itself synchronize the retained list cursor. Test those boundaries and explicit keyboard navigation, not invented successful activation. Callback users/storage/resources remain borrowed through existing active boundaries; copied payload is pointer-free. Owner writes/later consumption affect subsequent reducer work, not recursive events. Active teardown/context destruction/reentrant submission remains unsupported. No scheduler, request hook, lifecycle/submit/query event or bindings allowlist is added. Tests must exercise actual Base and Styled calls, independent query/selection ownership, both text-before-Enter and Enter-before-text cases, filtered-out selection, same-value confirmation, missing handler, scratch failures, pointer/touch and mixed-phase ordering, owner mutation/consumption, disabled/inert/omitted calls, explicit accessibility limits, payload lifetime and unchanged legacy choice regressions. Root owns registration/generation. --- ## Command observer slice: review checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMMAND_EVENTS_SLICE.md # Command observer slice: review checkpoint Status: proposal only; no new Command API is implemented by this document. Audited integration `ca50785b`: `cui_command.h`, Base rebuild/select/move/confirm, Styled inline palette and existing `test_command.c`. This refines the historical Command row in COMPONENT_EVENTS_COVERAGE, without changing its baseline. ## Existing ownership and timing The caller owns rows, query editor, state, entries, items and callbacks. Rebuild borrows entry/item pointers until the next rebuild. It installs rows and selection, then (for changed query) calls on_select if the resulting eligible path changed, then on_query with borrowed raw UTF-8. Initial/unchanged rebuild does not call those hooks. Select stores the row and pending-scroll policy before on_select. Move calls Select. Confirm snapshots row, on_confirm and user before invoking item.action, then invokes the captured on_confirm, even if the action changes selected state. Styled calls rebuild before geometry validation, renders/reduces query, rebuilds on aggregate input change, selects newly hovered rows, and selects then confirms an activated row after its paint. Footer runs before the keyboard loop. Keyboard arrows move, Enter confirms, Escape clears/rebuilds a nonempty searchable query; otherwise it calls on_cancel only when installed. Existing disabled/loading, consumption and focus behavior is operation-specific. A later false return may follow successful earlier mutation/callbacks. These facts must remain unchanged. ## Compatible contract and implementation slices Use a new header `cui_command_events.h` and additive observed entry points; existing public structs and functions remain ABI/source compatible. Implement private common reducer/render functions, with NULL observer on legacy paths. Do not wrap all of Command in a final-state diff, replace old option.user, or change the query to the per-input Input observer API: its current aggregate query callback timing is intentional compatibility behavior. 1. Base observed rebuild/select/move/confirm with pointer-free typed selected path snapshots (section,row), optional previous path and shared metadata; query callback borrowing raw UTF-8; ACTIVATE confirmation snapshot. Each exact pointer-free callback seam freezes payload before legacy callback, invokes that callback with original userdata, then invokes the borrowed observer. Borrowed query observation has the explicit ordering exception below. Confirm preserves action -> captured legacy on_confirm -> new ACTIVATE ordering and snapshot identity. Counts summarize actual observer calls, even if old callbacks subsequently redirect state. Programmatic entry points use PROGRAMMATIC without invented frame/input metadata. Explicit clear-selection remains an existing silent helper unless a separate observed variant is designed. 2. Styled observed submission threads a private observation context through the same reducers. Query notifications remain aggregate per actual rebuild. Pointer hover selection is CHANGE, with only actual known pointer evidence; accepted row activation uses unique genuine snapshots when available, otherwise frame UNKNOWN (no invented index). Keyboard loop has actual frame/index/key evidence frozen before old callbacks; Enter is ACTIVATE, eligible Escape cancel is REQUEST to dismiss, not proof of dismissed hosting surface. Existing option on_cancel presence controls the legacy path; the new cancel handler can enable only the additive entry point's cancel notification, without implicitly consuming Escape, closing an overlay, or clearing query. Disabled suppresses new UI interaction observations; loading retains old policy. Initial/passive model rebuild callbacks require an explicit PROGRAMMATIC classification and must not be mislabeled user input. Inert/layout-only submissions must not introduce UI interaction callbacks. Custom content/matches/binding remain separate contracts. Before production, the worker must refine exact type/function spellings, how new-handler-only selection/query notifications map existing callback predicates, and passive/inert behavior against actual source tests. Do not suppress existing legacy callbacks merely to impose new policy. Root reviews the refinement. ## Ownership, alternatives and limits Observer handler/user and payload views are borrowed for the outer operation. Copy paths/metadata by value and query through bounded UTF-8 copy for deferred work. No heap allocations, queue, propagation tree, deferred dispatch or generic veto. Pointer-free CHANGE/ACTIVATE/REQUEST follow their documented legacy seam; borrowed query CHANGE uses the explicit safe pre-hook exception below; acceptance, consumption and platform defaults remain independent. Do not destroy context/active resources or recursively submit UI during observers. Existing legacy callback-driven selection changes remain observable at their old timing; new observers may copy or set unrelated application flags and defer teardown. Appending callbacks to public options was rejected to preserve old layouts. End-of-frame replay loses ordering and mutations. Polling only the final selected row loses hover/keyboard multiplicity and action snapshot identity. Emitting a query event for each text edit would change legacy aggregate query timing. No Python/JS/Go/Rust bridge equivalence is promised: native synchronous callbacks, query-vs-selected-path values and action payloads are not current bridge V1 value categories. SDK distributions include the C headers; owning language facades remain explicitly omitted until their own protocol is designed. ## Verification and ownership Own new public header, Base/Styled Command, dedicated new headless tests, new guide and this checkpoint status only. Root owns CMake/WASI/source metadata, website, usage inventory, generated SDK/distributions/skill. Use isolated worktree. Compare legacy/new reducer state, callback order, mutation redirects, false-return progress and rendering. Cover repeated confirms/moves in a frame, query+selection ordering, action mutating selection before on_confirm, raw UTF-8 lifetime/copy, handler/userdata routing, disabled/loading/inert/passive/omitted components, pointer hover vs accepted activation, real keyboard and actual accessibility role eligibility. Verify counts never replay or mutate. Run warnings, portable C/C++ headers, private-Xvfb native tests and applicable WASI/sanitizers. Never use desktop. ## Refined review contract (audited `91fab8fc`) This section supersedes the provisional spellings/classification above. Production is still unapproved. No new public layout, behavior or generated file is changed. ### Exact additive API `cui_command_events.h` includes Command and shared component metadata. Proposed public declarations (all callbacks are user-first): ```c typedef struct { cui_component_event_metadata event; /* CHANGE */ bool has_previous; cui_command_index previous, value; } cui_command_selection_change; typedef struct { cui_component_event_metadata event; /* CHANGE */ cui_str value; /* Borrowed raw, untrimmed UTF-8; not an owned snapshot. */ } cui_command_query_change; typedef struct { cui_component_event_metadata event; /* ACTIVATE */ cui_command_index value; /* Confirmed snapshot, not later selected state. */ } cui_command_activation; typedef struct { cui_component_event_metadata event; /* REQUEST to dismiss host */ } cui_command_cancel_request; typedef void (*cui_command_selection_change_fn)(void *, const cui_command_selection_change *); typedef void (*cui_command_query_change_fn)(void *, const cui_command_query_change *); typedef void (*cui_command_activation_fn)(void *, const cui_command_activation *); typedef void (*cui_command_cancel_request_fn)(void *, const cui_command_cancel_request *); typedef struct { cui_command_selection_change_fn on_selection; cui_command_query_change_fn on_query; cui_command_activation_fn on_activate; cui_command_cancel_request_fn on_cancel; void *user; } cui_command_event_handler; typedef struct { bool control; /* Exact old bool return; false is not necessarily an error. */ bool count_overflow; size_t selection_count, query_count, activation_count, cancel_request_count; } cui_command_event_result; cui_command_event_result cui_command_rebuild_events( cui_command_state *, cui_id target, const cui_command_entry *, size_t, cui_str query, bool query_changed, cui_command_options, cui_command_event_handler); cui_command_event_result cui_command_select_events( cui_command_state *, cui_id target, cui_command_index, bool scroll, cui_command_options, cui_command_event_handler); cui_command_event_result cui_command_move_events( cui_command_state *, cui_id target, bool forward, cui_command_options, cui_command_event_handler); cui_command_event_result cui_command_confirm_events( cui_command_state *, cui_id target, cui_command_options, cui_command_event_handler); cui_command_event_result cui_command_events( cui_context *, cui_id, const cui_theme *, cui_command_state *, const cui_command_entry *, size_t, cui_command_options, cui_command_event_handler); ``` Base has no context/ID today; the explicit nonzero `target` provides metadata identity without retaining a context or inventing input provenance. Zero target is an additive preflight failure: zero result, no reducer call/mutation/callback. Other `control` values are exactly the old operation result. No `valid` or `submitted` field conflates no-change/invalid/late-error paths. Counts saturate with `count_overflow`, count only actual observer calls, and retain earlier calls when a later Styled operation fails. No public observed clear helper or Base cancel operation is proposed. Missing callbacks ignore `user`, including nonNULL. ### Callbackless predicates and frozen operation facts The observer removes only the old callback-presence predicate, never the reducer predicate. Keep old options callbacks and `options.user` unchanged; do not install forwarders into those fields. Each pointer-free old callback precedes its new observer. Borrowed query uses the ordering exception below. Freeze operation facts before the old callback so redirects cannot turn one operation into another. Observer snapshots describe the completed operation, not a promise that current owner state still equals the payload after legacy code. | Operation | Observer predicate independent of old callback presence | Order/facts | | --- | --- | --- | | Rebuild selection | Rebuild succeeds; `query_changed`; eligible selected path exists; no previous path or different path | Install all rebuilt rows/state, freeze previous/value, old `on_select`, new `on_selection` | | Rebuild query | Rebuild succeeds; `query_changed && options.searchable` | After rebuilt state/path snapshots are installed, new `on_query` BEFORE legacy select/query hooks; old `on_query` keeps its original position after the selection pair | | Select/move | Eligible item found and selected row index actually changes | Store selected/preserve/pending-scroll, freeze previous/value, old select, new selection | | Confirm | Existing confirm returns true: state exists, options not disabled, selected row/item exists and item enabled | Freeze selected row/path, action callback and old confirm/user as today; action, captured old confirm, new activation | | Styled cancel | Existing keyboard Escape branch reaches empty/nonsearchable query, enabled palette/focus, unconsumed unmodified KEY_DOWN; either old cancel or new cancel installed | Freeze REQUEST, old cancel if present, new cancel if present; no added consume/invalidate/host close | Important exclusions from these exact predicates: - `query_changed=false` rebuild may replace selection because an old row vanished or became disabled; it remains silent. `query_changed=true` need not imply different bytes in Base: it still reports query, even if the caller passes the same raw text. No selected-to-none event is invented when filtering yields no eligible item. `has_previous=false` makes `previous` absent (zero-filled). - Styled first submission computes `changed=false` because `initialized=false`, so its initial highlight is silent. In contrast an explicit Base rebuild with `query_changed=true` can notify even on an uninitialized state. The earlier blanket “initial rebuild does not call hooks” refers only to Styled/false flag. - Direct Base select/move do not check `options.disabled` or `state.loading`; preserve this policy. Confirm checks options/item disabled but not loading, and can activate without item action or legacy `on_confirm`. Same-item confirm is an ACTIVATE even when select first returned false. Repeated confirms are not deduplicated; pointer row interaction retains its existing aggregate coalescing. - Never add a selection-loss callback, infer query previous text, replace query aggregation with per-edit events, or make new handler presence enable movement, selection, confirmation, consumption or focus. Only cancel gets the explicit new-handler-only notification branch described above. ### Initial, passive and input classification | Actual seam | Metadata | | --- | --- | | Explicit Base operation, even called during a UI frame | PROGRAMMATIC, target only; no context/frame/index/activation invention | | Styled leading rebuild detecting an externally modified editor hash | PROGRAMMATIC, target only, including disabled/loading/inert/layout-only/out-of-frame attempts | | Styled initial or unchanged leading rebuild | Silent under the existing `changed=false` predicate | | Aggregate query-input changed rebuild | UNKNOWN plus proven active frame only; do not choose an arbitrary input event/index or claim per-edit origin | | Escape clear-query rebuild | Genuine keyboard frame/index/source from that loop event; CHANGE, no fabricated accepted activation | | Hover-selected row | UNKNOWN plus proven frame; aggregate/stationary hover does not establish a causal event index or activation snapshot | | Pointer/accepted row activation | Freeze before hover/select/content/binding callbacks; exactly one genuine accepted row activation supplies shared snapshot, multiple/missing evidence gives UNKNOWN plus proven frame only | | Keyboard move/confirm/cancel loop | Freeze current event frame/index/KEYBOARD before callbacks; attach genuine accepted activation only if actually available for this operation/target, never copy a different target's snapshot | All Styled targets are the Command root ID, while selection/activation payloads carry exact section/row paths. Remapped accepted row evidence retains the actual row target in `activation.target`; the root `event.target` is the owning Command. Do not manufacture keyboard accepted snapshots for an Enter handled by the palette loop when the accepted target is its query editor or nothing. Only the leading externally changed rebuild is PROGRAMMATIC; a passive submission is not universally silent. It still rebuilds before Styled focus/container and geometry checks and may call old select/query hooks, so the new programmatic observers must also run there. This includes disabled palettes and inert/layout-only ancestry; suppressing those observers would lose actual model changes. Conversely, interaction observations require nonzero `cui_frame_sequence(ui)` at their seam: Core returns zero under inert/layout-only/measurement/out-of-frame work. Do not add guards that suppress legacy callbacks/mutations merely to impose this observer policy. Loading does not block existing nonempty-row navigation/confirmation; retain it, rather than treating busy as disabled. Omitted submission emits nothing. ### Mutation, query lifetime and failure details Capture accepted row evidence immediately after interaction/current semantic registration and before hover selection or custom content/binding execution. The later confirm operation freezes the **actual selected row at confirm entry**: a legacy select callback may redirect it, and a content callback may change state. Do not overwrite that confirmed path with the clicked row. If it differs, retain only causal evidence that genuinely establishes origin, not an invented accepted activation for the redirected item. Confirmation must snapshot its old confirm callback/user before action, exactly as Base currently does; an action changing selection does not change the ensuing captured confirm/typed activation path. New observers must not mutate active state/editor/model/resources, recursively invoke the same UI/reducer, or destroy context; legacy permitted redirects remain. **Query-only ordering exception, requiring root review:** invoke the new query observer after all rebuild state and selection facts are installed/frozen, before the first potentially mutating legacy selection/query hook. Exact order when all are eligible: new query -> old select -> new selection -> old query. If no select transition is eligible, this reduces to new query immediately before old query. Old select -> old query order, state installation, and their original argument values remain unchanged; new observers cannot mutate active state/resources. Placing the new query immediately after old query is unsafe: legitimate legacy `on_query` can edit the editor and reallocate its backing store. Placing it only immediately **before** old query, but after old select, is insufficient for callbackless observation: legacy `on_select` can replace the raw storage while `on_query` is NULL; the old implementation then never reads the raw query again. Installing a new query observer there would introduce a new dangling-view read. The proposed uniform pre-hook position avoids both hazards with no allocation, workspace, refetching/reinterpreting query, or new legacy callback constraints. The query view is exactly the original raw untrimmed rebuild argument, borrowed only during the new callback, before legacy mutations. Never dereference the saved view after either legacy hook returns. Observers needing retention call `cui_component_event_copy_utf8` with explicit bound/storage and check its status; struct copy alone is insufficient. Legacy on_select still has its **existing** obligation to leave the raw argument valid if legacy on_query will subsequently read it; this slice neither repairs that pre-existing ordering nor extends that obligation when legacy on_query is absent. Legacy query editing/reallocation and select redirects remain supported at their original times. No hidden snapshot, owned-byte or post-hook view promise is made. Root must approve this earlier query exception (or separately design explicit bounded caller snapshot workspace) before production; a pointer freeze alone is not an acceptable solution. Selection/activation/cancel payloads are pointer-free copies and survive context teardown. All callbacks/users borrow only through the outer operation. Leading rebuild can notify and install new rows before density/geometry validation returns false. Input rebuild can notify before a custom measure failure. Retain that progress and counts; do not attempt rollback, withhold notifications until return, or relabel `control=false` as no work. Escape currently ignores rebuild's bool before updating hash/consuming; preserve that legacy sequence and report only actual successful reducer callbacks. No architecture/dispatch/teardown fixes here. ### Evidence and independently reviewed implementation sequence 1. Base only: shared types + four observed operations/private seams and tests. Verify callbackless predicates, explicit changed=true initialization, silent changed=false selection replacement/loss, select/move disabled policy, confirm without action/hooks, redirects and action snapshot, raw query/copy bounds, counts/zero-target failure and unchanged old bool returns. Add a legacy query hook that grows/reallocates its editor after the new observer copies the view, plus a legacy select hook doing the same with old query absent. Assert old callbacks retain their relative order and no post-hook view is accessed under ASan. Cover old query present/select redirect with the same original raw-view obligations, without silently forbidding legacy edits. No Styled activation claim from this slice. 2. Styled submission: same private reducers with scoped cause contexts; leading programmatic rebuild, aggregate query, hover/row confirm, keyboard/cancel. Compare old/new paint/semantics/focus/consume and callback traces, including nil legacy hooks, old hooks consuming input/changing selection, stationary hover, actual accepted pointer/accessibility eligibility, repeated keyboard confirms, disabled vs loading, inert/layout-only/measurement and omitted work, changed editor before passive submission, late custom geometry failure. Source anchors: [Base rebuild](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_command.c#L83) installs state then select/query at lines 172–178; [select/move/confirm](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_command.c#L181) show selection predicates and captured confirm at 223–228. [Styled entry](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_command.c#L76) rebuilds before geometry; aggregate query at 163–180, hover at 228–232, accepted row at 291–295, footer then keyboard at 309–335. [Core frame identity](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/core/cui.c#L4463) excludes inert/layout-only work. Existing [model tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_command.c#L40) cover callback ordering, clear/preserve, filtering/disabled selection and capacity; [render tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_command.c#L165) cover stationary hover, click focus, Escape and disabled consumption; [slots/loading](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_command.c#L392) cover presentation/busy, not suppression of confirmation. Existing tests do not prove legacy action redirects, passive observer classification or new metadata; the new focused tests above must supply that proof. No builds run for this checkpoint and no foreign binding coverage is claimed. ### Base implementation checkpoint The independent Base slice implements only rebuild/select/move/confirm event entrypoints, selection/query/activation payloads, handler fields and counts. Cancel types/handler/count and Styled declaration are deferred until that slice is approved; no reserved silently ignored public field ships here. Early query exception is implemented after installation/all path snapshots and before legacy hooks. Actual editor detach/realloc/recreate regressions cover oldselect with oldquery NULL and oldquery itself, with observer-owned copies before either edit; ASan additionally checks allocation actually moved. Legacy-only/new paired traces preserve redirects, action identity and old bool/state semantics. No Styled, Core, dispatch, build wiring, generated SDK or binding edits in this slice. ### Styled implementation checkpoint Implemented independently after Base review: private cause context shared through `src/base/cui_command_events_private.h`, with globally unique `cui_command_events_private_*` seams for amalgamation. Public Base entrypoints still create only contextless PROGRAMMATIC observers. Styled uses the same actual reducers once, preserving early query ordering, legacy paint/callback/focus/consume, leading passive PROGRAMMATIC rebuilds and late-error progress. Added implemented cancel type/field/count and Styled declaration, no reserved field. Focused paired tests cover keyboard multiplicity, aggregate query/clear/cancel, custom content consuming pointer evidence, legacy selection redirects and actual confirmed identity, unique/ambiguous row activations, actual OPTION accessibility FOCUS/ACTIVATE eligibility, disabled/loading/inert/layout-only, leading and input rebuild notifications before geometry failure. Existing Base realloc regressions remain in the same strict/sanitizer test. No Core/dispatch/role/wiring/generator or foreign schema changes. Root must inline the new private header in amalgamation. --- ## Proposed activation and discrete-value event slice Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_ACTIVATION_SLICE.md # Proposed activation and discrete-value event slice Status: design only, based on `71b72f96`. No declarations below are shipped or approved by this document. Read the [contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_CONTRACT.md), [78-family inventory](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_COVERAGE.md), [bindings audit](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_BINDINGS.md) and [implemented metadata utility](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMPONENT_EVENTS.md) together. Preserve all 78 families. This slice covers direct portable C Button, Checkbox, Switch and Toggle only, not groups, binding requests, continuous editing or global routing. ## Source facts and compatibility decisions | Control | Existing observable behavior | Consequence for this slice | | --- | --- | --- | | Button | [`cui_button_ex`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_components.c) freezes each click payload, invokes legacy `on_click` then `on_click_event` per accepted event, then paints. Hover metadata/callback work precedes click iteration. Disabled/loading block activation. Inert/layout-only ancestry paints without normal lifecycle mutation. | Adapt the existing per-event typed callback; preserve both old callbacks and their order. Reuse its already-frozen `evidence`, not a new lookup after legacy callbacks. | | Checkbox | [`cui_base_check_ex`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_base.c) snapshots the value and requested tri-state once per call, iterates accepted events and invokes requests individually. Callback controls acceptance; missing callback with `controlled=true` is read-only. Source Styled checkbox suppresses pointer focus; Base defaults to pointer focus. Legacy simple Checkbox still uses aggregate mutable behavior. | New by-value controlled facade can reuse extended Check with local snapshot and forwarding callback. Preserve mixed -> checked, snapshot-once multiplicity and source/Base focus differences. Leave all legacy functions unchanged. | | Switch | [`cui_switch_ex`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_components.c) calls legacy Base binary reduction on a local bool, then emits at most one aggregate `on_change`; it reads the external owner value again for semantics and painting after that callback. | A new per-event request API cannot be a wrapper around that callback. Add a separate Base reducer and split out paint-only Styled composition without changing the old path. New snapshot behavior must be explicit. | | Toggle | [`cui_toggle_ex`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_components.c) likewise collapses activation to one local bool request; paint-only `cui_toggle_paint` already exists. | New Base request reduction plus existing paint is feasible. Never silently upgrade the legacy aggregate callback to per-event dispatch. | Evidence tests inspected, not rerun for this documentation-only change: [Button event multiplicity](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_button_callback_events.c), [Button evidence snapshots and mutation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_button_click_snapshot.c), [Button passive lifecycle](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_button_passive_lifecycle.c), [Checkbox controlled/source contracts](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_checkbox_source.c), and [controlled siblings](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_controlled_siblings.c). Existing test coverage is not a general reentrancy or teardown guarantee. ## Exact additive declarations proposed Put typed request/activation declarations and Base entry points in a new `cui_control_events.h` depending on Base and the existing shared metadata header. Styled declarations belong beside existing component entry points in `cui_components.h`. No platform types or component dependency in Base. These handler types contain context pointers, never untyped value payloads: ```c typedef void (*cui_component_activation_fn)( void *user, const cui_component_event_metadata *event); typedef struct { cui_component_activation_fn callback; void *user; } cui_component_activation_handler; typedef struct { cui_component_event_metadata event; /* kind REQUEST */ bool current, requested; } cui_component_boolean_request; typedef void (*cui_component_boolean_request_fn)( void *user, const cui_component_boolean_request *request); typedef struct { cui_component_boolean_request_fn callback; void *user; } cui_component_boolean_handler; typedef struct { cui_component_event_metadata event; /* kind REQUEST */ cui_check_state current, requested; } cui_component_check_request; typedef void (*cui_component_check_request_fn)( void *user, const cui_component_check_request *request); typedef struct { cui_component_check_request_fn callback; void *user; } cui_component_check_handler; typedef struct { bool valid, submitted, count_overflow; size_t activation_count, request_count; } cui_component_action_result; typedef struct { bool disabled, skip_tab, no_pointer_focus; int tab_index; } cui_boolean_event_options; cui_component_action_result cui_base_check_events( cui_context *, cui_id, cui_str name, cui_check_state value, cui_check_options, cui_component_check_handler); cui_component_action_result cui_base_switch_events( cui_context *, cui_id, cui_str name, bool value, cui_boolean_event_options, cui_component_boolean_handler); cui_component_action_result cui_base_toggle_events( cui_context *, cui_id, cui_str name, bool value, cui_boolean_event_options, cui_component_boolean_handler); cui_component_action_result cui_button_events( cui_context *, cui_id, const cui_theme *, cui_str name, cui_button_options, cui_component_activation_handler); cui_component_action_result cui_checkbox_events( cui_context *, cui_id, const cui_theme *, cui_str name, cui_check_state value, cui_checkbox_options, cui_component_check_handler); cui_component_action_result cui_switch_events( cui_context *, cui_id, const cui_theme *, cui_str name, bool value, cui_switch_state *, cui_switch_options, cui_component_boolean_handler); cui_component_action_result cui_toggle_events( cui_context *, cui_id, const cui_theme *, cui_str name, bool value, cui_hover_state *tooltip_state, cui_toggle_options, cui_component_boolean_handler); ``` All value arguments are immutable per-call snapshots. A callback may assign the application's external value, but the new call keeps its original snapshot for subsequent requests, semantics and painting. The next submission observes the owner assignment. No getter hook, borrowed model pointer, hidden retained value, application acceptance bool or synthesized CHANGE notification is introduced. A future same-call owner-readback API would be a separate decision, not an undocumented callback effect. For Check options, `on_change` and `change_user` must be NULL; likewise the old change callback/user fields in Checkbox/Switch/Toggle options. Reject conflicts before submission with `valid=false`; never silently discard or double-dispatch value handlers. Check's `controlled` setting is superseded by the immutable signature; this entry point is always controlled. Styled Checkbox always selects existing source focus behavior, regardless of `source_behavior`; Base preserves its supplied `no_pointer_focus`. Other appearance, required/invalid, role, slot and tab settings retain their documented meanings. Button may retain legacy click callbacks for migration. New dispatch order is existing hover processing, then for each accepted event: freeze existing payload, legacy click, old typed click, new metadata handler; then existing paint/tooltip work. Forward original `action_user` independently from new handler user (including hover), and preserve artwork descriptor snapshotting. Document one side-effect path as recommended; using both handlers is an explicit migration/debug choice. No new hover metadata API is needed here. ## Result, timing and request rules `valid` means arguments/options passed preflight; it does not promise that later rendering cannot fail. `submitted` means ordinary active submission was reached, including a disabled control; it is false outside submission or in inert/layout-only ancestry. Passive visual composition may still occur. No result claims that an external owner accepted a request. `activation_count` counts supported accepted activations observed by this invocation, in original Core event-index order. `request_count` counts actual typed request callback invocations (zero for Button). Both use saturating `size_t` increments with a shared overflow flag; counts are per invocation, not accumulated across frames. Callback delivery continues in reducer order on counter saturation. Result reads are passive. Do not add an event log or last-value field to this small slice. Each accepted event invokes Button's new handler once when present. Each accepted Check/Switch/Toggle event proposes the same inverse of the entry snapshot; mixed Check proposes checked. For two accepted activations in one call, both controlled requests carry the same current/requested pair, even if the owner accepts the first. This matches extended Check's current snapshot rule, while the old aggregate Switch/Toggle functions retain their single callback. Never derive per-event identity from aggregate `cui_interaction.activated`. A missing request callback is read-only: no mutation and no request dispatch, but accepted activation count may still report an attempt, as existing controlled Check's bool does. Do not claim rejection unconsumes input or permits parent activation. Disabled and inert controls emit no user activation/request callbacks; Button loading has the same suppression. Switch, Toggle and Checkbox gain no invented loading state. Omitting the call emits nothing. No new commit, submit or lifecycle events are manufactured for discrete toggles. Metadata uses `cui_component_event_from_activation` on a genuine frozen snapshot; Button uses existing payload evidence. Do not fabricate a pointer for keys/accessibility or reconstruct evidence after mutable callbacks. Payload pointers, handlers and users are borrowed during synchronous submission only; request/metadata structs are pointer-free and may be copied by value. Appearance resources/state keep existing longer lifetimes, including deferred label paint. There is no callback registration or end-frame queue. ## Implementation boundaries and the teardown decision Smallest independently reviewable order: **(1) Button and Check**, using existing per-event seams; **(2) Boolean Base reducer and Toggle**; **(3) Switch paint extraction and facade**. Do not implement all four with an aggregate callback adapter. Proposed ownership for a later implementation approval: new control-events header, narrow additive declarations in Base/Components headers, Base event reducer source, Components forwarding/paint extraction, dedicated unit fixtures, guide and integration example. Root retains CMake/module/export/binding/generator ownership. The new Boolean Base reducer must register each role's normal semantics/focus policy once, iterate accepted snapshots without duplicate reduction, then preserve controlled snapshot semantics. Do not implement it by publicly calling Check with a different role: Check adds required/focusable/pointer-activation details and has a distinct disabled-parent behavior. Share private accepted-event iteration only after semantic-policy tests establish equivalence. Extract Switch painting mechanically and prove the old mutation/callback-before-paint sequence unchanged. Callback mutation supported here: change unrelated application state or the owner's external value, request view removal/close in application state, and omit later siblings through ordinary caller control flow. Descriptors are passed by value; changing the caller's descriptor affects later invocations only. Active state/resources/users/labels must remain alive through their existing boundary. Consuming later events can change their later eligibility; do not pre-queue every future callback merely to simplify iteration. **A reliable context-destruction guard is not feasible in a facade-only slice.** [`cui_destroy`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/core/cui.c) calls `cui_core_mutation`, whose guards cover diagnostic/measurement/prepaint phases, not arbitrary ordinary component callback execution. It can free the context while a submitting component still holds it. A local `busy` flag or checking frame sequence after return cannot detect that safely; reading the freed context would itself be invalid. Different wrapper workspaces also cannot enforce per-context recursive-entry safety. Recommendation: keep recursive same-component submission, recursive frame entry, destruction of the active context, and freeing active storage explicitly unsupported preconditions in this slice, as the committed contract already states. Do not advertise a runtime guard. The application marks pending teardown and performs it after submission/frame completion. If root requires deterministic rejection or deferred teardown instead, stop before production implementation and authorize a separate Core-owned per-context dispatch-depth/destruction design, with legacy compatibility tests. Bridge runner deferred destruction is not a portable Core guarantee. No test should deliberately execute undefined use-after-free and count a non-crash as proof. ## Required proof before integration - Multiple accepted pointer, touch, Enter, Space and accessibility events: callback order, exact count, no repeat/cancel activation, real frozen metadata and retention after context destruction performed **after** frame completion. Pointer clicks preserve raw contact/device evidence. - Button migration trace: hover, legacy click, old typed click and new callback order; separate old/new users; legacy callback consumes accessibility input or mutates artwork descriptors; new metadata remains frozen. Run existing click snapshot/artwork/passive lifecycle tests unchanged. - Controlled value owner accepts/rejects and changes unrelated state; current/requested remain entry snapshots through several events; no hidden writes, CHANGE notification or duplicate frame-result effects. Missing handler is read-only; conflicting old/new request handlers fail before semantics, callbacks or paint. - Check mixed transition, Base versus source pointer focus, required/invalid/role override/tab order/indicator slots and disabled parent bubbling. Run source Checkbox and controlled-sibling suites unchanged. - Boolean role semantics, disabled parent routing, focus/tab/keyboard/a11y policy and occlusion match each family, rather than inheriting Check behavior. Legacy Switch/Toggle still dispatch once for multiple accepted events; new facades dispatch once per accepted event. - Disabled/loading/inert/layout-only/outside-frame and measurement/prepaint calls: zero event callbacks/counts, correct submitted flag, preserved passive state behavior. Failure preflight leaves caller values/state untouched. - Mutation requests remove a later sibling or schedule application close; no handler retains freed userdata, removal happens only after the active call returns, and teardown occurs after frame completion. Recursive misuse is documented unsupported unless the separately approved Core guard exists. - Counter saturation helper tests without fabricating a huge event allocation; returned result copies never redispatch. Strict portable C11 builds and meaningful CTest through the invisible wrapper; browser tests stay headless. No changes to bridge queued notification timing or false binding coverage claims. Human/LLM guide and generated resource/index updates must accompany an approved implementation, plus one real owner-accept/reject example. These additions do not provide synchronous rejection through existing language bindings; that remains separately reviewed work. --- ## Component events: bridge and binding audit Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_BINDINGS.md # Component events: bridge and binding audit Status: read-only source audit, not an approved event design or a completion claim. Baseline: `integration/next39-components`, commit `e9d2c1a561ced3254e606b0206f412af8b156317`. This addresses the binding boundary of [the request](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_REQUEST.md); the separate family matrix owns all 78 families. No production, generated SDK or manifest changes accompany this document. Tests below were inspected, not rerun for this documentation-only audit. Their existence is evidence of intended coverage, not a fresh pass report. ## Implemented additions since the checkpoint [Shared metadata](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMPONENT_EVENTS.md) and the direct C [Button/Check facades](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CONTROL_EVENTS.md) are implemented after this audit. Button preserves legacy callback order and adds typed activation metadata; Check offers immutable typed requests with per-invocation counts. These are submission-borrowed synchronous handlers. The original rows below remain the checkpoint baseline, not an assertion that later additions are absent. No Python, JavaScript/TypeScript, Go or Rust wrapper for these synchronous handlers is implemented; owning manual queued views were added later. See the current dated snapshot below. Original sections retain their historical scope. ## What exists at the C boundary The canonical public ABI is [cui_bridge.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_bridge.h). `cui_bridge_event_ex` has an event discriminator (`CLICK`, `CHANGE`, `CLOSE`), origin node slot/generation, `uint64_t frame_sequence`, `uint32_t checked`, `double value`, text length and selected node slot/generation. Text is copied separately into the caller's buffer. There is no public per-component C callback registration in this bridge; applications poll queued events. `cui_bridge_run`'s callback is an after-frame host hook, not a component event callback. [The bridge implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/bridge/cui_bridge.c) owns retained node records and component state, including edit models, checked/value fields and selection/surface state. Language builder objects retain references and initial properties; mounted readback uses C getters. The ordinary checkbox, switch, toggle and slider bridge paths call mutating legacy C component facades, update the bridge-owned value and then call `bridge_change`. Input/editor paths inspect `result.changed`. This is a **confirmed post-mutation notification**, not a controlled proposed-value request. Registering no language callback does not prevent the underlying mutation. Callback returns cannot veto it. Native source-controlled C component facades are not automatically exposed by these bridge paths. `bridge_click` uses `cui_button_options.on_click_event`, queues an event per accepted button callback and ignores the component's returned aggregate boolean. The bridge input path does not forward native `cui_input_result.submitted` (see [cui_base.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_base.h)); no shared SUBMIT channel exists. Slider begin/update/commit/cancel phases are likewise not represented by the bridge's single legacy value-change channel. Other paths translate their particular result flags into notifications; a `CHANGE` is not a universal one-to-one record of raw input events. Dialog close uses `bridge_surface_close`, putting accepted/cancelled/closed in `value`. That is a surface outcome; it does not implement event acceptance, propagation stopping or platform default prevention. The event payload is a generic record, not a typed union: | Meaning | Current representation and limits | | --- | --- | | Button activation | `CLICK`, node, frame. No origin/evidence payload survives. | | Boolean / numeric state | `CHANGE`, `checked` / `value`; applicability depends on node kind. | | Editable text | Copied UTF-8 snapshot in `text`; it can differ from the latest getter after later frames. | | Selected item | Full selected slot/generation snapshot for supported selection paths; not an owning node reference. | | Surface outcome | `CLOSE`, numeric `value` 1 accepted / 2 cancelled / 3 closed. | | Time, color, date | Formatted text and/or numeric fields, plus separate typed state getter APIs. Not typed date/time event variants. | | Data table / questionnaire | Component-specific JSON text plus overloaded generic fields. `bridge_data_table_change` stores the column in `checked` and row in `value`. | These are actual adapters, not a promise that every family emits every channel. Some explicit programmatic commands also enqueue events (for example questionnaire/speech/dock paths); do not assume all setters are event-free or that every setter produces a notification. Audit the particular setter before specifying compatibility. ## Timing, ownership and event evidence `cui_bridge_step` sets `stepping`, polls native input, builds the C frame, ends it, renders SDL if applicable, then returns status. Component callbacks used by the bridge run during frame construction but only enqueue snapshots; foreign language callbacks are invoked afterwards. A callback's state update can affect later callbacks/getters immediately, but is painted by a subsequent step. It cannot retroactively change the frame just rendered. The queue is FIFO **in enqueue order**. Components are visited in scene traversal order and can aggregate their own input. Neither FIFO nor `frame_sequence` promises global chronological ordering across components. Multiple events can share a frame; no event index is exported to recover their original input order. The bridge defaults to 256 event slots, allows at most 4096, and reports `CAPACITY` on queue exhaustion. Snapshot text uses owned heap allocations; allocation can fail with `OUT_OF_MEMORY`. There is no allocation-free handler contract. Rendering paths can mutate state before an enqueue failure: step failure is not a transaction that rolls back component state or old queued events. Some explicit commands preflight capacity separately. `cui_bridge_poll_event_ex` copies a snapshot and consumes it once. On insufficient buffer it reports required capacity and leaves that event queued. It frees internal text on consumption, stale-origin discard or app destruction. The caller owns copied text/output storage. The legacy `poll_event` consumes and discards all non-CLICK events while searching for a click; mixing the two poll APIs loses notifications. Polling/readback never invokes language handlers. Calling a language dispatcher after manual polling cannot replay consumed events. Origin handles are generation-checked; removing an origin causes its queued events to be skipped. A selected handle is a historical value and can become stale independently. Removing a subtree does not mean every language closure capturing a former child is immediately released; retention differs below. [Native C button snapshots](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h), `cui_button_click_event`, already include origin, target, event index/type, key/modifiers/repeat, pointer position/type/button/device/ID/click count and a copied `cui_activation_snapshot`. `bridge_click` preserves **only node and frame**. Therefore keyboard/pointer interaction tests do not prove evidence export. Accessibility-specific queuing/evidence is not a shared public bridge event API. Never infer origin, pointer coordinates, timestamp, trusted status or modifier state from the sparse bridge event or current global input. ## Language interfaces actually implemented | Boundary | Dispatch and handler shape | Payload / ownership | | --- | --- | --- | | Python [canonical module](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/python/cui_bridge/__init__.py) | `App.step()` only steps. `poll_events()` consumes snapshots; `dispatch()` calls `Widget.on_click/on_change/on_close` handlers. `run()` dispatches from native after-frame hook. | Frozen `Event` dataclass, `type: str`, widget reference, integer frame, bool checked, float value, copied string, selected handle tuple. One stored callable per channel; new registration replaces it. Return object ignored. | | JS [index.cjs](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/node/index.cjs) and [addon](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/node/addon.c) | `App.step()` steps **and dispatches**. `_dispatch()` is internal; `run()` dispatches after each native frame. `start(fps)` is a separate timer/manual-step loop. | JS event objects vary by channel: click `{node,frame}`, change adds checked/value/text/selectedHandle, close adds result. Stored closures live on nodes; returns ignored, promises not awaited. | | TypeScript [index.d.ts](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/typescript/index.d.ts) | Declarations over the JS implementation, not another runtime. Interfaces restrict supported builders/methods and declare callback returns `void`. | `ClickEvent`, generic `ChangeEvent`, `CloseEvent` with result `1 \| 2 \| 3`. Change payload is not discriminated by component/value kind; no static request/notification distinction. | | Go [native.go](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/go/cui/native.go) | `Step` and `PollEvent`/`Dispatch` are separate. `Node.OnClick/OnChange/OnClose(func(Event))` store functions. `Run` dispatches through the native runner. | Value `Event` owns Go string and scalar copies, references `*Node`, includes Type, Frame, Selected, raw SelectedHandle and CloseResult. Callbacks have no return decision. | | Rust [lib.rs](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/rust/src/lib.rs) | `step` and `dispatch` separate; `frame` combines them. `on_click` is a no-payload `FnMut()`; `on_change` also has a no-payload convenience form, while `on_change_event/on_close_event` take `&ChangeEvent`. `run_with` adds an after-frame app hook. | Callback map keyed by raw node/channel, `Rc>>`, closures `'static`. Payload owns String and copyable Node tokens; handler borrows payload only for the call, clone if deferring. `checked_raw` preserves the full C integer, unlike boolean conversion. | Python's type hints/dataclass are not runtime component-specific payload typing. JS uses runtime kind checks; TypeScript adds compile-time interface restrictions, not runtime validation of all event payload meanings. Go has one general Node builder with sticky builder errors and runtime kind checks. Rust's Node token checks app identity and C validates generation on operations; callback registration itself does not validate that the node kind can emit that channel. A successfully registered callback is not proof an event will ever be emitted. C `checked` is converted to bool in Python, JS and Go. For the data-table column overload this loses the raw integer; JSON text still includes the column and Rust also exposes `checked_raw`. This concrete mismatch rules out treating the current generic record as a lossless typed schema. Rust's `surface_result()` decodes numeric value, not an independently discriminated surface event. JS frame IDs are converted from uint64 to Number, losing exactness above `2^53-1`; Python, Go and Rust retain integer-width precision appropriate to their representations. All four runtimes use a 4097-byte event text buffer rather than implementing arbitrary poll-capacity retry. This matches present common text bounds, not an extensible payload-size guarantee. If future payloads grow, a capacity error can leave the event queued until a capable consumer drains it. Dispatch counts are not uniform: Python and Go count consumed events even without a matching handler; JS and Rust count handler invocations. A step/result count must not be specified as a cross-language event cardinality contract today. ## Mutation, removal, shutdown and exceptions Handlers are retained language objects, not C `void *` handlers retained by Core. They can capture application data for later dispatch; that data must remain valid according to the language's ownership rules. C's after-frame `user` is borrowed for the synchronous `cui_bridge_run` duration. The button adapter's stack `bridge_click_binding` survives its synchronous component invocation only; its pointer is never published as queued payload. Python clears/invalidate wrappers on close; JS disposal clears its app node map, but externally retained nodes can still retain their handler closures. Go removal marks descendants removed and deletes lookup entries, but a retained `*Node` continues owning its functions. Rust `remove` removes callbacks for the explicit node token, while C removes its subtree; descendant callback-map entries can remain until app teardown. C drops stale queued origins, so retention does not entitle an old closure to delivery for a reused slot. Callback-driven property updates and supported wrapper close/disposal have existing tests. They occur after C step, not inside Core component dispatch. This does **not** authorize destroying a Core context inside a synchronous native component callback. Direct C bridge destruction frees the app; a freed pointer cannot be destroyed again. During `run`, bridge destruction requests close and defers the single release until runner exit; do not reuse that pointer afterwards. [cui_bridge_run's public contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_bridge.h) rejects nested run/step from its callback. [The SDL runner](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/bridge/cui_bridge_sdl.c) invokes it on the UI thread after a successful completed step; it releases the native host on exit. Window close is normal `CLOSED`. Python/JS/Go/Rust runner wrappers catch foreign exceptions/panics, stop C, then rethrow/resume on their own side. Go retains runner userdata with `cgo.Handle` for that call and pins/checks the owning OS thread; Rust marks App local with `PhantomData>`. Standalone manual `dispatch` is synchronous and exceptions/panics propagate in the language after the event has been consumed. Remaining events need not be lost, but the throwing event is not retried automatically. No uniform guard for recursively dispatching or stepping from a manual handler was found; do not promise identical nesting or listener-replacement behavior across languages. Rust's closure borrowing imposes additional restrictions. Main-thread use is required; this audit does not establish uniform cross-thread enforcement in all bindings. `run` is a blocking native callback loop. JS `start` yields through timers but has different modal-resize behavior. Async callbacks/promises, Python coroutines, worker completion delivery, cancellation, thread pools and idle-loop wakeups are not implemented as a common event facility. Blocking work in a handler blocks its UI thread. Existing speech host-report APIs are not a generic URL-fetch executor or a guarantee of async shutdown/cancellation semantics. ## Examples and test evidence The examples under [bindings/bridge/examples](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/bridge/examples), [bindings/node/examples](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/node/examples), [bindings/go/examples](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/go/examples) and [bindings/rust/examples](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/rust/examples) use the actual retained bridge/builders. The older [foreign_languages host](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/foreign_languages/host.h) exports only `cui_example_run(font, frames, count_callback, user)`; its wrappers run the fixed C host and observe a count. They are host/FFI demonstrations, not proof of arbitrary component builders or the requested shared event API. The Node README's initial “row, column, label, button only” statement is stale against its canonical JS source and component tests; do not derive coverage from that sentence or from launcher examples. Relevant existing regression sources (not new execution results): - [C bridge core](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/bridge/tests/test_bridge_core.c) and [components](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/bridge/tests/test_bridge_components.c): real node operations, queued events, copied state snapshots, capacities and lifecycle. - [Python bridge tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/python/test_bridge.py): explicit separation of step/dispatch, callback mutation, disabled suppression, callback close, exceptions outside C and cross-app/disposal checks. [Component tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/python/test_components.py) include two text changes across frames before draining, proving snapshots rather than getters. - [JS binding tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/node/test/binding.test.cjs) and [components](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/node/test/components.test.cjs): auto-dispatch from step, mutation, close/dispose, disabled controls and change payloads. - [Go native tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/go/cui/native_test.go): `TestChangeSnapshotsAndInput`, `TestCallbackCloseAndThread`, `TestKeyboardAndCallbackPanic`, plus component-specific scenarios. - [Rust builders](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/rust/tests/builders.rs), [callback panic](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/rust/tests/callback_panic.rs) and [TypeScript typecheck fixture](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/typescript/components.typecheck.ts): current builder/payload behavior and negative type examples. Compilation of declarations is not proof of runtime dispatch timing. - Runner lifecycle/error/nesting sources: [Python](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/python/test_run_native_virtual.py), [JS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/node/test/run-native.test.cjs), [Go](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/go/cui/run_native_test.go), [Rust](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/rust/tests/run_native.rs). Portable unavailable-runner tests are separate; neither substitutes for all native host acceptance. ## Cross-check of proposal commit `84376caa` The separately committed `docs/design/COMPONENT_EVENTS_CONTRACT.md` is explicitly a proposal, not a shipped API. Its choice of synchronous component-local native callbacks is consistent with preserving existing C facades. The following binding qualifications are necessary at the design checkpoint: - “Callbacks run synchronously at the family's reduction/submission point” must not be read as describing current Python/JS/Go/Rust component callbacks. Their existing notifications run after step/render. Preserve that timing as a documented compatibility adapter; moving them inside C is an architectural boundary with exception, reentrancy and ownership implications. - Submission-borrowed handlers/userdata and no hidden allocation describe new immediate facades. Existing language closures are retained, and bridge snapshots allocate and queue. They need their own explicit exception, bounds and release contract rather than being relabeled as immediate callbacks. - The proposed request/notification/result distinctions do not yet cross the generic bridge record. Native controlled requests cannot be implemented by treating an existing post-mutation `CHANGE` handler's return as acceptance. - Native pointer-free metadata can reuse the existing Button snapshot; present bridge payloads omit it. Mark unavailable facts honestly until a new bridge payload transports them. No current binding exposes the proposed shared propagation/default-prevention/consumption controls. - Proposed recursive-frame/dispatch restrictions are sensible for new facades, but manual language dispatch does not presently have a uniform nesting guard. Wrapper close-after-frame behavior also differs from unsupported native context destruction during component dispatch. Keep these scopes separate. No new input-dispatch architecture is established by this audit. The proposal can retain native local dispatch and existing deferred notifications; the exact foreign controlled-request boundary still needs a separately reviewed slice. ## Practical future slices for the integrator's proposal These are implementation boundaries to consider, not an approved contract: 1. Preserve existing notification queue/timing and add a versioned event schema with explicit payload tags, owned/copyable strings and complete selected handles. Add optional, truthfully marked button evidence copied from the existing C snapshot. Specify queue/byte limits, unsupported capabilities and retry behavior. Do not reconstruct missing historical evidence. 2. Add component-specific typed language events over that schema, keeping compatibility adapters for generic `checked/value/text`. Cover lossless table columns, close outcomes, uint64 frame precision, stale selection and descendant callback retention. Reading a result must never dispatch a handler. 3. Add proposed-value requests only where the native controlled component contract supports them. Acceptance/rejection must execute at its defined synchronous decision point; the existing post-frame language notification cannot veto past mutation. Reusing it as a request would change semantics. Decide architectural/FFI reentrancy requirements before crossing that boundary. 4. Specify aggregation/counts, handler replacement/removal and mutation ordering independently from any capture/bubble architecture. Keep legacy timing and exception behavior explicit; test multiple interactions, absent handlers, queue failure and callback/result coexistence before claiming consistency. 5. Implement the requested optional async host example outside Core: handlers enqueue copied requests, UI-thread completions apply state, and shutdown, stale replies, logical/transport cancellation and wakeups have deterministic injected-transport tests. Current runners alone do not supply this contract. The binding-specific decision remains open: how to add a controlled request path while preserving deferred legacy notifications, and whether any such path requires a new synchronous foreign boundary with explicit ownership/reentrancy rules. Changing existing callback timing to “make it consistent” is observable and cannot be treated as a documentation-only or backward-compatible normalization. ## Implemented notification follow-up The additive [V1 manual notification API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_NOTIFICATIONS.md) now has owning Python/JavaScript/TypeScript views and [Go/Rust views](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_NOTIFICATIONS_GO_RUST.md). Its initial typed allowlist is activation, applied boolean changes, table changes and surface close outcomes; other payloads remain legacy. It preserves the existing shared queue and delivery timing. These views do not expose synchronous C value requests, Slider phase callbacks or Base Input observers to foreign handlers. Those omissions and the architectural decision above remain applicable. The separate [opt-in C value poll](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_VALUE_NOTIFICATIONS.md) additionally supports scalar, plain-text and selection snapshots for its explicit producer allowlists. [Python](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_VALUE_NOTIFICATIONS_PYTHON.md) and [JS/TypeScript](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_VALUE_NOTIFICATIONS_JS.md) and [Go](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_VALUE_NOTIFICATIONS_GO.md) and [Rust](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_VALUE_NOTIFICATIONS_RUST.md) owning value polling are implemented; Rust static builds require the paired SDK, while dynamic builds negotiate optional exports; existing V1 methods keep their initial allowlist and receive LEGACY snapshots for these categories. Consumers must negotiate the new optional symbols and category mask rather than enabling reserved tags through the old method. ## Current source snapshot — 2026-10-18 (`9ba9c78c`) This section supersedes historical **current availability** claims above, not the baseline's evidence. Read-only inspection of canonical C, Python, JS/TypeScript, Go and Rust sources/tests/docs; no suites rerun for this documentation update. All 78 manifest entries remain present. SDK header distribution, a component builder and a passing legacy UI test each establish different facts; none means all direct-C observer semantics are implemented in a foreign runtime. ### Two manual protocols over one queue | API boundary | Complete typed producer eligibility | Not supplied | | --- | --- | --- | | Initial `cui_bridge_poll_notification_v1` | Existing CLICK → ACTIVATE/NONE; Checkbox/Switch/Toggle → CHANGE/BOOLEAN; DataTable existing selection/sort enqueue → CHANGE/TABLE; existing surface/Notification CLOSE → LIFECYCLE/SURFACE | Every other CHANGE remains LEGACY, including producers that the separate value method can decode. No input evidence/index/source or synchronous veto. | | Opt-in `cui_bridge_poll_value_notification_v1` | Initial categories plus requested/negotiated SCALAR (Slider, NumberInput, Rating, Pagination), TEXT (Input, Textarea, Editor, Input Group), SELECTION (Radio group, Tabs, Select, List, Stepper) | Unrequested categories, unsupported producers and mask0 stay complete LEGACY. No automatic mapping from native typed facades. | The exact [initial contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_NOTIFICATIONS.md), [value contract and allowlists](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_VALUE_NOTIFICATIONS.md), [C declarations](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_bridge.h) and [enqueue implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/bridge/cui_bridge.c) are authoritative. Both methods consume the same FIFO as old extended/filtered polling and dispatch; there is no duplicate queue, subscription/fanout, implicit getter or replay. Polling only owns a snapshot and never invokes a handler. Filtered old CLICK polling still discards non-CLICK records. Capacity failure preserves the live record; stale-origin cleanup before it is not rolled back. Queue-full error can follow already-applied model mutation. Neither API is a transaction or request decision. Initial schema/size/version checks remain mandatory; value polling additionally negotiates optional value-category and poll exports and requests only compiled-known advertised bits. Old libraries remain usable through old methods; missing/incompatible optional exports fail explicitly **before draining**, without fallback to another consumer. Malformed records detected after successful consuming C reads cannot be restored. Genuine older-library no-drain tests and injected malformed-provider tests prove different properties and must be reported separately. Typed table row/column/sort values are exact uint32 one-based bridge indices (zero absent), not Core IDs or C observer operation keys. BOOLEAN reports already-applied state, not immutable entry/requested-value controlled Check/Switch/Toggle semantics. SCALAR copies binary64: NumberInput retains its actual double, while Slider/Rating cannot regain precision lost in their float models. TEXT is the existing aggregate plain UTF-8 snapshot, not each edit/commit/submit, and inherits no native secure redaction. The bridge exposes no secure/password configuration; OTP remains Legacy. SELECTION holds historical Item slot/generation, not an owned live node or a per-transition native selection event. Select's net-zero frame can remain silent; List can repeat the same item on activation. Menu/Dropdown/Combobox retain Legacy classification even when old fields contain text or selected handles. ### Canonical owning wrapper entrypoints | Language | Initial manual API / opt-in value API | Ownership, precision and stepping | | --- | --- | --- | | Python | `App.poll_notifications_v1()` / `App.poll_value_notifications_v1()` iterators | Frozen dataclass variants with owned strings, exact Python integer frame and uint32 handle tuples; optional live Widget references are not immutable model ownership. `step()` does not dispatch; manual iterator consumes only when advanced. | | JavaScript | `App.poll_notification_v1()` / `App.poll_value_notification_v1()` → record or `undefined` | Frozen discriminated records, copied strings/handle objects, exact uint64 `frame: bigint`; optional Node references can later become invalid. Use `step_only()` to avoid legacy automatic dispatch by `step()`/`run()`. | | TypeScript | `NotificationV1` / separate `ValueNotificationV1` unions over those JS methods | Runtime is the Node addon, not another implementation. Readonly/discriminated declarations require BigInt-capable tooling; typecheck evidence is not runtime proof. | | Go | `App.PollNotificationV1()` / `App.PollValueNotificationV1()` → value, present bool, error | Separate kind enums and kind-selected typed fields; strings/uint64 frame/uint32 handle are copied, optional `*Node` remains live. `Step` and `Dispatch` remain separate. | | Rust | `App::poll_notification_v1()` / `App::poll_value_notification_v1()` → `Result>` | Separate exhaustive owning enums, `String`, u64 frame and u32 handles; tokens do not own live native nodes. `step` and `dispatch` remain separate (`frame` combines them). Static Rust requires paired SDK; dynamic optional exports are negotiated. | Representative canonical references: [Python methods/types](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/python/cui_bridge/__init__.py), [JS manual methods](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/node/index.cjs), [Node FFI/protocol checks](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/node/addon.c), [TypeScript unions](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/typescript/index.d.ts), [Go owning decoder](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/go/cui/native.go), [Rust owning decoder](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/rust/src/lib.rs). Language-specific [Python](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_VALUE_NOTIFICATIONS_PYTHON.md), [JS/TS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_VALUE_NOTIFICATIONS_JS.md), [Go](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_VALUE_NOTIFICATIONS_GO.md) and [Rust](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_VALUE_NOTIFICATIONS_RUST.md) guides specify exact errors. All four owning manual decoders start with 4097 bytes and allow one strictly larger capacity retry, capped at 1 MiB **including NUL**. This replaces the historical fixed-buffer limitation for these manual methods only; it does not rewrite old legacy dispatch buffers, bool conversions or JS Number frame behavior. No silent truncation. Copies outlive queue reuse, later model edits/removal and app teardown; optional node resolution uses complete slot+generation and must not resolve a historical selection to a replacement slot occupant. Record immutability does not freeze a referenced node. Handler retention/exception/timing differences in the historical dispatch audit remain separate from manual owning records. ### All 78 families: explicit omission boundary This partition checks the exact names in [component manifest](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/gpui-parity.json), not every possible enqueue branch. The rows below account for all 78 once. Common initial ACTIVATE/NONE can also originate from existing simple CLICK adapters in other rows; it does not grant an extra typed component-specific payload. A row with no dedicated typed value can still emit Legacy/CLOSE/CLICK through existing adapters, host interactive children, be noninteractive, or lack a foreign node representation. **No notification emission promise is inferred from membership.** | Manifest families (disjoint accounting) | Current dedicated typed view / omission | | --- | --- | | Button | Initial ACTIVATE/NONE for existing CLICK; native accepted pointer/key evidence and per-input handler semantics are not exported. | | Checkbox, Switch, Toggle | Initial applied BOOLEAN; native controlled request/readonly/entry snapshot facades are not exported. | | DataTable | Initial TABLE at existing selection/sort enqueues only; newer native set/span workspace, per-transition multiplicity, stable uint64 keys, column width/move, activation/context/mode requests are not exported. | | AlertDialog, Dialog, Sheet, Popover, Notification | Initial SURFACE at existing CLOSE enqueues; not the retained native completed-CLOSED observer registration/update/lifetime contract, synchronous decide/veto or general lifecycle stream. | | Slider, NumberInput, Rating, Pagination | Opt-in SCALAR only; native phases/reasons/before-after/counts/commit policies are not exported. | | Input, Textarea, Editor, Input Group | Opt-in aggregate plain TEXT only; native per-edit payloads/selection/redaction, Input Group addon observer details and submit/commit are not exported. | | Radio, Tabs, Select, List, Stepper | Opt-in SELECTION applies only to the bridge's RadioGroup producer (catalog Radio), Tabs, Select, single List and Stepper; not every radio item, Listmulti/ToggleGroup arrays or native per-transition facade. | | Accordion, Alert, Attachment, Avatar, Badge, Bubble, Clipboard, Collapsible, DropdownButton, Empty, Focus Trap, GroupBox, HoverCard, Icon | No additional dedicated typed value allowlist. Existing producer-specific Legacy/common initial records only where implemented; native family observers/results/host services do not automatically cross this bridge. | | Image, Kbd, Label, Marker, Message, MessageScroller, Progress, Shimmer, Skeleton, Spinner, Tag, Tooltip, Calendar, ColorPicker | No additional dedicated typed value allowlist. Existing producer-specific Legacy/common initial records only where implemented; native family observers/results/host services do not automatically cross this bridge. | | Combobox, DatePicker, Form, OtpInput, Questionnaire, Speech, TimeField, Carousel, DescriptionList, Dock, Menu, Resizable, Root View, Scrollable | No additional dedicated typed value allowlist. Existing producer-specific Legacy/common initial records only where implemented; native family observers/results/host services do not automatically cross this bridge. | | Settings, Sidebar, StatusBar, Theme, TitleBar, Toolbar, Tree, VirtualList, Chart, Command, Plot, Table, TextView | No additional dedicated typed value allowlist. Existing producer-specific Legacy/common initial records only where implemented; native family observers/results/host services do not automatically cross this bridge. | Command, Toolbar, Sidebar, Scrollable, HoverCard and Tooltip in that remainder now have direct-C typed facades, as do numerous other families audited in their guides. That does not add foreign handlers, direct-C synchronous execution timing or callback veto. Tree activation, retained surface completion, Command early query/confirmed-path semantics, Toolbar aggregate ambiguity and Sidebar collapse details all remain native contracts. Shared C metadata's input source/index/activation evidence is absent from bridge V1 beyond captured frame presence. No capture/bubble/default-prevention layer, foreign controlled request, synchronous lifecycle veto or async completion protocol is implied. Native render/match/content and retained lifecycle callbacks additionally have distinct lifetime rules that cannot be replaced by a queued notification. ### Inspected tests versus executed historical evidence Current real-queue C tests: [initial V1](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_bridge_notifications.c), [scalar](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_bridge_value_notifications.c), [text](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_bridge_text_notifications.c), [selection](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_bridge_selection_notifications.c). Owning wrapper tests are [Python initial](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/python/test_notifications_v1.py)/[values](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/python/test_value_notifications_v1.py), [Node initial](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/node/test/notifications-v1.test.cjs)/[values](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/node/test/value-notifications-v1.test.cjs), [Go initial](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/go/cui/notifications_v1_test.go)/[values](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/go/cui/value_notifications_v1_test.go), [Rust initial](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/rust/tests/notifications_v1.rs)/[values](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/rust/tests/value_notifications_v1.rs). They distinguish real queue FIFO/interleaving, copied text, table columns above 1, stale selected generations and later setters from synthetic protocol values. Node [initial](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/node/test/notifications-v1-protocol.test.cjs)/[value](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/node/test/value-notifications-protocol.test.cjs) and language-specific providers cover malformed negotiation/capacity/union output; maximal uint64 frames and oversized synthetic payloads are **not** real UI proof. Observed historical evidence, not a fresh run: integrator's offline Linux [`test_notification_bindings.py`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/scripts/test_notification_bindings.py) log `/tmp/cui-next39-rust-value-bindings.log` records source `4aa3c3d02bac4a5b3b24320d08790a667fbc6ce3`, shared bridge SHA256 `fa9cb17db1317ac3c3ae23959f4091ca12f5f85dc5db80cdb5ed4f1d1082b946`, **52/52 passed, 122.78 s**. The integrator separately recorded unchanged library hash before/after. This precedes later native component-event slices; it is not validation of current `9ba9c78c` binaries, Python/Node runtime cases, macOS/Windows, native SDL lifecycle windows or all 78 family semantics. That 52-case configuration includes four Go/Rust static/dynamic real+legacy suites with `CUI_VALUE_REAL=1`, fourteen initial protocol cases (seven modes per language), two genuine pre-V1 unavailable cases, 26 value protocol cases (13 separate provider modes per language), and six genuine initial-V1/optional-unavailable no-drain cases. Older-library flags are required for those optional cases; a shorter run with skips/omitted flags is not 52-case proof. Rust static uses paired SDK; injected and older-library interposition remain dynamic only. The runner disables downloads, checks SDK source freshness, builds separate strict C11 providers and uses private `test_local.py`; it does not run the separate native window lifecycle suite. No suite was executed and no manifest status was promoted by this documentation refresh. Future foreign typed/controlled/lifecycle work needs its own reviewed protocol, exception/reentrancy/storage and real-input tests; native source-header availability alone is insufficient. ## Avatar observer addition Direct C single-Avatar and visible-stack activation observers are implemented in [cui_avatar_events.h](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_avatar_events.h). Python, JS/TS, Go and Rust do not yet expose these synchronous observer handlers or stack payloads. Avatar style setters are a separate retained binding feature, not event parity. See [the observer guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/AVATAR_EVENTS.md) for timing and borrowed lifetimes. ## Alert completed-dismiss observer Direct C `cui_alert_events` is a synchronous coalesced observer after the existing optional visibility assignment. Python, JS/TS, Go and Rust do not expose this handler/result facade or per-input Dismiss events. The retained bridge Alert is presentational; its arbitrary child actions remain separate. See [the guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/ALERT_EVENTS.md); no foreign close/veto support is implied. ## Bounded Button styles and extended HoverCard policy Direct C `cui_button_styled_ex`/`cui_button_styled_paint` add borrowed pure paint handlers; these are not interaction observers and are not exposed by Python, JS/TS, Go or Rust wrappers. Existing event wrappers and Group do not accept these new style records. See [Button styles](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BUTTON_STYLES.md). Direct C `cui_begin_hover_card_extended` combines the existing lifecycle observer with an opt-in caller-accepted tap policy and semantic relationship snapshots. Existing foreign HoverCard wrappers retain their legacy behavior; no policy workspace or synchronous callback bridge is exposed. See [HoverCard extended policy](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/HOVER_CARD_EXTENDED.md). ## Controlled Stepper navigation and typed Kbd hints Direct C `cui_base_stepper_navigation` and `cui_stepper_navigation` expose synchronous typed REQUEST handlers. Existing Python, JS/TS, Go and Rust Stepper wrappers retain their current behavior and do not expose this request facade. The new `cui_kbd_ex` typed stroke/options surface is also C-only; existing foreign literal shortcut hints remain available. Bundled C sources include both APIs; bundling does not establish language-wrapper support. See [Stepper navigation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/STEPPER_NAVIGATION.md) and [Kbd](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/KBD.md). --- ## Component events: proposed contract and implementation slices Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_CONTRACT.md # Component events: proposed contract and implementation slices Status: committed design checkpoint. The shared metadata utility is now [implemented](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMPONENT_EVENTS.md); component-family facades and other contracts proposed below remain unimplemented unless explicitly linked to an implementation guide. The committed [78-family inventory](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_COVERAGE.md) and [binding audit](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_BINDINGS.md) accompany this checkpoint. Their source evidence establishes existing contracts and identifies missing proof; it is not a claim that proposed behavior is implemented. Existing headers remain the authority for implemented behavior. ## Architectural decision Keep immediate submission and synchronous component-local dispatch. Do not add capture/bubble routing, an end-of-frame callback queue, a scheduler, a thread pool, or networking to Core. New optional facades should preserve existing ownership models rather than replacing them. A family that cannot adopt this contract without changing public timing, mutation, or ownership must be split out for a reported architectural decision before production implementation. Preserve explicit exceptions established by the audits: Speech's pump and foreign-language notification queues retain their current delivery timing. Surface, Notification, Carousel, Resizable, Root, Questionnaire and Dock keep their retained registration/descriptor lifetimes. Plot/Chart callbacks deferred to layout/prepaint/paint remain valid through their existing current-frame boundary. Omitting a drawing call does not cancel retained lifecycle work. No broad synchronous-dispatch or submission-borrowing claim covers these APIs. The bridge currently reports post-mutation notifications, not synchronous typed value requests. Preserve that path. A future opt-in foreign request hook needs its own reviewed retention, cross-language exception, reentrancy and value-owner design; adding fields to a queued notification cannot implement rejection. No new request hook or retiming is authorized by calling this checkpoint complete. Current source examples establish why a blanket replacement is unsafe: - `include/cui/cui_components.h`: Button has a legacy callback followed by a typed click-evidence callback. Its boolean result still reports activation. - `include/cui/cui_base.h`: controlled Check emits a typed request without writing the value; a rejected request can still return accepted activation. - The controlled double Slider has begin/update/commit/cancel phases and an externally owned value; its boolean means submission, not value change. - `include/cui/cui_edit.h`: editing already has transaction validation, mutation guards, and borrowed text lifetimes. Do not bypass those mechanisms. - `cui_event` contains a borrowed optional text pointer. Copying the struct alone is not a general deferred-event copy operation. The audit documents must record other family-specific differences, including legacy functions that mutate caller storage directly. These differences are compatibility obligations, not reasons to reinterpret existing results. ## Vocabulary and typed payloads Use these meanings where a component actually supports the interaction: | Concept | Meaning | | --- | --- | | Activation | An accepted attempt to invoke an action; no implied value change. | | Change request | A typed proposed value offered to the value owner. | | Change notification | A typed value transition that has actually been applied. | | Commit | Completion of a value-editing gesture/transaction; may have no net change. | | Submit | Explicit submission of entered data, distinct from typing or blur. | | Lifecycle | Open/close or begin/cancel/end with a component-specific reason. | Avoid a generic `void *value` payload. Boolean, check-state, scalar, selection, date, text-edit and other values retain typed declarations. `void *userdata` is solely an application context convention. Use a shared, pointer-free metadata envelope only for common facts; preserve component-specific reason/value fields. Final public names and layouts require the audits and ABI review first. Metadata should identify the stable component ID and available event sequence, input origin and evidence. Represent unavailable facts explicitly. Do not invent a pointer position for a key or accessibility action, a physical device ID, a host timestamp, or an event index for programmatic lifecycle work. Existing `cui_activation_snapshot` and Button evidence should be reused where their documented evidence is sufficient, not reconstructed after mutable callbacks. ## Four independent decisions 1. Value acceptance: the owner accepts/rejects a proposed typed value. A request alone is never a committed-value notification. 2. Input consumption: existing reducer/host handling determines whether the input has been handled. Value rejection does not automatically unconsume it. 3. Propagation: no new general routing is proposed. A facade cannot advertise stop-propagation semantics that Core does not implement. 4. Platform defaults: retain explicit existing host facilities. Callback return values must not pretend to cancel browser/native defaults already performed. New controlled facades should take a value snapshot and emit requests without mutating it. The owner may assign external state synchronously, and the next documented snapshot point observes it. Existing pointer-mutating entry points keep their exact behavior. An optional acceptance hook for an existing transaction is distinct from a notification handler. Do not promise a committed notification for external owner assignment that CUI cannot observe. ## Timing, ordering and results Callbacks run synchronously at the current family's reduction/submission point. Do not silently defer them to end-frame. Freeze required evidence before a callback can consume input or mutate application state. Preserve existing legacy callback order; in particular, Button legacy `on_click` precedes its existing typed click handler. New per-family adapters need explicit source and legacy regression tests before claiming this ordering contract. Process multiple supported events in original reducer order. A result may aggregate counts and flags and retain a documented last value/reason, but must not imply that only one callback occurred. Overflow behavior must be explicit; prefer bounded counters with an overflow flag to an unbounded event log. Reading a result never dispatches, reapplies mutations, or repeats callbacks. Applications choose callbacks or frame results for each side effect. The proposed new result vocabulary distinguishes submitted, activated, requested, applied, committed and cancelled rather than overloading one `changed` boolean. Families expose only meaningful fields. Legacy result types and booleans keep their documented meanings through separate adapters. Disabled and inert components emit no user activation/value requests. Loading suppresses activation only where the family's contract defines that behavior; do not globally change legacy loading semantics. Read-only may allow focus, selection or copying while suppressing changes. Omitted immediate components cannot generate new submission callbacks; retained resources follow their explicit release rules. Define cancellation on disable/removal for each active-gesture family, without fabricating an input origin. ## Lifetimes and callback mutation For new immediate facades, handlers and userdata are borrowed through that submission call. They are not stored for the next frame. Retained APIs must declare registration/replacement/release lifetimes separately; do not relabel existing retained userdata as submission-borrowed. Payloads are callback-borrowed unless explicitly documented as copyable values. Pointer-free snapshots can be copied by value. Borrowed text, selections or arrays require caller-provided storage and checked length/capacity for deferred copies; no hidden allocation or unbounded queue. A copy operation must fail explicitly for insufficient capacity and leave no misleading partial payload. Numeric resource limits must come from audited existing limits or an explicit new bounded type, not undocumented assumptions. Callbacks may update unrelated application state or the value owner's external storage according to the family's snapshot rules. Recursive submission of the same component, recursive frame entry, destruction of the UI context, and freeing active callback/state storage are unsupported. Existing edit mutation guards remain effective. New facades need a clear failure/guard contract rather than allowing use-after-free. Removal/shutdown is requested in app state and performed after the active submission/dispatch returns. Whether a later component is omitted in that same frame remains normal application control flow; it must not cause a queued callback to run on freed userdata. ## Alternatives considered - One untyped universal callback: rejected because it erases value types and makes payload ownership difficult to check. - Force all controls into internal retained state: rejected because it breaks immediate caller-owned values and controlled requests. - End-of-frame callback batching: rejected because callback ordering and synchronous mutation are observable behavior. - DOM-style capture/bubble: deferred; no present requirement justifies new Core dispatch architecture. Explicit local/host consumption remains independent. - Rename legacy callbacks globally: rejected; additive facades and compatibility wrappers allow independently verifiable migration. ## Independently reviewable slices 1. Commit completed source/test coverage, this contract, binding coverage, justified exceptions and any unresolved architectural decisions. No production event changes before this checkpoint. 2. Add only shared metadata/copy contracts with bounded headless tests. Preserve existing Button callbacks and legacy callback timing/mutation regressions. 3. Introduce optional typed facades for activation and discrete controlled Boolean/check/selection requests. Verify rejection separately from input consumption and preserve old mutation entry points. 4. Adapt continuous editing and transactions independently: Slider first, then numeric/text families through their existing acceptance machinery. Explicitly test gesture commit/cancel, multiple events and callback mutation. 5. Adapt menus, selection composites and dialog lifecycle independently. Record noninteractive and unsupported lifecycle exceptions instead of manufacturing callbacks for every family. 6. Update bridge/bindings per supported slice with real UI examples and lifetime tests; document omissions until implemented. Regenerate distributions, source metadata, SDKs and consumer skill through repository generators. 7. Commit the separate async host example and deterministic offline tests. Each slice requires warnings-enabled builds, meaningful tests and an isolated commit. Linux native tests use `python scripts/test_local.py --build-dir build`; browser tests are headless; unsupported GPU hardware remains deferred. Keep all 78 manifest entries. A completed slice is not full component uniformity. ## Separate async example design Proposed optional stack: existing SDL3 host plus a libcurl-backed worker. Verify dependency availability/pinning and repository conventions before implementation; neither stack becomes a Core dependency. A synchronous UI handler copies the URL into bounded worker-owned storage, assigns a monotonically increasing request generation, marks loading, enqueues one job and returns promptly. Reject a duplicate request while loading. The worker calls only transport/synchronization facilities. Completion data crosses a bounded synchronized mailbox and wakes the idle SDL host with its supported user-event/wakeup facility. Only the UI thread drains completions, checks the active generation, changes UI state and calls CUI. Failures display retry; retry receives a new generation. Late completions cannot overwrite a newer request or a removed view. Minimum cancellation guarantee is logical cancellation: invalidate the active generation and ignore its eventual result. If libcurl progress cancellation is implemented, document its cooperative transport guarantee separately; do not claim immediate cancellation of DNS or other blocking host operations. Shutdown signals cancellation, wakes the worker, joins it, drains/frees mailbox data and only then destroys synchronization/host state. Timeouts must bound real network work; the injected offline transport controls completion explicitly. Offline tests must cover prompt enqueue/return, loading/duplicate prevention, owned request bytes after caller mutation, controlled success/failure/retry, out-of-order/stale completion, logical cancellation, wake delivery, UI-thread application, and shutdown with pending work. No test requires network access. ## Queued follow-up After the overall event API work, reduce consumer-skill output/context cost, especially example and limitation discovery. A separate Sol 6.1 low audit is assigned; preserve essential unsupported-API and build guidance while making long detail explicitly retrievable. This is a subsequent task, not a reason to delay the event design checkpoint or shrink its documentation obligations. --- ## Component event coverage checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_COVERAGE.md # Component event coverage checkpoint Read-only inventory at `e9d2c1a561ced3254e606b0206f412af8b156317` on `integration/next39-components`. This covers the exact 78 names in [the frozen manifest](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/gpui-parity.json), not a parity promotion. The design request is tracked in `docs/design/COMPONENT_EVENTS_REQUEST.md` at this baseline. This document describes existing C APIs and implementation seams. It approves no new API. Correction to this historical inventory: the Avatar and Alert rows below omitted intrinsic activation/dismissal paths. The [current audit](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/AVATAR_EVENTS_SLICE.md) records those paths and their observer gaps; use the [remaining coverage matrix](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_REMAINING.md) for current dispositions. ## Implemented additions since the checkpoint [Shared metadata](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMPONENT_EVENTS.md) and the direct C [Button/Check facades](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CONTROL_EVENTS.md) are implemented after this audit. Button preserves legacy callback order and adds typed activation metadata; Check offers immutable typed requests with per-invocation counts. These are submission-borrowed synchronous handlers. The original rows below remain the checkpoint baseline, not an assertion that later additions are absent. No Python, JavaScript/TypeScript, Go or Rust wrapper for these new handlers is implemented yet; existing queued notifications retain their audited behavior. ## Reading the evidence Each row has a public contract, implementation, and an existing focused test to inspect. These are source evidence and test locations, **not a claim that every event property in that row has a dedicated passing assertion**. No runtime suite was run for this documentation-only audit. In particular, general callback reentrancy, context destruction, arbitrary descriptor removal during dispatch, cross-family ordering, and every binding's callback ownership remain unverified unless explicitly documented below. The grouping is by ownership and dispatch semantics, not visual similarity: - **S**: synchronous reduction/operation or submission. A callback's presence does not make its handler retained. Payload pointers are borrowed unless a stronger copy contract is explicit. - **R**: a model, resource, descriptor, or lifecycle snapshot retains handlers/users or borrowed inputs beyond a submission. The owner must keep them alive until their last use/teardown; the individual API determines that boundary. - **F**: layout/prepaint/paint can invoke callbacks later in the current frame. Submission-only lifetime is insufficient. - **Q**: explicit bounded queued delivery, distinct from synchronous UI reduction. - **N**: noninteractive family-level exception. Render, validation, formatting, easing, resource-loader and host-service functions are not automatically component events. Interactive children retain their own contracts. A bool may mean changed, activated, valid, opened a container, or successfully submitted. It is not a common event record. A typed result can aggregate a frame without specifying event count. Merely reading a returned C value has no dispatch effect; operations such as `take_result`, `update`, `pump`, `dispatch`, and `confirm` are actions, not passive getters. ## Per-family inventory (78/78) The manifest order is preserved so omissions are mechanically detectable. Shared header/implementation groups are intentional: rows retain their separate state/result/exception contracts. | Family | State ownership and frame/operation result | Existing callback/payload category | Timing and lifetime boundary | Evidence (contract, source, test location) | | --- | --- | --- | --- | --- | | Accordion | Caller bool array + optional motion; bool reduction result. | No change event callback; header/panel slots render content. | S: reducers mutate open array; no controlled rejection seam. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_disclosure.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_disclosure.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_disclosure.c) | | AlertDialog | Caller surface/overlay state; typed close reason; take_result consumes a latch. | Request: decide(user, reason) -> bool; lifecycle: on_close(user, reason). | R: close handler stored in state; decision is synchronous; close notification follows actual close/focus restoration, possibly after exit motion. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_surface.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_surface.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_surface.c) | | Alert | Caller descriptors; paint/container submission (void or success result by entry point), no value event. | N: any content slots are render callbacks; child controls own their events. | Submission borrowing; no family activation callback. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_content.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_content.c) | | Attachment | Caller attachment descriptor; typed click/remove/retry result (group aggregation too). | Activation callbacks on_click/on_remove/on_retry(user, id). | S: callbacks after reduction, in click/remove/retry code order; results coexist with dispatch. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_media.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_media.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_media.c) | | Avatar | Caller descriptors; paint/container submission (void or success result by entry point), no value event. | N: any content slots are render callbacks; child controls own their events. | Submission borrowing; no family activation callback. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_content.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_content.c) | | Badge | Caller value/content; drawing/container submission. | N: optional content renderer; no activation notification. | Child controls remain independent. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_components.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_components.c) | | Bubble | Caller descriptors; paint/container submission (void or success result by entry point), no value event. | N: any content slots are render callbacks; child controls own their events. | Submission borrowing; no family activation callback. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_content.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_content.c) | | Button | Caller optional hover/tooltip state; bool aggregates activation. | Activation: on_click(user), then typed on_click_event(user, const event*); on_hover(user,bool) edges. | S per accepted event, not merely once per true frame result; typed snapshot pointer callback-local, contents pointer-free/copyable. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_components.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_button_callback_events.c) | | Checkbox | Caller tri-state; legacy mutates; source/controlled facade proposes value; bool result. | Request: on_change(user, requested tri-state, activation snapshot*); style/indicator callbacks are render/policy. | S: owner may reject; controlled without callback read-only; legacy mutation preserved. Snapshot borrowed callback-local. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_components.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_checkbox_source.c) | | Clipboard | Host-owned clipboard service; explicit get/set success/status. | Host service function pointers in cui_platform; no component change notification. | S service borrowing; platform-specific capability, not an editable UI value. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_sdl3.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/backends/sdl3/cui_sdl3.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_sdl3.c) | | Collapsible | Caller bool + optional motion; bool reduction result. | No change event callback; content slots render. | S: mutates open; suppression is reducer policy. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_disclosure.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_disclosure.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_disclosure.c) | | DropdownButton | Caller popup/menu action; typed {action_activated,menu_activated}. | No uniform family event object; choice/menu composition uses ID outputs and render slots; nested list callbacks depend on selected entry point. | S: choice reducers consume input and mutate caller state. Callback multiplicity/order must be specified per entry point, not inherited from bool result. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_choice.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_choice.c) | | Empty | Caller descriptors; paint/container submission (void or success result by entry point), no value event. | N: any content slots are render callbacks; child controls own their events. | Submission borrowing; no family activation callback. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_content.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_empty_source.c) | | Focus Trap | Caller overlay + Core focus scope; update returns close-on-input bool. | No trap event callback. | Explicit open/update/begin/end/close; innermost update first; consumed input ignored. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_overlay.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_overlay.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_overlay.c) | | GroupBox | Caller descriptors; paint/container submission (void or success result by entry point), no value event. | N: any content slots are render callbacks; child controls own their events. | Submission borrowing; no family activation callback. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_content.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_content.c) | | HoverCard | Caller overlay/hover state; visibility driven by input/time. | No public visibility-change event; content renderer is not a notification. | S: hover/focus visibility reduction; hidden content is not an activation result. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_content.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_content.c) | | Icon | Caller icon state/owned decoded resource; typed error/result. | N/host: theme SVG loader; no activation/change callback. | Loader is resource policy; SVG/resource lifetime differs from event payload lifetime. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_icon.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_icon.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_icon.c) | | Image | Caller image state/resource/source; typed load/render result. | N/host: loader returns typed load; placeholder/fallback/content renderers. | Frames/pixels borrowed through frame/render completion; no image-click or load-change event callback. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_media.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_media.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_media.c) | | Kbd | Caller descriptors; paint/container submission (void or success result by entry point), no value event. | N: any content slots are render callbacks; child controls own their events. | Submission borrowing; no family activation callback. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_content.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_content.c) | | Label | Caller text/options/target; bool is submission success. | N: text/rich content; target focus association is behavior, not activation callback. | No family change handler; do not interpret success as click. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_components.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_label_source.c) | | Marker | Caller marker state; submit/render result. | N: custom marker renderer receives id/font/color. | Renderer is composition, not click/change notification. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_status.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_status.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_status.c) | | Message | Caller content/style; bool composition result. | N: message content render callback. | Child controls own interaction; bool not submit/send. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_message.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_message.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_message.c) | | MessageScroller | Caller-managed opaque layout/scroll bookkeeping (no retained message records); typed render result. | Row renderer; no general message-added/read/scroll notification callback. | Count append/splice are explicit; renderer sees visible rows plus overdraw; collection/state must remain unchanged through end_frame. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_message.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_message.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_message.c) | | Notification | Caller entries + retained descriptors/host; advance result. | Activation/lifecycle callbacks on_click/on_action/on_close(user, typed ID); host send -> bool, retract/activate. | R: descriptor shallow-copied into entries; strings/users/handlers must survive use. Host send can reject push; close can occur during update. Checked renderer prevalidates but cannot roll back external side effects. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_status.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_status.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_status.c) | | Pagination | Caller size_t page pointer; bool change result. | No public typed change callback. | S mutation during reducer; frame bool does not encode count/origin. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_numeric.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_numeric.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_numeric.c) | | Progress | Controlled fraction; caller motion/result optional; no editable value. | N: no value-change/completion notification. | Motion result is sampled state, not dispatched lifecycle. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_components.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_control_family_audit.c) | | Radio | Legacy caller int selection; group caller stable-ID selection + workspace/results. | Group request: on_change(user, requested ID); legacy radio has no notification callback. | S: group without callback writes selection; already-selected item emits no change. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_radio_group.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_radio_group.c) | | Rating | Caller float rating pointer; bool change result. | No public typed change callback. | S mutation during reducer; frame bool does not encode count/origin. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_numeric.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_numeric.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_numeric.c) | | Shimmer | Caller motion/time state; sampling/paint outputs. | N: no animation-completion event. | Time-driven rendering; no interactive request. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_status.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_status.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_status_motion.c) | | Skeleton | Caller motion; loading-motion result and success bool. | N: easing policy and optional Spinner paint callback; no completion/change event. | S: easing/paint borrowed during call; paint userdata explicitly not retained. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_content.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_content.c) | | Spinner | Caller motion; loading-motion result and success bool. | N: easing policy and optional Spinner paint callback; no completion/change event. | S: easing/paint borrowed during call; paint userdata explicitly not retained. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_content.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_spinner_contract.c) | | Stepper | Caller size_t current step pointer; bool change result. | No public typed change callback. | S mutation during reducer; frame bool does not encode count/origin. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_numeric.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_numeric.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_numeric.c) | | Switch | Caller bool; legacy mutable and controlled callback forms; bool activation/change result. | Request: on_change(user,bool requested); content render slot. | S: callback-owned acceptance differs from legacy pointer write; no common event metadata. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_components.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_controlled_siblings.c) | | Tag | Caller style/text; bool submission success. | N: no remove/click callback in current standalone Tag. | Registers label semantics, removes tab stop; true does not mean activation. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_status.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_status.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_status.c) | | Toggle | Caller bool / group bool array; bool result. | Request: on_change(user,bool); group callback gets const requested bool array + count. | S: group scratch must be separate from values; request array borrowed only during callback; not a retained value pointer. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_components.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_controlled_siblings.c) | | Tooltip | Caller overlay/hover state; visibility driven by input/time. | No public visibility-change event; content renderer is not a notification. | S: hover/focus visibility reduction; hidden content is not an activation result. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_content.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_content.c) | | Calendar | Caller calendar state/selection; typed calendar result. | disabled-date predicate is policy; no selection event callback. | S reduction then submission; predicate does not own selection acceptance. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_picker.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_picker.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_picker.c) | | ColorPicker | Caller picker state/color; Styled bool change (Base DatePicker typed calendar result). | No public change callback; DatePicker may use disabled-date predicate. | S pointer/model updates; popup lifecycle is not exposed as common typed events. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_picker.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_picker.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_picker.c) | | Combobox | Caller edit, selection and popup; typed combobox result. | No uniform family event object; choice/menu composition uses ID outputs and render slots; nested list callbacks depend on selected entry point. | S: choice reducers consume input and mutate caller state. Callback multiplicity/order must be specified per entry point, not inherited from bool result. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_choice.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_choice.c) | | DatePicker | Caller popup/calendar/date; Styled bool change (Base DatePicker typed calendar result). | No public change callback; DatePicker may use disabled-date predicate. | S pointer/model updates; popup lifecycle is not exposed as common typed events. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_picker.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_picker.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_picker.c) | | Editor | Caller edit/editor/search/completion state; textarea + search results. | Highlight/measurement callbacks are policy; no universal edit/completion event handler. | S edits; completion item array explicitly borrowed until close; callbacks are not an async completion provider contract. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_editor.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_editor.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_editor.c) | | Form | Caller field metadata/layout; begin/end composition. | N: content render callback; no form-wide submit/validation event bus. | Child input result/validation remains caller-owned. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_form.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_form.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_form.c) | | Input | Caller cui_edit + optional behavior state; {changed,submitted,error,rejected}. | Acceptance predicate, format/matcher policy; Base presentation_complete(prepared,applied) lifecycle, not change notification. | S event-order edits; validation candidate borrowed synchronously. Mask allocator/storage can remain retained until context resource release. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_components.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_input_acceptance.c) | | Input Group | Caller editor and input state; typed input-group result nests input result. | Prefix/suffix renderers; nested Input validation policy, no new group change callback. | S: accessory/clear results distinct from text mutation; render callback not event. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_form.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_form.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_form.c) | | NumberInput | Caller double + edit/state; typed numeric/edit result. | step(user,value,direction)->double is value policy, not confirmed change event. | S parse/step/edit mutation; no general change/submit callback. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_numeric.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_numeric.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_numeric.c) | | OtpInput | Caller UTF-8 buffer and OTP/composition state; typed changed/complete/focus/error result plus change_count and complete_count. | No completion/change callback. | S value mutation; complete flag and bounded counts must retain their own documented aggregation semantics. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_otp.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_otp.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_otp.c) | | Questionnaire | Caller definitions/editors/workspace + runtime; typed operation status and bool navigation. | Retained legacy event(const state*, {kind,item,previous},user); optional persistent typed observer with frozen names/answer/submission and UNKNOWN origin; validators return borrowed error. | R: synchronous pre-legacy typed delivery with bounded caller arenas, frozen Completed/Submit pair and BUSY detach pinning. Legacy callback mutations remain live; typed handlers and validators are pure. Definitions/workspaces/handlers outlive use; errors last until next validation. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_questionnaire.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_questionnaire.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_questionnaire.c) | | Select | Caller selected value + popup; bool change result. | No uniform family event object; choice/menu composition uses ID outputs and render slots; nested list callbacks depend on selected entry point. | S: choice reducers consume input and mutate caller state. Callback multiplicity/order must be specified per entry point, not inherited from bool result. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_choice.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_choice.c) | | Slider | Legacy float pointer/bool; controlled double value + caller drag presentation state; controlled bool reports valid submission. | Typed request {BEGIN,UPDATE,COMMIT,CANCEL; double value; copied event}; legacy has no change callback. | S: controlled never writes confirmed value; missing callback read-only; event borrowed during callback (not guaranteed deep-copy-safe). Keyboard can emit multiple phases per key. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_base.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_base.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_slider_controlled.c) | | Speech | Caller workspace/state, generation-tagged provider sessions; bool/status operations. | Retained typed {type,error,text} event; provider start/audio/finish/close host interfaces. | R/Q: reports copy payload into bounded queue; events delivered only by owner-thread pump, even synchronous provider reports. Providers cannot call lifecycle functions. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_speech.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_speech.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_speech.c) | | Textarea | Caller edit/layout/selection state; typed changed/selection/scrolled/Enter-modifier/error result. | No general changed/submit callback; geometry/clipboard services are policy. | S mutable editor; frame result is aggregation, not a retained transcript of edits. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_textarea.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_textarea.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_textarea.c) | | TimeField | Caller time state/value; Styled bool change (Base DatePicker typed calendar result). | No public change callback; DatePicker may use disabled-date predicate. | S pointer/model updates; popup lifecycle is not exposed as common typed events. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_picker.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_picker.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_picker.c) | | Carousel | Caller state/geometry; bool operation/render results. | Retained on_change(index,user), confirmed selected-index notification. | R/S: valid different select emits once; render/content callbacks separate. Handler/user lifetime follows state use. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_carousel.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_carousel.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_carousel.c) | | DescriptionList | Caller item array; bool composition result. | N: label/value render slots. | Submission borrows content; child interaction independent. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_description.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_description.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_description.c) | | Dialog | Caller surface/overlay state; typed close reason; take_result consumes a latch. | Request: decide(user, reason) -> bool; lifecycle: on_close(user, reason). | R: close handler stored in state; decision is synchronous; close notification follows actual close/focus restoration, possibly after exit motion. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_surface.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_surface.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_surface.c) | | Dock | Caller model/view/workspace/lifecycle snapshots; typed errors/view/workspace results. | on_event(enum,panel,node), resize/transfer requests; panel add/remove/active/zoom hooks; factory lifecycle. | R/S/explicit: panel descriptors/factories and snapshot identities retained; lifecycle capture/dispatch is separate from paint. Transfer acceptance cannot be inferred from callback presence. See dedicated obligations below. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_dock.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_dock.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_dock_styled.c) | | List | Caller selected ID / multi bool array; bool selection-change result. | List options: on_activate(ID,user), then on_confirm(ID,secondary,user); on_cancel(user). Render/panel callbacks separate. | S: choice reducers consume input and mutate caller state. Callback multiplicity/order must be specified per entry point, not inherited from bool result. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_choice.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_choice.c) | | Menu | Caller popup/tree state + selected/activated ID outputs. | No uniform family event object; choice/menu composition uses ID outputs and render slots; nested list callbacks depend on selected entry point. | S: choice reducers consume input and mutate caller state. Callback multiplicity/order must be specified per entry point, not inherited from bool result. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_choice.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_choice.c) | | Popover | Caller surface/overlay state; typed close reason; take_result consumes a latch. | Request: decide(user, reason) -> bool; lifecycle: on_close(user, reason). | R: close handler stored in state; decision is synchronous; close notification follows actual close/focus restoration, possibly after exit motion. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_surface.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_surface.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_surface.c) | | Resizable | Caller slots/state; typed errors + {changed,completed,phase}. | Retained on_resize(user,const state*) confirmed resize; appearance/content callbacks are render. | R/S: explicit restore emits one completed resize; state pointer is borrowed, not immutable owned snapshot. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_resizable.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_resizable.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_resizable.c) | | Root View | Caller root/registry/plugin instances + facilities; bool operation/render status. | Retained plugin build/destroy/render and copy hook; no general root change event. | R: registration user/window state survive plugin lifetime; explicit dispose owns teardown ordering. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_root.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_root.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_root.c) | | Scrollable | Caller scroll state / offset pointers; bool reduction results. | No common scroll callback; overlay/container composition. | S and finish/deferred-child handling; bool is entry-point-specific, not event count. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_scroll.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_scroll.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_scroll.c) | | Settings | Caller pages/item value pointers + filter/selection state; typed settings result. | on_change(user) after built-in change/reset; dirty/reset/render policy hooks. | S: no typed changed value supplied; caller reads its model; descriptors/users must survive rendering/reset. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_settings.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_settings.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_settings.c) | | Sheet | Caller surface/overlay state; typed close reason; take_result consumes a latch. | Request: decide(user, reason) -> bool; lifecycle: on_close(user, reason). | R: close handler stored in state; decision is synchronous; close notification follows actual close/focus restoration, possibly after exit motion. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_surface.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_surface.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_surface.c) | | Sidebar | Caller cache/expanded/collapsed state; typed item result, aggregate bool render. | on_activate(user); controlled on_expand(bool,user); toggle on_change(bool,user); header/footer pointer-only activation. | S: owner commits controlled expansion; header/footer has narrower input coverage than menu items. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_sidebar.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_sidebar.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_sidebar.c) | | StatusBar | Caller region items; bool submission success. | N: region render callbacks own child input/semantics. | Strings/callbacks borrowed for submission; no status-change event. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_chrome.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_chrome.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_chrome.c) | | Tabs | Caller selected ID + optional animation; bool change result. | No uniform family event object; choice/menu composition uses ID outputs and render slots; nested list callbacks depend on selected entry point. | S: choice reducers consume input and mutate caller state. Callback multiplicity/order must be specified per entry point, not inherited from bool result. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_choice.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_choice.c) | | Theme | Caller theme value/palette; explicit copy/project/load operations. | N/host: icon_loader(user,path,svg*) is resource policy, not theme-change event. | No ambient theme-change notification; loader resource users have their own lifetime. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_theme.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/theme/cui_theme.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_theme_registry.c) | | TitleBar | Caller gesture state + window info/host; bool behavior/render result. | on_close(user); host move/minimize/maximize services. | S: close request is host action, not proof of destroyed window; host/user lifetime required during call. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_chrome.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_chrome.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_chrome.c) | | Toolbar | Caller item/command descriptors; bool container submission. | Command on_activate(user); render callback receives presentation metrics. | S: arrays/callbacks borrowed for call in source order; toolbar disabled suppresses navigation, owner disables children. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_toolbar.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_toolbar.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_toolbar.c) | | Tree | Caller model/state; typed selection/expansion result. | No general selection/expansion event callback; activated ID is a result field. | S mutates model/state; result contains IDs/flags, not uniform acceptance policy. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_tree.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_tree.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_tree.c) | | VirtualList | Caller virtual model + scroll state; typed error/view/scroll_changed/window_pending. | Measure policy + visible-row renderer; no item-select event. | S plus deferred child scroll: callback window may be old; invalidation renders new window next frame. Model keys/heights cannot change inside row callback. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_virtual_scroll.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_virtual_scroll.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_virtual_styled.c) | | Chart | Caller data/pixels/motion/hover state; typed chart result. | Format/geometry/fill/tooltip callbacks are policy/render; typed tooltip builder is not value-change notification. | F: current-frame mode borrows state/data/users through paint; tooltip info/builder callback-local, strings copied boundedly by builder; external effects not rollback-safe. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_chart.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_chart.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_chart_typed_tooltip.c) | | Command | Caller rows/query/state; bool validity/operation results. | on_select(index), on_query(str), item action(user), on_confirm(index), on_cancel; matches/binding/render separate. | S/R: rebuild retains entry pointers until next rebuild; confirm snapshots row and invokes action before on_confirm; query text borrowed. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_command.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_command.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_command.c) | | DataTable | Caller model/columns/rows/selection workspace; typed selection/sort/column/request result. | Cell/header/group/trailing callbacks render; no universal value/sort/selection event callback. | S: reducers mutate state/model, some requested-selection-mode outputs remain caller decisions; stable IDs not owned row payload copies. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_table.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_table.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_table_selection_contracts.c) | | Plot | Caller element/motion/hover state + paint resources; typed plot result. | on_appear receives callback-local sample; resolver/paint/tooltip callbacks separate. | F: appearance notifies in preflight before resolver/paint; current-frame callbacks run after layout, borrowing through end_frame/render completion. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_plot_view.h) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_plot_chart_prepaint.c) | | Table | Caller basic row/cell/span descriptors; begin/end checked submission. | N: basic table composition has no table-wide event callback; DataTable is separate behavior. | Child controls own events; successful begin is not row activation. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_table.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_table.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_table.c) | | TextView | Caller document/workspace/selection/motion; typed parsing/render error and selection updates. | on_link(url,const event*,user) activation; on_reveal(rect,user) viewport request; measurement policy. | S: decoded URI borrowed only during callback; copy for deferred use. Event pointer borrowed; selection manager is caller-owned. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_text_view.h) · [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_text_view.c) · [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_text_view.c) | ## Verified distinctions that a common convention must preserve 1. **Request is not commit.** Checkbox source, controlled Slider, Switch/Toggle callbacks and Sidebar expansion permit application-owned values. RadioGroup has its own callback-versus-legacy-write rule. Returning an activation/change bool cannot establish that the owner accepted a proposal. See [Checkbox source tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_checkbox_source.c), [controlled siblings](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_controlled_siblings.c), [RadioGroup contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_radio_group.h), and [Slider phase tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_slider_controlled.c). 2. **Activation can have multiplicity.** [Button callback events](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_button_callback_events.c) and [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_components.c) distinguish per-accepted-event callback dispatch from frame bool aggregation. Legacy `on_click` precedes the typed snapshot callback. [List reducer](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_choice.c) invokes activation before confirmation; cancellation is independent of selection change. A blanket end-frame dispatcher would change observable ordering. 3. **Lifecycle may outlive the initiating call.** [Surface close](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_surface.c) stores its close callback and delays actual close through motion; [Notification](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_status.c) shallow-copies descriptors into entries (not an owned deep string copy). [Dock](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_dock.h) has explicit snapshot capture/dispatch and reconstruction/factory destruction, in addition to view callbacks. Dock's complete callback mutation/removal/reconciliation ordering needs a separate event trace audit before adapters are designed; this inventory does not certify it. 4. **Some rendering happens after submission.** [Plot/Chart current-frame contracts](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_plot_view.h) borrow state/data/users through deferred paint; [prepaint tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_plot_chart_prepaint.c) are relevant evidence. Typed Chart tooltip info/builders are callback-local; builder setters copy bounded strings, but borrowed data and raster writes remain external. Converting these to event listeners would conflate rendering and notifications. 5. **There is already a queued exception.** [Speech](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_speech.h) copies reports to bounded workspace and emits only from its explicit owner-thread pump, with generation-tagged sinks. It is not evidence that arbitrary component handlers can safely run on worker threads. The callback's transcript view still needs copying for deferred consumers. 6. **Validation/rejection has a narrower meaning.** [Input acceptance](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_input_acceptance.c) separates rejected edit from error/submission; the [Base contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_base.h) describes synchronous candidates and completion. Notification host send rejection is a transaction boundary. Surface decision false keeps it open. None of these return values means DOM-style propagation stop or platform-default prevention. 7. **Borrowed event is not always a copyable snapshot.** Button explicitly provides a pointer-free accepted snapshot. Slider carries a copied `cui_event` but only promises callback-local borrowing; TextView passes a borrowed event pointer and decoded URI. No common durable event ownership can be inferred from those three signatures. ## Bindings and host boundary This matrix inventories public portable C, not 78 verified language event surfaces. The [C bridge](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_bridge.h) explicitly copies clicks into a bounded queue and language callbacks run after `step`; its native `run` callback has a separate deferred-destroy contract. That differs from direct C Button synchronous dispatch. The [Rust wrapper](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/bindings/rust/src/lib.rs) is a separate adapter; matching node names or constructors does not establish matching typed callback payloads, multiplicity, lifetime or controlled rejection. Every row's direct callback availability in Rust/Go/other generated bindings is **unknown in this checkpoint** until an explicit export/signature and callback-retention matrix is added. No proposed new event API is exported by this document. Clipboard, TitleBar, Speech, image loaders and Root plugins are host/service boundaries. Their callbacks cannot be made portable network/OS implementations by renaming them as component events. Video/VideoControls are additive modules outside these 78 frozen families. Their supplementary inventory below does not add a 79th baseline entry. ## Supplementary modules outside the frozen manifest These already implemented modules are part of the interaction audit without changing the 78-entry manifest: | Module | Ownership/results | Callbacks/timing/lifetimes | Evidence | | --- | --- | --- | --- | | Video timeline/surface | Caller-owned timeline; mutators return operation validity. Surface borrows decoded pixel storage through all renderer consumption. | No family event callback; playback/seek success is a model operation, not asynchronous decoder acknowledgement. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_video.h), [source](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_video.c), [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_video.c) | | VideoControls/Player | Caller-owned confirmed view and local presentation/scrub state; bool is submission validity. | Synchronous typed requests with source/generation/sequence and typed union. Requests never mutate/acknowledge confirmed host state; absent handler is read-only. Options/view copied before dispatch; UI/state must survive callbacks. Hidden parts submit no targets. | [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_video_controls.h), [source](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_video_controls.c), [test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_video_controls.c) | ## Design obligations and missing proof (proposals, not current guarantees) The following is recommended work for the separate proposal; none is asserted as implemented: - Define common naming and typed metadata while keeping activation, requested value, committed notification, submission and lifecycle distinct. Preserve the concrete double/ID/date/color/tri-state/text types; opaque `void *user` is context, not an untyped value payload. - Specify each entry point's callback/result multiplicity, event ordering, snapshot point, disabled/loading/inert/omission behavior, and accepted input channels. Use existing pointer/keyboard/accessibility evidence; do not fabricate coordinates or source metadata for model operations. Current Sidebar header/footer are explicitly pointer-only. - State handler retention, payload copying, scratch bounds, deferred access and removal/teardown rules. Default to no context destruction during dispatch unless explicitly supported; the bridge runner's deferred-destroy behavior does not grant that permission to portable C controls. - Test callback-driven owner rejection, value changes, sibling removal, callback replacement, nested operation attempts, and shutdown. Distinguish supported mutation from rejected reentrancy rather than merely documenting whichever behavior happens today. Existing focused tests above are starting evidence, not blanket coverage of these cases. - Keep propagation/consumption, owner acceptance, and platform default action separate. A generic capture/bubble system would require Core routing and lifetime design; current reducer order alone is not such a system. - Offer one recommended application side-effect path. Preserve legacy callback ordering and mutation in wrappers; consuming both frame result and callback for the same action must not be the recommended pattern. Passive result reads must never replay callbacks. - Audit exports and generated human/LLM references with the implementation. Binding adapters must explicitly preserve or document their queued timing differences and bounded-overflow behavior. - For any optional async example, workers own jobs and requests, publish synchronized UI-thread completions, wake an idle host runner, reject stale generations, and terminate/cancel safely. No networking is needed in deterministic headless tests. This is a host example requirement, not permission for callbacks to block or for Base to depend on a codec/network runtime. ## Check against the parallel proposal Reviewed `docs/design/COMPONENT_EVENTS_CONTRACT.md` at integrator commit `84376caa` without changing this audit baseline. Its additive facades, preserved legacy timing, separate acceptance/consumption, callback-local payloads and no generic bubbling match the source distinctions above. The following are architectural exceptions requiring explicit wording before implementation, not contradictions to hide: - “Synchronous component-local dispatch” must exempt Speech's explicit pump and the bridge's queued language delivery. They are shipped behaviors, not candidates for silent retiming. - “Handlers borrowed through submission” applies only to new immediate facades. Surface, Notification, Carousel, Resizable, Root, Questionnaire and Dock already have retained registrations/descriptors; Plot/Chart have current-frame deferred callbacks. Adapters must leave those lifetimes intact or report a separately approved redesign. - The proposed omission rule must distinguish new immediate callbacks from retained lifecycle/pump work: omitted drawing does not by itself cancel an already-registered notification, provider report or surface exit. Removal/cancellation policy is still per-family work. - Slider's current controlled bool is submission validity, not changed/requested. Textarea reports last Enter modifiers rather than a universal submit event; OTP already exposes per-frame counts. Proposed richer result fields need additive types and exact adapters, not reinterpretation. No source contract was altered to fit the proposal. The separately committed [binding audit](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_BINDINGS.md) supplies the bridge and language-specific timing/ownership evidence. ## Audit validation Documentation validation checks exact family equality/count against `docs/component manifest` and resolves every relative Markdown file link. The 78-family matrix is an API coverage inventory with explicit unknowns. It does not establish upstream source parity or justify ledger promotion. ## Subsequent compatible slices The checkpoint matrix above records the audited legacy baseline. The following additive C entry points are implemented; their guides and focused tests define the actual limits. Existing rows remain intact so the original 78-family audit stays reviewable. None of these additions promotes a parity level. | Implemented entry points | Values and dispatch | Important exception | | --- | --- | --- | | [Button/Checkbox](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CONTROL_EVENTS.md) | Activation plus typed tri-state requests at the existing synchronous seams. | Controlled acceptance is separate from consumption; legacy callback order remains. | | [Switch/Toggle](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BOOLEAN_EVENTS.md) | Immutable boolean requests; owner accepts on a later submission. | No handler means read-only requests, unlike applied observers below. | | [Base Slider](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SLIDER_EVENTS.md), [Styled Slider](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/STYLED_SLIDER_EVENTS.md) | Double BEGIN/UPDATE/COMMIT/CANCEL phases, caller-owned confirmed value and preview. | Cancellation can lack input evidence; old float API remains unchanged. | | [Base Input](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TEXT_INPUT_EVENTS.md), [Styled Input](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TEXT_INPUT_STYLED_EVENTS.md) | Per-event committed text CHANGE and eligible Enter SUBMIT. | No rejectable edit transaction; secure payloads are redacted. | | [Textarea](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MULTILINE_EVENTS.md), [Editor](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MULTILINE_EVENTS.md#editor-observers) | Zero-or-one aggregate revision CHANGE after the relevant complete reducer. | Editor observes its outer completion path; no inferred cause/index or submit event. | | [RadioGroup](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SELECTION_EVENTS.md), [Select](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SELECT_EVENTS.md), [Combobox](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMBOBOX_EVENTS.md) | ID transitions at actual reducer seams, preserving existing callbacks and phase order. | OPTION accessibility ACTIVATE remains unsupported; combobox query edits are separate. | | [Surface](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SURFACE_EVENTS.md) | Retained completed-close lifecycle observer; legacy decision callback remains separate. | Stable state address/user lifetime extends through exit motion; imperative close requires an active frame. | | [MenuTree](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MENU_EVENTS.md), [ContextMenu](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CONTEXT_MENU_EVENTS.md), [Simple Menu](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SIMPLE_MENU_EVENTS.md) | Every applied command, including repeated same-ID activation; context opening is separate. | Dropdown has separate action/menu phases; no value veto. | | [NumberInput](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NUMBER_EVENTS.md) | Zero-or-one aggregate exact-double applied CHANGE, separate from draft revision. | A committed change can accompany a legacy error; no inferred COMMIT/SUBMIT. | | [Tabs](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TABS_EVENTS.md) | Zero-or-one aggregate stable-ID selection CHANGE before Styled paint/panel. | Scroll, reorder and overflow lifecycle are separate; no reconstructed input cause. | | [Pagination, Stepper, Rating](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NUMERIC_SELECTION_EVENTS.md) | Aggregate applied size_t page/index or float rating CHANGE. | One-based page differs from zero-based step; passive normalization can mutate without notification. | | [Calendar/DatePicker/ColorPicker](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PICKER_EVENTS.md) | Aggregate typed start/end dates or RGBA CHANGE after the chosen whole reduce/Base/Styled call. | Month/year navigation, latent HSV, external color sync and popup lifecycle are separate. | | [DropdownButton](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DROPDOWN_EVENTS.md) | Per-action accepted evidence followed by per-command menu notifications. | Phase indices can decrease; Styled modal and Link accessibility restrictions remain. | | [OTP](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/OTP_EVENTS.md) | One aggregate CHANGE carrying accepted-operation/completion counts and final borrowed text. | Masked text is redacted; completion is not SUBMIT and final state may be incomplete. | | [Collapsible and Accordion](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DISCLOSURE_EVENTS.md) | Every applied expanded bool transition, preserving repeated/net-zero toggles and genuine activation evidence. | Notification precedes final semantics/paint; callback model/input mutation is unsupported. | | [List and ToggleGroup](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/LIST_EVENTS.md) | Ordered single-ID or per-item bool transitions; List observes after legacy activation/confirmation callbacks. | Same-item confirmation is separate; ToggleGroup preserves intermediate sibling closures. | | [Tree](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TREE_EVENTS.md) | Each applied selection and expansion transition and every row invocation. | Observer sees intermediate cursor/focus/semantic state; model mutation during callback is unsupported. | | [DataTable](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TABLE_EVENTS.md) | Per-transition sort, single selection, exact multi-set snapshots, column width/move, activation, context and ROW-mode requests. | Scalar selection observers reject multi mode; separate set API requires bounded exclusive caller workspace. Viewport/load-edge completion remains result-only. | | [Attachment](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/ATTACHMENT_EVENTS.md) | OPEN/REMOVE/RETRY after corresponding legacy callback in fixed category order. | Each category coalesces to zero/one; host work completion is not implied. | | [TimeField](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TIME_FIELD_EVENTS.md) | Final typed time CHANGE after the whole Base/Styled operation. | Aggregate zero/one notification; no draft, submit or per-input cause claim. | | [Sidebar](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SIDEBAR_EVENTS.md) | Each row invocation plus controlled expansion/collapse REQUEST and uncontrolled expansion CHANGE after legacy callbacks, before later paint. | Header/footer action observers preserve genuine pointer-activatable GROUP accessibility routing; row TREEITEM activation remains unsupported. | | [Command](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMMAND_EVENTS.md) | Base programmatic and Styled path/query/activation observations plus Styled cancel REQUEST. | Borrowed query observation precedes legacy mutation hooks; externally edited leading rebuild remains PROGRAMMATIC even in passive scopes. | | [Toolbar commands](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TOOLBAR_EVENTS.md) | Aggregate ACTIVATE after paint and legacy callback, with evidence frozen before either. | Custom renderers opt in explicitly; container disabled controls navigation independently of child command availability. | | [InputGroup](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/INPUT_GROUP_EVENTS.md) | Accepted addon ACTIVATE inputs in descriptor/input order, then per-event nested text CHANGE/SUBMIT. | Custom addon controls own their events; masked Styled rendering uses checked Input presentation and rejects conflicting custom presentation hooks. | | [Settings](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SETTINGS_EVENTS.md) | Applied navigation plus built-in bool/double/choice owner changes and committed text revisions after legacy callbacks, including explicit RESET. | Filter reconciliation is silent; custom reset hooks keep their existing untyped contract. | Counts summarize actual observer invocations except where a guide explicitly preserves another established result convention. Reading results is passive. Synchronous callbacks must not destroy their active context or storage. New immediate handlers are borrowed; Surface is explicitly retained. No generic capture/bubble dispatch or end-of-frame retiming was introduced. Foreign bindings expose owning [V1 manual notifications](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_NOTIFICATIONS.md) and [Go/Rust views](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_NOTIFICATIONS_GO_RUST.md) for the documented initial allowlist. They do not automatically expose these direct C facades, synchronous requests, text, scalar or selection events. See the [binding audit](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_BINDINGS.md). Opt-in C bridge scalar notifications are implemented for Slider, NumberInput, Rating and Pagination, and plain text for Input, Textarea, Editor and InputGroup; see [support and legacy downgrade rules](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_VALUE_NOTIFICATIONS.md). Selection snapshots are also supported for the explicit RadioGroup/Tabs/Select/List/Stepper allowlist. Python, JS/TypeScript, Go and Rust have owning value polls; Rust static builds require their paired SDK. Questionnaire now also offers the bounded persistent C observer in [QUESTIONNAIRE_OBSERVER.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/QUESTIONNAIRE_OBSERVER.md). It freezes copied payloads before legacy callbacks, including one Completed/Submit pair, while preserving live legacy mutation and callback replacement. Caller-owned attachment/frame lifetimes, BUSY detach, capacity/depth failures and UNKNOWN metadata are explicit; no language observer facade or full-family uniformity is claimed. --- ## Remaining component event coverage Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_REMAINING.md # Remaining component event coverage Source checkpoint: `18d3c17d` (78 frozen manifest families). Documentation-only audit, not a parity/status promotion or a claim of 78 uniform event APIs. The [contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_CONTRACT.md), original [matrix](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_COVERAGE.md) and [binding audit](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_BINDINGS.md) retain their historical scope; current headers and implemented guides take precedence over their older absence statements. No production behavior or tests changed and no runtime builds were run for this audit. Linked tests are evidence to inspect, not newly executed proof. ## User-facing priority Button, Input, Checkbox, Switch, Toggle, controlled double Slider, selections, menus and completed dialog close already have additive C APIs. The remaining objective is discoverable use and honest boundaries, rather than inventing a new callback for every render family. Standalone legacy Radio/float Slider and legacy entrypoints are preserved alternatives, not automatically adapted APIs. Controlled requests permit owner rejection; applied notifications do not. Enter submission, gesture commit and completed surface close are distinct events. Immediate handlers are submission-borrowed and payloads callback-borrowed unless their guide says otherwise. Text/arrays require checked owned copies. Shared metadata never establishes an unavailable cause. Context destruction, recursive composition and freeing active storage during callbacks remain unsupported. Surface is retained; Speech is pumped; retained models and deferred rendering retain their longer lifetimes. None is silently retimed to end-frame. ## Exhaustive disposition (78/78) A = additive facade exists for the stated scope; T = existing typed API with a justified timing/lifetime exception; N = render/child composition; H = host, resource or deferred-render exception; G = genuine gap or pending slice. A is not full-family verification. Each family links its authoritative public header. | Family | Class | Current boundary and next work | | --- | --- | --- | | [Accordion](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_disclosure.h) | A | [DISCLOSURE_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DISCLOSURE_EVENTS.md): Every applied expansion transition; no controlled veto added. | | [AlertDialog](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_surface.h) | A | [SURFACE_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SURFACE_EVENTS.md): Retained completed-close only; existing decision policy separate; open/request/veto not notifications. | | [Alert](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) | A | [ALERT_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/ALERT_EVENTS.md): coalesced completed Dismiss action after legacy visibility assignment; frame-only metadata, no per-input observer or close/veto promise. Child actions remain separate. | | [Attachment](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_media.h) | A | [ATTACHMENT_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/ATTACHMENT_EVENTS.md): Coalesced OPEN/REMOVE/RETRY after old callbacks in category order, not raw-input multiplicity. | | [Avatar](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) | A | [AVATAR_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/AVATAR_EVENTS.md): single and visible-stack per-event activation observers preserve genuine child evidence and legacy aggregate order. Legacy void Avatar remains presentational; foreign callback facades are omitted. | | [Badge](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) | N | Rendering/container or child composition; successful submission is not activation. Child controls retain their own event contracts. | | [Bubble](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) | N | Rendering/container or child composition; successful submission is not activation. Child controls retain their own event contracts. | | [Button](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) | A | [CONTROL_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CONTROL_EVENTS.md): Per-activation Button; immutable controlled Check requests, not confirmed owner changes. | | [Checkbox](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) | A | [CONTROL_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CONTROL_EVENTS.md): Per-activation Button; immutable controlled Check requests, not confirmed owner changes. | | [Clipboard](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_sdl3.h) | H | Host get/set service; no editable component event. Preserve platform capability/failure semantics. | | [Collapsible](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_disclosure.h) | A | [DISCLOSURE_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DISCLOSURE_EVENTS.md): Every applied expansion transition; no controlled veto added. | | [DropdownButton](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h) | A | [DROPDOWN_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DROPDOWN_EVENTS.md): Action phase then every menu command; indices can decrease across phases. | | [Empty](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) | N | Rendering/container or child composition; successful submission is not activation. Child controls retain their own event contracts. | | [Focus Trap](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_overlay.h) | N | Reviewed primitive exception in [checkpoint](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/LIFECYCLE_RESULT_EVENTS_SLICE.md): caller-owned scope begin/end is composition, not open/close lifecycle. Optional overlay-operation observer absent; Surface close separate. | | [GroupBox](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) | N | Rendering/container or child composition; successful submission is not activation. Child controls retain their own event contracts. | | [HoverCard](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) | A | [HOVER_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/HOVER_EVENTS.md): Pure Base and Styled final open-model transitions; not actual visibility or animation completion. Child composition remains separate. | | [Icon](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_icon.h) | H | Resource loading/style/rendering, not activation; loader users/resources follow resource lifetime. | | [Image](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_media.h) | H | Loader/result and borrowed frame resources through render completion; no implied image activation or async load-change event. | | [Kbd](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) | N | Rendering/container or child composition; successful submission is not activation. Child controls retain their own event contracts. | | [Label](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) | N | Rendering/container or child composition; successful submission is not activation. Child controls retain their own event contracts. | | [Marker](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_status.h) | N | Rendering/container or child composition; successful submission is not activation. Child controls retain their own event contracts. | | [Message](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_message.h) | N | Rendering/container or child composition; successful submission is not activation. Child controls retain their own event contracts. | | [MessageScroller](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_message.h) | A | [MESSAGE_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MESSAGE_EVENTS.md): Base/Styled exact double-offset and following-tail observers after legacy composition; explicit mutators and deferred bounds remain outside call-local notification. | | [Notification](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_status.h) | T | Retained descriptor click/action/close callbacks with typed ID and host send/retract operations; descriptor strings/users survive use, not just submission. | | [Pagination](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_numeric.h) | A | [NUMERIC_SELECTION_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NUMERIC_SELECTION_EVENTS.md): Aggregate applied page/index/rating; normalization is not automatically notification. | | [Progress](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) | N | Rendering/container or child composition; successful submission is not activation. Child controls retain their own event contracts. | | [Radio](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) | A | [SELECTION_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SELECTION_EVENTS.md): RadioGroup Base/Styled transitions covered; standalone legacy int Radio has no new facade. | | [Rating](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_numeric.h) | A | [NUMERIC_SELECTION_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NUMERIC_SELECTION_EVENTS.md): Aggregate applied page/index/rating; normalization is not automatically notification. | | [Shimmer](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_status.h) | N | Rendering/container or child composition; successful submission is not activation. Child controls retain their own event contracts. | | [Skeleton](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) | N | Rendering/container or child composition; successful submission is not activation. Child controls retain their own event contracts. | | [Spinner](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) | N | Rendering/container or child composition; successful submission is not activation. Child controls retain their own event contracts. | | [Stepper](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_numeric.h) | A | [NUMERIC_SELECTION_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NUMERIC_SELECTION_EVENTS.md): Aggregate applied page/index/rating; normalization is not automatically notification. | | [Switch](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) | A | [BOOLEAN_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BOOLEAN_EVENTS.md): Base/Styled immutable entry requests; ToggleGroup transitions are separately covered by LIST_EVENTS. | | [Tag](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_status.h) | N | Rendering/container or child composition; successful submission is not activation. Child controls retain their own event contracts. | | [Toggle](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) | A | [BOOLEAN_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BOOLEAN_EVENTS.md): Base/Styled immutable entry requests; ToggleGroup transitions are separately covered by LIST_EVENTS. | | [Tooltip](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) | A | [HOVER_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/HOVER_EVENTS.md): Aggregate applied open-model transition, distinct from composition bool; omission retains no listener or synthetic close. | | [Calendar](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_picker.h) | A | [PICKER_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PICKER_EVENTS.md): Aggregate applied dates/RGBA; navigation/latent HSV/popup lifecycle excluded. | | [ColorPicker](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_picker.h) | A | [PICKER_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PICKER_EVENTS.md): Aggregate applied dates/RGBA; navigation/latent HSV/popup lifecycle excluded. | | [Combobox](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h) | A | [COMBOBOX_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMBOBOX_EVENTS.md): Selection only; query editing and submission are not derived from selection notifications. | | [DatePicker](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_picker.h) | A | [PICKER_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PICKER_EVENTS.md): Aggregate applied dates/RGBA; navigation/latent HSV/popup lifecycle excluded. | | [Editor](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_editor.h) | A | [MULTILINE_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MULTILINE_EVENTS.md): Aggregate revision CHANGE after whole reducer; Editor completion included, no invented cause or submit. | | [Form](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_form.h) | N | Rendering/container or child composition; successful submission is not activation. Child controls retain their own event contracts. | | [Input](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) | A | [TEXT_INPUT_STYLED_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TEXT_INPUT_STYLED_EVENTS.md): Base/Styled committed per-event text CHANGE and eligible SUBMIT; secure payload redaction. | | [Input Group](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_form.h) | A | [INPUT_GROUP_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/INPUT_GROUP_EVENTS.md): Addon activations plus nested Input changes/submits; custom children remain independent. | | [NumberInput](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_numeric.h) | A | [NUMBER_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NUMBER_EVENTS.md): Aggregate exact-double applied change; draft revisions distinct, no inferred commit. | | [OtpInput](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_otp.h) | A | [OTP_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/OTP_EVENTS.md): Aggregate final borrowed text and operation/completion counts; masked redaction, no submit claim. | | [Questionnaire](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_questionnaire.h) | T | Legacy retained kind/index callbacks remain synchronous and observe live model mutations; they do not carry copied names/answers/submissions. Pure [copy-out snapshots](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/QUESTIONNAIRE_SNAPSHOTS.md) are implemented separately. [Typed observation proposal](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/QUESTIONNAIRE_EVENTS_CONTRACT.md) is design-only and awaits a public-state ABI decision; validators are policy, errors borrowed until next validation. | | [Select](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h) | A | [SELECT_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SELECT_EVENTS.md): Per-transition selection; OPTION accessibility ACTIVATE remains unsupported. | | [Slider](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) | A | [STYLED_SLIDER_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/STYLED_SLIDER_EVENTS.md): Controlled double Base/Styled BEGIN/UPDATE/COMMIT/CANCEL; legacy float path stays separate. | | [Speech](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_speech.h) | T | Typed bounded provider reports delivered by owner-thread pump only; generation/session checks and pump lifetime cannot become immediate handlers. | | [Textarea](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_textarea.h) | A | [MULTILINE_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MULTILINE_EVENTS.md): Aggregate revision CHANGE after whole reducer; Editor completion included, no invented cause or submit. | | [TimeField](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_picker.h) | A | [TIME_FIELD_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TIME_FIELD_EVENTS.md): Final aggregate typed time; draft/submit/cause excluded. | | [Carousel](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_carousel.h) | T | Retained index-change callback already reports confirmed selection; no common metadata envelope. Preserve state/user lifetime and operation-time dispatch. | | [DescriptionList](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_description.h) | N | Rendering/container or child composition; successful submission is not activation. Child controls retain their own event contracts. | | [Dialog](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_surface.h) | A | [SURFACE_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SURFACE_EVENTS.md): Retained completed-close only; existing decision policy separate; open/request/veto not notifications. | | [Dock](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_dock.h) | T | Typed event/panel/node, resize and transfer requests, explicit lifecycle capture/dispatch and retained descriptors; no blanket submission borrowing. | | [List](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h) | A | [LIST_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/LIST_EVENTS.md): Ordered ID transitions and confirmation; ToggleGroup per-item changes separate. | | [Menu](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h) | A | [MENU_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MENU_EVENTS.md): MenuTree, SimpleMenu and ContextMenu forwarding implemented; opening is not command activation. | | [Popover](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_surface.h) | A | [SURFACE_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SURFACE_EVENTS.md): Retained completed-close only; existing decision policy separate; open/request/veto not notifications. | | [Resizable](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_resizable.h) | T | Retained on_resize receives borrowed live state; typed changed/completed/phase results. Immutable snapshot facade would need independent lifetime review. | | [Root View](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_root.h) | H | Retained plugin build/render/destroy/copy services; explicit dispose ordering, not value notifications. | | [Scrollable](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_scroll.h) | A | [SCROLL_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SCROLL_EVENTS.md): Paired Base/Styled final-offset observer after children/finish; aggregate normalization included, no fabricated per-input transitions. Overlay, virtual and message paths remain separate. | | [Settings](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_settings.h) | A | [SETTINGS_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SETTINGS_EVENTS.md): Applied navigation/built-in values/text/reset; custom controls and custom reset hooks separate. | | [Sheet](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_surface.h) | A | [SURFACE_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SURFACE_EVENTS.md): Retained completed-close only; existing decision policy separate; open/request/veto not notifications. | | [Sidebar](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_sidebar.h) | A | [SIDEBAR_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SIDEBAR_EVENTS.md): Rows, expansion, collapse and header/footer complete; GROUP pointer_activatable supports a11y, TREEITEM limitation remains. | | [StatusBar](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_chrome.h) | N | Rendering/container or child composition; successful submission is not activation. Child controls retain their own event contracts. | | [Tabs](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h) | A | [TABS_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TABS_EVENTS.md): Aggregate stable-ID selection; reorder/overflow/scroll lifecycle excluded. | | [Theme](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_theme.h) | H | Explicit value projection/loading and icon-loader policy; no ambient theme-change event bus. | | [TitleBar](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_chrome.h) | H | Reviewed host-service exception in [checkpoint](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/TITLE_BAR_EVENTS_SLICE.md): existing perform/close hooks remain synchronous services, not confirmed OS lifecycle or value notifications. No proposed observer implemented. | | [Toolbar](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_toolbar.h) | A | [TOOLBAR_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TOOLBAR_EVENTS.md): Aggregate command activation after paint/legacy callback; custom renderer opt-in. | | [Tree](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_tree.h) | A | [TREE_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TREE_EVENTS.md): Applied selection/expansion and invocation; intermediate reducer state preserved. | | [VirtualList](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_virtual_scroll.h) | A | [VIRTUAL_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/VIRTUAL_EVENTS.md): Base/Styled aggregate final float-offset observers; deferred rendered window remains result-only and can lag one frame. Rows own item events. | | [Chart](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_chart.h) | H | Typed hover/result and tooltip/render policy; callbacks may run during layout/prepaint/paint with current-frame borrowed data. | | [Command](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_command.h) | A | [COMMAND_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMMAND_EVENTS.md): Base operations and Styled forwarding implemented. Query-before-old-hook exception preserves borrowed query lifetime; cancel is separate. | | [DataTable](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_table.h) | A | [TABLE_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TABLE_EVENTS.md): Sort/selection/set snapshots/columns/actions/ROW requests; viewport/load-edge still result-only. | | [Plot](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_plot_view.h) | H | Existing prepaint appearance callback and hover/result; deferred resolver/paint lifetimes must remain through render completion. | | [Table](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_table.h) | N | Rendering/container or child composition; successful submission is not activation. Child controls retain their own event contracts. | | [TextView](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_text_view.h) | T | Existing on_link borrows decoded URI/event, on_reveal requests viewport movement. No common selection/link metadata facade; copying struct does not own URI. | ## Updated implementation disposition Command Base/Styled forwarding and Scrollable Base/Styled pairing are implemented. TitleBar remains an explicitly reviewed host-service exception: host dispatch success is not confirmed OS state, and existing host/close hooks already provide synchronous extension points. TextView keeps its typed link/reveal callbacks; focused contract tests and copying guidance were added without changing dispatch. The original coverage matrix remains a historical checkpoint, not a current absence claim. HoverCard and Tooltip now have final open-model observers. Focus Trap bracketing and virtual-window completion are explicitly accepted primitive/result exceptions in the [lifecycle checkpoint](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/LIFECYCLE_RESULT_EVENTS_SLICE.md). VirtualList now exposes aggregate final-offset observers. MessageScroller now exposes exact double-offset/following-tail observers. Deferred window completion remains result-only and is not a claimed callback API. No universal lifecycle coverage is asserted. Foreign binding allowlists remain separately bounded. The follow-up list records the original review plan; the status above supersedes completed/in-flight descriptions in that historical plan. ## Remaining review boundaries The earlier follow-up plan has landed for Command forwarding, Scrollable, HoverCard/Tooltip, VirtualList and MessageScroller. TitleBar, Focus Trap and TextView retain the documented typed/host/composition exceptions. Current classification is A45, N18, H8, T7, G0 across exactly 78 families. This is a **disposition count**, not uniform event semantics or complete family parity. Further work must target demonstrated application needs rather than repeat those slices. Deferred virtual-window/render completion stays result-only; applied notification is not a controlled request or veto. Optional visibility observers describe the open model, not pixels or animation completion. Retained Carousel, Notification, Questionnaire, Resizable, Dock and Speech keep their explicit registration/pump/user-lifetime rules. A future metadata adapter must separately preserve those rules and existing mutation/ordering behavior. Foreign binding coverage below remains narrower than direct C. Full platform and accessibility acceptance also remains separate from headless event evidence. Each future behavior change needs strict public headers, legacy comparisons, owned-copy and ordering tests plus private-display CTest; no desktop or GPU proof is implied. ## Binding coverage is a separate axis [Initial V1](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_NOTIFICATIONS.md) exposes CLICK, audited boolean/table and surface-close views. [Opt-in values](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_VALUE_NOTIFICATIONS.md) add only: - SCALAR: Slider, NumberInput, Rating, Pagination. - TEXT: Input, Textarea, Editor, InputGroup. - SELECTION: RadioGroup, Tabs, Select, List, Stepper. Python, JS/TypeScript, Go and Rust have owning manual value polls documented in those guides. They preserve the existing shared queue, aggregate producer timing, full historical handles and uint64 frames, bounded capacity negotiation, optional symbol availability and LEGACY downgrade. Rust static builds require their paired SDK; dynamic availability does not promise mismatched static-library compatibility. These are applied bridge notifications, not exports of the new synchronous C request handlers, per-transition C selection observers or Slider gesture phases. No foreign synchronous rejection, callback auto-fanout or independent queue exists. Menu/Dropdown, Combobox, dates/time/color, Tree/Sidebar/Command/Dock/Settings and other unaudited values are not newly typed by resemblance. Plain bridge text has no secure/masked model configuration: direct C secure redaction is not a promise about legacy bridge bytes. Future secure support must cover both typed and legacy copies before exposure. Bridge Item slot/generation handles are not Core uint64 IDs. C selection intermediate transitions and query/submit reasons cannot be recovered by parsing the existing final JSON payload. The next binding slices should audit actual enqueue producers individually, capture typed data at enqueue without JSON parsing, negotiate categories on the same queue, and test real queued UI input separately from synthetic protocol fixtures. Preserve old/new polling interleave, FIFO/capacity atomicity, removal and historical generations, malformed-tag failure, older-library no-drain, UTF-8 ownership and numeric precision in every language. A new C facade alone does not close any of these binding gaps. ## Verified delivery checkpoints The Scroll/Command/Sidebar checkpoint at `5da9648f` passed the warning-enabled native build and all **292/292** CTest cases through the private-display wrapper (87.12 seconds). Scroll additionally passed 5/5 WASI and 5/5 ASan/UBSan cases. The subsequent Hover Base/Styled and standalone Content dependency changes passed 6/6 applicable native cases, 5/5 ASan/UBSan cases, 4/4 WASI suites, strict generated all-implementation C11 syntax, 11/11 documentation tests and 11/11 skill tests. This is broad baseline plus focused subsequent proof, not a claim that the earlier 292-case run included APIs added afterward. All 78 manifest entries remain intact. The separately rebuilt optional async host example passed 5/5 deterministic offline cases at `5da9648f`, including actual SDL frames and pending-work shutdown under private Xvfb. Cancellation means immediate logical invalidation plus cooperative transport cancellation subject to configured timeouts, not a hard real-time abort. No networking or worker pool was added to Core. Unsupported GPU hardware and physical macOS/Wayland behavior remain outside this headless proof. Go/Rust owning notification integration also passed a fresh 52/52-case run after the Command/Sidebar/InputGroup fixes and before Scroll/Hover additions. That proof includes actual older-library no-drain behavior and static/dynamic SDK cases; it neither exports the newer native observers nor implies foreign synchronous request acceptance. Binding omissions above remain explicit. No new hash-pair claim is made for that run. --- ## Component event API: requested work Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_REQUEST.md # Component event API: requested work Status: design checkpoint committed; shared metadata is the first implementation slice under integration. Family adapters and async host example remain in progress. This document defines requested work, not an implemented API or approved design. The contract, exact 78-family coverage matrix and binding audit live alongside this request. Their exceptions preserve queued, retained and deferred delivery. Before production changes, commit independently reviewable artifacts covering: - Existing state ownership, results, callbacks, typed payloads, dispatch timing, handler/userdata retention and payload lifetimes for every interactive family. - Proposed shared contract, alternatives, compatibility strategy and slices. - Binding support distinguished from documented omissions and justified exceptions. Scope includes buttons, inputs, checkboxes, switches, toggles, sliders, selections, menus and dialogs. Preserve component-specific semantics; identical interfaces and every event category on every component are not requirements. The design must distinguish activation, proposed value requests, confirmed value notifications, submission and lifecycle events. Preserve typed values without untyped value pointers. Define shared metadata and handler/userdata conventions. Acceptance/rejection, input consumption, propagation and platform default prevention are separate decisions; none implies another. General capture/bubble dispatch requires explicit architectural justification. Specify synchronous callback ordering, multiplicity within a frame, disabled/loading/inert and omitted behavior, reentrancy, callback-driven state changes and supported removal/shutdown. Context destruction during dispatch is unsupported unless explicitly designed otherwise. Preserve available pointer, keyboard and accessibility evidence without fabricated metadata. Specify payload ownership, borrowed lifetimes, safe deferred copies, allocation bounds and whether handler/userdata are submission-borrowed or retained. Keep convenient frame results with explicit aggregation: reading results must never dispatch callbacks, replay mutations or repeat interactions. Applications choose one side-effect path. Compatibility wrappers must preserve legacy timing, ordering and mutation behavior; end-of-frame callback movement is observable. If the design requires a new input-dispatch architecture, incompatible ownership or breaking behavior, complete the proposal and report the architectural decision before implementing that change. Otherwise proceed through compatible slices. ## Separate async host example Use one explicitly documented optional host/network stack, reusing supported dependencies where possible. Keep networking and thread pools out of Core. Handlers enqueue URL fetches and return promptly. Demonstrate loading feedback, duplicate prevention, worker-owned request data, synchronized completion delivery and waking an idle UI loop. Apply UI changes and call CUI on the UI thread. Cover failure/retry, stale responses, cancellation and shutdown with pending work. Distinguish logical cancellation from actual transport cancellation and test the precise guarantee with injected transport and controlled completions. Tests require no external network. Blocking I/O in a synchronous handler still blocks the UI thread. ## Verification and delivery Audit legacy tests first. Add meaningful headless tests for ordering/multiplicity, acceptance independently of consumption, callback/result coexistence, inactive and omitted components, payload/userdata lifetimes, callback-driven mutation, supported teardown, available input evidence and all async lifecycle cases. Retain behavioral legacy regressions, not compilation alone. Preserve portable C11, dependency direction and all 78 manifest entries. Update applicable bridges, bindings, examples, human/LLM documentation, source metadata, generated distributions and consumer skill guidance. Generate skill resources with the existing tooling; never edit generated files by hand. Build with warnings and use `python scripts/test_local.py --build-dir build` for Linux native checks. Browser tests are headless; unsupported GPU checks stay deferred. Commit completed verified slices. Final delivery includes the completed matrix, exceptions, real API examples, compatibility/migration guidance, binding support, tests and limitations. Do not claim uniformity from partial coverage. Workers leave merging and pushing to the integrator. --- ## Compound shadow parts: proposed identity contract Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPOUND_SHADOW_PARTS.md # Compound shadow parts: proposed identity contract Design checkpoint against `08a00f0b`, following the [78-family ownership audit](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/ELEMENT_SHADOW_COVERAGE.md). **Proposal only:** no API, painter, binding, generated file or runtime evidence is added by this document. Review this contract before implementation. This slice covers rectangular painted surfaces and their existing controls; it does not finish all 78 families. ## Constraints and scope Expose additive typed getters for existing IDs, then make the corresponding painters call those getters/the same private mapping functions. Do not re-key any box, callback argument, interaction, focus target, semantic parent or tracked bounds. Do not add wrapper boxes, shadow masks, callback passes, allocations, retained state, portal layers or styles. Unstyled command streams and node/command capacity behavior must remain byte-for-byte unchanged. No public struct grows. The existing [Core element setter](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui.h#L679) remains the only styling operation: submit the owner, then apply a copied list before `end_frame`, outside measurement/prepaint/diagnostics. Getters are side-effect-free identity computations. They do **not** look up current bounds, initialize state, open an overlay, submit paint, report visibility or promise a part exists. An ID returned for an omitted/virtual/closed/layout-only owner does not authorize styling it; Core must continue rejecting unavailable targets. `cui_bounds` alone may describe prior layout and must not become a presence gate. Return `0` for root/scope `0`, unsupported enum, invalid index, null scroller state, or invalid logical notification key `{0,0}`. Getter failure emits no diagnostic and changes no output/state. Do not add a generic ID-space registry or claim collision-free hashes. Preserve a legacy derived zero rather than remapping it: that result cannot be targeted by the element setter. Existing nonzero-remapping behavior in the media helper stays exactly as it is. ## Proposed public surface Proposed declarations below are illustrative C11, using only existing portable public types. Enum values should be explicit contiguous values starting at zero; no platform/Clay types enter the headers. There is deliberately no generic integer `part` escape hatch exposing all internal padding/hash slots. ```c /* cui_content.h: applies to composed cui_bubble(), not cui_begin_bubble(). */ typedef enum { CUI_BUBBLE_PART_SURFACE, CUI_BUBBLE_PART_REACTIONS } cui_bubble_part; cui_id cui_bubble_part_id(cui_id bubble, cui_bubble_part part); /* cui_message.h */ typedef enum { CUI_MESSAGE_PART_AVATAR, CUI_MESSAGE_PART_HEADER, CUI_MESSAGE_PART_FOOTER } cui_message_part; cui_id cui_message_part_id(cui_id message, cui_message_part part); cui_id cui_message_body_id(cui_id message, size_t body_index); /* index < 256 */ typedef enum { CUI_MESSAGE_SCROLLER_PART_VIEWPORT, CUI_MESSAGE_SCROLLER_PART_JUMP } cui_message_scroller_part; cui_id cui_message_scroller_part_id(cui_id scroller, cui_message_scroller_part part); cui_id cui_message_scroller_row_id(cui_id scroller, const cui_message_scroller_state *state, size_t index); /* cui_status.h: scope is the ID passed to cui_notifications[_checked](). */ typedef enum { CUI_NOTIFICATION_PART_CARD, CUI_NOTIFICATION_PART_CONTENT, CUI_NOTIFICATION_PART_ACTION, CUI_NOTIFICATION_PART_CLOSE } cui_notification_part; cui_id cui_notification_part_id(cui_id scope, cui_notification_id logical_id, cui_notification_part part); /* cui_media.h */ typedef enum { CUI_ATTACHMENT_PART_CARD, CUI_ATTACHMENT_PART_MEDIA, CUI_ATTACHMENT_PART_MEDIA_OVERLAY, CUI_ATTACHMENT_PART_METADATA, CUI_ATTACHMENT_PART_ACTIONS, CUI_ATTACHMENT_PART_REMOVE, CUI_ATTACHMENT_PART_MEDIA_RETRY } cui_attachment_part; cui_id cui_attachment_part_id(cui_id attachment, cui_attachment_part part); typedef enum { CUI_ATTACHMENT_CHILD_PART_ROW, CUI_ATTACHMENT_CHILD_PART_RETRY } cui_attachment_child_part; cui_id cui_attachment_child_part_id(cui_id attachment, size_t child_index, cui_attachment_child_part part); /* index < CUI_ATTACHMENT_MAX_CHILDREN */ ``` Keep existing `cui_message_scroller_jump_id`, `cui_attachment_remove_id` and `cui_attachment_retry_id` symbols and results. New aliases must agree with them for supported nonzero roots; no deprecation or behavior change is needed. Existing callers passing zero to those old helpers retain their old behavior; the new zero-validation contract must not be retrofitted onto legacy helpers. ## Exact mappings and ownership In this table `content_child`, `message_child`, `status_child`, `media_id` and `notification_element` mean the **current private functions**, not public hash recipes for consumers. Implementations must reuse them. These expressions are review evidence, not a recommendation to copy constants into applications. | Facade / proposed part | Existing owner to expose | Submission and callback limits / exact source | | --- | --- | --- | | `cui_bubble`, SURFACE | `content_child(root,3)` | Actual rounded surface inside row/width wrappers; [composition](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_content.c#L636), [begin surface](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_content.c#L485). `cui_begin_bubble(id)` already paints directly at `id`; applying the composed getter to that ID is incorrect. | | `cui_bubble`, REACTIONS | `content_child(root,5)` | Same pill ID in flow and measured absolute placement; absent without reactions callback. Do not target child4 alignment or child6 spacer. [Both branches](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_content.c#L539). | | `cui_message`, AVATAR / HEADER / FOOTER | `message_child(root,1/3/7)` | Avatar is painted clipped round box; metadata getters identify slot rows, not callback-owned descendants. Slots may be omitted by the existing plan. [Avatar/slots](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_message.c#L51), [composition](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_message.c#L109), [footer](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_message.c#L157). | | `cui_message`, body index | `message_child(root,20+index)` | Typed body: actual `cui_begin_bubble` surface. Untyped body: slot row, not an invented bubble. Custom slot renderer receives a different child namespace and owns its own boxes. `index < 256` matches existing admission; getter cannot know current body count/type. [Body loop](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_message.c#L127), [limit](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_message.c#L25). | | `cui_message_scroller`, VIEWPORT | `message_child(root,100)` | Existing clipped scrolling content viewport; offset includes virtual before/scroll projection. Not the outer root or a particular message. [Viewport](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_message.c#L229). | | `cui_message_scroller`, JUMP | Existing `cui_message_scroller_jump_id(root)` | Actual painted/interactive jump box, **not** positioning portal child600 or callback namespace child601. Appears only when enabled with positive jump opacity. [Portal and button](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_message.c#L289). | | `cui_message_scroller`, row(state,index) | `message_child(root,(size_t)state->rows[index].key+200)` | Side-effect-free **state-derived** getter: validate `index < state->count`, read retained key, never create/measure/reconcile a row. Exists as a Core box only for rendered range/overdraw. Key follows existing splice bookkeeping; index is a lookup coordinate, not identity. [Row paint](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_message.c#L235), [key allocation/splice](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_message.c#L163). | | `cui_notifications[_checked]`, CARD | `notification_element(scope,logical_id)` | Actual card portal; no box exists at the supplied scope ID. Fully hidden cards may be `layout_only`; system-only notifications have no card. [Derivation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_status.c#L476), [portal/layout-only](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_status.c#L769). | | Notification CONTENT / ACTION / CLOSE | `status_child(card,302/301/300)` | CONTENT is the real clipped content column. Default ACTION is a button only with action label; custom `action` receives this namespace but need not submit a box. CLOSE is actual button inside positioning portal313, emitted only hovered/expanded. Do not target portal313 or glyph315 instead. [Content/action](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_status.c#L842), [close](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_status.c#L867). | | `cui_attachment`, CARD / MEDIA | `root` / `media_id(root,3)` | CARD is actual chip/card inside outer overhang wrappers; MEDIA is clipped thumbnail/glyph frame only with media enabled. [Card/media](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_media.c#L397). | | Attachment MEDIA_OVERLAY | `media_id(media_id(root,3),5)` | Existing positioning portal for optional `media_overlay`; callback receives child6 namespace, not this owner. Requires usable tracked media bounds; may be absent on first layout. [Overlay](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_media.c#L477). | | Attachment METADATA / ACTIONS | `media_id(root,4/5)` | METADATA column only when content enabled. ACTIONS is actual cluster box or portal with the same ID in horizontal/vertical forms. Custom action callback receives `media_id(root,6)` and owns any real buttons. [Metadata](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_media.c#L211), [action cluster](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_media.c#L503). | | Attachment REMOVE / MEDIA_RETRY | Existing remove/retry getters | REMOVE is button inside positioning portal8. MEDIA_RETRY is the existing retry button used by failed media, not a universal textual retry link. [Legacy getters](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_media.c#L16), [media retry](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_media.c#L454), [remove](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_media.c#L536). | | Attachment child ROW | `media_id(media_id(root,4),index+1)` | Actual title/description row; CUSTOM child receives same namespace without an automatic row box. Do not fabricate a wrapper around the callback. [Child loop](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_media.c#L211). | | Attachment child RETRY | `media_id(cui_attachment_retry_id(media_id(root,4)),index+1)` | Actual description retry link only when existing first-eligible failed-description logic emits it. Index is original child-array index, not filtered/visual order. The metadata helper receives `media_id(root,4)` as its own local root: neither `cui_attachment_retry_id(root)` nor a child of that card-level ID names these links. [Link derivation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_media.c#L259). | No getter is proposed for spacers, fade strips, legacy shadow-ring portals, progress raster strips, icon paths, text glyphs, title/status tint regions or custom callback namespaces without a known automatically submitted owner. Their styles/callbacks remain separate concerns. Native OS notification cards are host owned and cannot acquire a Core shadow through an in-app getter. ## Notification identity, collisions and lifetimes Three different identities must stay explicit: - **Logical notification ID** `{type,key}` belongs to model replacement/dismissal, callbacks and optional OS delivery. `{0,0}` is already invalid for push ([validation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_status.c#L88)). Never cast its key to paint ID. - **Scope ID** is the caller's namespace for one in-app stack rendering. The same logical notification rendered in another scope derives a different card; scope does not itself imply an emitted paint node. - **Card paint ID** derives from scope plus the full existing logical-ID mixing function. Part IDs derive from that card. Getters must preserve current `size_t` conversion and arithmetic, including existing architecture limits; do not promise identical cross-architecture IDs or 128-to-64-bit injectivity. The logical pair is not collision-free after folding into a `cui_id`. Two model entries can be distinct while deriving the same card or folded Core ID. Tests must demonstrate existing duplicate-ID rejection and no partial decoration of another owner, not silently salt/remap/merge them. Hash redesign would alter legacy identities and requires a separate review. A computed ID owns no memory. It is useful only with the same scope/root and logical record/current composition. Model replacement retaining a logical ID retains the paint identity; dismissal completion removes presence, not the pure mapping. Scroller row IDs instead depend on live bookkeeping state and retained row keys: unaffected rows keep IDs across insertion/removal shifts; reset/newly inserted rows get the existing new keys. Do not cache an index as stable identity or call a state-derived getter after destroy. Existing collection/state lifetime through `end_frame` remains unchanged. Numeric body/child positions identify positions, not application-level stable keys after reordering. ## Implementation seams and review gates Use the [content child helper](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_content.c#L23), [message child helper](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_message.c#L36), [notification/card helper](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_status.c#L476), [status child helper](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_status.c#L278) and [media helper](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_media.c#L8) as the single derivation sources. Do not reproduce their salts in public headers, tests or bridge code. For row lookup, reuse the existing private row-key representation; Base and component currently mirror the private scroller state. If extraction is needed, share one internal header/accessor rather than introducing a third layout copy or moving platform/theme dependencies into Base. Public prototypes belong only to the four owning headers above; no Core API change is proposed. Painters should consume the semantic mapping at the same call sites, without moving callbacks or changing `cui_interact` order. Notification custom action and Attachment custom child/action callbacks retain their existing namespace IDs and phase; no post-paint callback is added. After a compound painter returns, callers may style its actual completed named boxes before `end_frame`. Pure getters may also be used outside a frame, but the element setter may not. Legacy root helper behavior, duplicate diagnostics, callback count/order and fixed array limits remain authoritative. ## Required focused evidence before accepting implementation | Area | Headless acceptance fixture | | --- | --- | | Exact ownership | Record legacy emitted IDs by observing draw/layout/semantics and callback arguments, then compare before/after getter integration. Check facade root versus surface boxes and independently tracked bounds; do not derive expected values by copying salts or merely compare getter to painter using the same new helper. Freeze representative baseline IDs or compare a retained pre-change fixture. | | Getter validity | Zero roots/scopes, unknown enums, body index256, child index128, null/out-of-range scroller state, logical notification `{0,0}`; no diagnostics/state mutation or new allocations. Valid-but-not-present IDs still compute without a fake presence result. Preserve old zero-input helper behavior and any derived-zero edge. | | Bubble / Message | Composed surface versus row, direct begin/end surface, reaction in-flow versus absolute placement retaining ID, optional slots, typed/untyped/custom bodies, 0/256 bodies and rejection257; alignment and custom renderer arguments unchanged. Apply/clear mixed shadows to surface without decorating row or sibling. | | Scroller | Prepend/splice/reset and changed indices retain the correct row-key identity; offscreen row getter still returns identity but setter rejects absent row. Only current visible/overdraw rows submit. Jump disabled/fading/visible cases, callback namespace versus row box, viewport clip/offset and current-frame scroll geometry. Destroy/lifetime contract must be enforced by caller, not dereferenced in a test. | | Notification | Same logical ID in distinct scopes; replacement/dismissal/ending/full removal; in-app/system-only/both delivery; collapsed hidden `layout_only` cards; hover/expanded conditional close; default action label versus custom action with/without a submitted box; same callback count/phase and logical ID payloads. Explicit logical-pair and folded-ID collisions reject decoration transactionally. | | Attachment | Horizontal/vertical card, media omitted, loading/failed/complete, first-frame and resolved-bounds media overlay, actions in flow versus portal with identical ID, custom metadata/action renderers with no box, multiple description rows and first eligible retry mapping, remove hover/touch conditions. No added wrappers to make absent parts styleable. | | Core style integration | Current-frame move/resize, open/closed boxes, ordinary/absolute/portal owners, prior-frame/omitted/layout-only rejection; copied eight-layer DROP/INSET list, clear and invalid transaction, ancestor clip/opacity, existing underlay/outline/prepaint ownership, unchanged interaction/semantics. No new command/node use on unstyled path; opt-in command exhaustion follows existing rollback and diagnostic behavior. | | SDK/docs/bindings boundary | Matching canonical headers, consumer examples, coverage metadata, generated SDK/amalgamation/skill resources and offline skill checks. Do not implement or claim a retained binding facade as part of getter tests. Native/browser/GPU proof, if later needed, remains separately declared and isolated. | Tests should be focused portable/headless fixtures; there is no reason to open a native desktop window to prove ID mappings. No build or test ran for this design checkpoint; link/count checks are documentation checks only. ## Future bridge mapping: MAIN is not automatically ROOT This is a mapping proposal, **not a new binding API or claim of support**. The retained facade should resolve an explicit semantic target after the relevant painter has submitted it, with per-frame deferred application for portals. Never use previous bounds as proof of presence or retain pointers into immediate paint. Distinguish unsupported/absent targets from success; do not decorate a fallback row when the requested surface was omitted. Callback-only namespaces are not paint targets unless the callback actually submits the corresponding box. | Current facade | Future ROOT / MAIN decision | | --- | --- | | Bubble | ROOT = node ID (outer row); MAIN = composed SURFACE getter. REACTIONS explicit and conditional. Current facade calls composed `cui_bubble` ([site](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/bridge/cui_bridge.c#L4648)). | | Message | ROOT = node ID stack; MAIN = body0 **only for the bridge's current known typed single body** ([site](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/bridge/cui_bridge.c#L4675)). General C multi-body content requires explicit index; no arbitrary first-body rule becomes a C guarantee. | | MessageScroller | ROOT = node ID clipped shell; MAIN aliases that shell, not an arbitrary message or the translated content canvas. VIEWPORT/JUMP explicit. A child bridge Item already renders Message at **its own node ID**, ignoring callback namespace; its MAIN should use that Message's body0. Scroller row(state,index) is not a substitute for child Item identity ([callback](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/bridge/cui_bridge.c#L3633), [facade](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/bridge/cui_bridge.c#L4497)). | | Notification | There is no per-node Core ROOT: the bridge tree case submits nothing ([site](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/bridge/cui_bridge.c#L4486)). Reject ROOT as unsupported rather than silently target the shared stack/scope or alias another node. MAIN = CARD at existing shared notification scope and logical `{1,node->id}`. Apply after deferred shared-stack rendering ([logical ID](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/bridge/cui_bridge.c#L2133), [stack site](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/bridge/cui_bridge.c#L4954)); explicit CONTENT/ACTION/CLOSE follow emitted owners. Changing ROOT to an alias would need an explicit separate facade contract. | | Attachment | ROOT and MAIN both = actual card node ID; MEDIA/MEDIA_OVERLAY/METADATA/ACTIONS/REMOVE/MEDIA_RETRY/child parts explicit. Current limited bridge options do not expose all C callbacks/media; do not infer binding option parity from getters ([site](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/bridge/cui_bridge.c#L4687)). | Follow-on bridge work must specify authoring validation, retained style ownership, when absent targets retry or remain unavailable, and atomic frame failure before shipping MAIN/ROOT or typed subparts. It must keep existing facade APIs/default paint unchanged and preserve the six-kind worker's independently owned contract. ## Implemented C slice The additive typed getters described above are implemented without public struct layout changes. Existing painters keep their raw zero-owner derivations; the new getters reject zero owners. Message's private derivation now lives in Base and is shared by its painter and getters; the row getter uses the existing Base state, with no additional private layout copy. Focused warning-enabled tests pass through the private-Xvfb wrapper: `compound_shadow_parts`, `compound_shadow_legacy` and `element_shadows`. The independent legacy fixture was captured/replayed before rebuild from the preserved pre-change library; its provenance and 64-bit little-endian scope are in [the consumer guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMPOUND_SHADOW_PARTS.md). It verifies unchanged IDs, commands, semantics and callback ordering for nonzero and zero-owner scenes. The getter fixture checks current-frame owners, closed/conditional/custom parts, retained-row identity, capacity boundaries, Notification collision/layout-only behavior and Attachment flow/portal identity. SDK/amalgamation freshness and the 18 offline agent-skill tests also pass. The expanded 12-test headless slice includes existing family/Base-only regressions and selective/umbrella generated- header C11 declaration/link checks against the rebuilt library. These checks do not establish browser/GPU rendering or language-builder target parity. The future bridge table remains a proposal only. Implementation sign-off: `/root/hidden_windows`, 2026-10-31. Additive C getters only; legacy fixture unchanged; no public struct/ABI layout change, no bridge or Core input-architecture changes. Root integrator owns merge/publication. --- ## Private CPU V2 owned-frame extraction checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/CPU_V2_OWNED_FRAME_EXTRACTION.md # Private CPU V2 owned-frame extraction checkpoint This refines `SDL_RENDERER_V2.md` after mechanical relocation `9ee20d6f`. It is a proposal and measurement fixture, not an implemented renderer feature. No SDL/public API or Core change is included. Actual native/WASM text/no-text measurements satisfy the 2048-byte frame guard; production extraction still requires root review of this checkpoint. ## Exact proposed retained control fields The measurement-only `tests/unit/cpu_v2_frame_layout_proposal.h` defines: - `state`: EMPTY, PREPARING, READY, RELEASING. - `self`: address sentinel rejecting a copied/moved live ownership handle. - `workspace`: existing CPU/metadata pointers, capacities/used counters, free callback/user and existing workspace teardown guard. - `pixels`, `width`, `height`, `stride`, `bytes`: READY tight RGBA output view. - With text compiled: embedded counted `text_owner` and `text_session`; the latter points to the former at its final address throughout recording and teardown. No duplicate font owner/64-face table, retained options copy, font pointer, command pointer, descriptors or clip stack is required in the frame. Commands, background/shadow descriptors and glyph-range metadata retain their existing workspace storage until release. After READY, painting is finished; the output needs only its packed view and live ownership blocks. Borrowed font/input graphs remain stable through release, matching the existing transaction contract. The request has width/height, three explicit `{pointer,bytes}` exclusions, checked count and optional owner-busy pointer. Frame and request records are automatically excluded before reading command resources. The old software wrapper supplies its owner, published pixel span and old target-view exclusions. No externally published destination is required by the common prepare operation. ## Narrow extraction and preserved behavior Move the existing body into private prepare without changing its validation, planning arithmetic, allocation order, command order, filters or byte arithmetic. Pure validation may inspect EMPTY control but must not mutate it. After all pure preflight, set PREPARING and owner busy at the current first-callback boundary. Use embedded workspace/text owner/session directly; never copy live owners. Prepare the same resources and completely paint the existing scratch allocation. Only then publish the tight output view and READY. No additional allocation or second CPU image is introduced. No source lifetime is shortened. The legacy helper keeps its signatures and target validations. It uses one local frame, prepares, copies active rows to the old target, and releases before clearing `target->busy`. It preserves the original published-target exclusions and optional owner-busy contract (the initialized adapter clears that flag after return). Allocation request vectors, peak bytes, callback order and old pixel/padding oracles must remain exact. V1 software functions and fixed object layout remain untouched. Existing private name/path forwarders remain available. Init on a zero/EMPTY frame allocates nothing. Init must not retire a live frame. Prepare on non-EMPTY or a copied live sentinel returns LIFECYCLE without callbacks. Release on EMPTY is harmless; PREPARING/RELEASING release is a no-op and cannot clear outer busy or queue cancellation. READY release enters RELEASING before the first callback, ends text session, ends workspace, then canonicalizes EMPTY. Preparation failure uses an internal teardown owner: it enters RELEASING before cleanup and returns EMPTY, never calls the public release on PREPARING. Recursive free callbacks cannot double-free. The adapter retains busy through later native cleanup; this frame does not own or clear the adapter's lifecycle guard. ## Measurement and gates `test_cpu_v2_frame_layout.c` exports compact integer object constants for frame size/alignment, every ownership/output offset, request/workspace/plan sizes, 64-entry clip-stack bytes and conditional text-owner/session offsets/sizes. Compile native and pinned WASM with/without CUI_HAS_TEXT without linking/running. Record compiler/flags/source hashes and four actual layouts before extraction. The frame is fixed stack control separate from heap quotas. Report one frame + request + existing clip-stack/plan storage, not a total compiler/dependency stack bound; scalar spills/call frames and dependency stacks remain additional. After production approval, test EMPTY repetition, READY lifetime, PREPARING allocation/provider reentry, RELEASING recursive free, attempted init/prepare/move, all allocation failures and retry. Assert no output/guard publication before pure preflight, no double free, stable session.owner, and exact callbacks/order. Retain frozen old/new allocation/layout/pixel and all command/text fixtures. Exercise both no-text and no-Bidi rejection, resource aliases, target padding, owner exclusions and complete READY bytes independently of a destination. Register actual CMake tests and copied SDK closure. SDL transport remains a separate gate. ## Actual four-layout measurement GCC 16.2.1 native and pinned Zig 0.16.0 Clang wasm32-unknown-wasi compiled C11 at O2 with UNDEBUG, Wall/Wextra/Wpedantic/Werror; no engine link or execution. The retained Zig Clang driver uses explicit pinned WASI/include roots for -S. System Zig 0.17.0 first rejected its cc-driver-generated unused -c under -Werror; that diagnostic remains in the local log, with no warning suppression. | Layout | Frame / align | Request | Workspace | Plan | Named owners subtotal | | --- | ---: | ---: | ---: | ---: | ---: | | Native no text | 120 / 8 | 72 | 72 | 80 | 2320 | | Native text | 808 / 8 | 72 | 72 | 80 | 3008 | | WASM no text | 64 / 4 | 40 | 36 | 40 | 2192 | | WASM text | 412 / 4 | 40 | 36 | 40 | 2540 | Subtotal = one frame + request + one existing 2048-byte clip stack + plan; it is explicitly not total stack usage. Text owner/session are already inside frame (native 656/32 bytes, WASM 332/16); no duplicate is counted or proposed. Full offsets, source hashes and exact commands are in the measurement receipt. --- ## DataTable typed transition checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/DATA_TABLE_EVENTS_SLICE.md # DataTable typed transition checkpoint Design only, audited at `d342f4d5`. Preserve the [shared contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_CONTRACT.md), [family inventory](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_COVERAGE.md#L111) and [binding exceptions](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_BINDINGS.md#L310). Stateless composable Table is not DataTable: child controls retain their own events. No new dispatch, render timing, public legacy layout, sorting algorithm or bridge schema is proposed. ## Actual owners, timing and results [Public API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_table.h): model binds borrowed rows and mutable columns transactionally; stable nonzero keys are unique within each dimension. Columns move/resize in place. State owns controlled primary row/column, separate navigation/header cursors, sort key/direction, scrolling/drag bookkeeping, and a borrowed multi-selection workspace/count/capacity. Rows are not sorted by changing sort state: the application owns data ordering/rebinding. Selection options are passed by value; a requested mode does not rewrite the caller's options. [Reducer](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_table.c#L609) validates inputs, normalizes cursor and scroll bookkeeping, processes input in order, then computes final viewport and load-more flags. It has no existing behavior observer. Important distinctions: - `selection_changed` is overwritten at return with entry/final primary ID and multi count/XOR-hash comparison. A->B->A can vanish; hash equality is not an exact selection transcript. `sort_changed` is set on each eligible header activation even if repeated cycling returns to entry. `columns_changed` ORs successful resize/move operations. None of these bools counts transitions. - [Selection helper](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_table.c#L386) normalizes IDs by row/column/ cell mode. Multi selection supports replace, Ctrl/Meta toggle and Shift range, skipping disabled rows/disabled or nonselectable columns. Capacity checking can reject an operation after earlier operations succeeded. Capacity error does not roll back previous changes. Escape clears primary IDs, anchors and selection. - `manual_selection` suppresses navigation-driven selection, not cursor/focus movement. `nonselectable` blocks selection without disabling sorting, resizing or interactive cell children. Preserve separate per-mode disable flags. - [Row-header path](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_table.c#L550) can apply row selection and also report `selection_mode_requested=ROW`; that request is not permission to undo the already-applied selection. `activated_row/column` retain the latest cell/row-header activation, including potential no-op/rejected selection. - Secondary press sets the latest context row/column independently of selection. Header sort, resize and move paths coexist with focus and selection in one input iteration. The loop does not globally skip every consumed event; do not add such filtering or reinterpret child-control behavior during this work. - [Resize/move helpers](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_table.c#L179) return actual changes: resize clamps width and rejects unchanged values; move enforces bounds, fixed-column region, movability and disabled policy. Drag threshold is >4px; Cancel/Escape clears gesture bookkeeping without restoring prior resize widths. Do not invent commit/cancel rollback events from these fields. - Post-input wheel, reveal, clamping and scrollbar passes compute final visible windows. First submission marks windows changed. `load_more` is edge/pending state near the end, reset by leaving the threshold, changed row count or turning the option off. Disabled/loading cancel gestures and suppress input/load-more while other bookkeeping remains active. [`cui_base_data_table`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_table.c#L1170) reduces then submits semantics for OK/CAPACITY. [Styled](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_table.c#L390) resolves theme scrollbar policy before reducing once, then paints virtual rows/columns, headers/groups/trailing slots/placeholders and cells. Render/label callbacks are presentation/accessibility producers, not legacy change handlers. Per-transition observers would run inside reduction, before final semantics and every render callback; do not claim final geometry/semantics are already refreshed. No retained observer registration is needed. Deferred child/renderer lifetimes still apply. ## First scalar transition API New `cui_table_events.h`; no fields added to old state/options/result. Proposed first declarations (land sort first, single-selection next; declare only the supported fields/functions at each reviewed production checkpoint): ```c typedef struct { cui_component_event_metadata event; cui_table_selection previous, value; cui_table_selection_mode mode; /* Effective operation mode, including row header. */ } cui_table_selection_change; typedef struct { cui_component_event_metadata event; cui_id previous_column, column; cui_table_sort previous, value; } cui_table_sort_change; typedef void (*cui_table_selection_change_fn)(void *, const cui_table_selection_change *); typedef void (*cui_table_sort_change_fn)(void *, const cui_table_sort_change *); typedef struct { cui_component_event_metadata event; cui_id column; float previous_width, width; } cui_table_column_width_change; typedef struct { cui_component_event_metadata event; cui_id column; size_t previous_index, index; } cui_table_column_move_change; typedef void (*cui_table_column_width_change_fn)(void *user, const cui_table_column_width_change *event); typedef void (*cui_table_column_move_change_fn)(void *user, const cui_table_column_move_change *event); typedef struct { cui_table_selection_change_fn on_selection; cui_table_sort_change_fn on_sort; cui_table_column_width_change_fn on_column_width; cui_table_column_move_change_fn on_column_move; void *user; } cui_table_event_handler; typedef struct { cui_table_result control; /* Unchanged old result/error, not callback counts. */ bool valid, submitted, count_overflow; size_t selection_count, sort_count; /* Actual synchronous calls. */ size_t column_width_count, column_move_count; } cui_table_event_result; cui_table_event_result cui_table_reduce_events(cui_context *, cui_id, cui_table_model *, cui_table_state *, cui_table_options, cui_table_event_handler); cui_table_event_result cui_base_data_table_events(cui_context *, cui_id, cui_table_model *, cui_table_state *, cui_table_options, cui_table_event_handler); cui_table_event_result cui_data_table_events(cui_context *, cui_id, const cui_theme *, cui_table_model *, cui_table_state *, cui_table_options, cui_table_label_fn, cui_table_cell_fn, void *, cui_table_event_handler); ``` Use a private common reducer with the old entrypoint's unobserved path; do not wrap final result bools. Capture scalars/metadata at each actual operation, mutate once, then notify exact pair or sort-key/direction inequality. Emit A->B->A and sort cycles individually; same-value selection emits no CHANGE. Preserve legacy result flags even when their interpretation differs from typed counts. One input can select then sort: callbacks follow those existing write points, not an invented family ordering. Keep successful earlier notifications when later operations fail. First selection support is explicitly **single selection only**. If a non-NULL `on_selection` is supplied with `multiple_selection`, the new API must return `valid=false`, `control.error=CUI_TABLE_INVALID` before reduction/paint; no silent partial coverage. Sort-only/nil observers may still reduce multi-selection using unchanged legacy behavior. Missing callbacks ignore userdata and preserve writes. This restriction belongs only to the additive facade, never the old API. Root must review it before production; full multi support is the next independent slice. ## Multi-selection: reviewed API and workspace This reviewed interface is now implemented in the independent multi-set slice. Keep the scalar API's `on_selection + multiple_selection` rejection. Add a distinct set-observation family, rather than changing scalar payload interpretation: ```c typedef struct { const cui_table_selection *items; size_t count; } cui_table_selection_span; typedef struct { cui_table_selection *previous, *value; size_t capacity; /* Entries in EACH array, not combined bytes. */ } cui_table_selection_workspace; typedef struct { cui_component_event_metadata event; cui_table_selection previous_primary, value_primary; cui_table_selection_mode mode; /* Effective operation mode. */ cui_table_selection_span previous, value; } cui_table_selection_set_change; typedef void (*cui_table_selection_set_change_fn)(void *user, const cui_table_selection_set_change *change); typedef struct { cui_table_selection_set_change_fn on_selection; cui_table_sort_change_fn on_sort; cui_table_column_width_change_fn on_column_width; cui_table_column_move_change_fn on_column_move; void *user; } cui_table_set_event_handler; typedef enum { CUI_TABLE_SET_PREFLIGHT_OK, CUI_TABLE_SET_PREFLIGHT_INVALID, CUI_TABLE_SET_PREFLIGHT_WORKSPACE_CAPACITY, CUI_TABLE_SET_PREFLIGHT_OVERLAP } cui_table_set_preflight; typedef struct { cui_table_event_result events; cui_table_set_preflight preflight; } cui_table_set_event_result; cui_table_set_event_result cui_table_reduce_set_events(cui_context *, cui_id, cui_table_model *, cui_table_state *, cui_table_options, cui_table_selection_workspace, cui_table_set_event_handler); cui_table_set_event_result cui_base_data_table_set_events(cui_context *, cui_id, cui_table_model *, cui_table_state *, cui_table_options, cui_table_selection_workspace, cui_table_set_event_handler); cui_table_set_event_result cui_data_table_set_events(cui_context *, cui_id, const cui_theme *, cui_table_model *, cui_table_state *, cui_table_options, cui_table_label_fn, cui_table_cell_fn, void *, cui_table_selection_workspace, cui_table_set_event_handler); ``` `events.control` remains the legacy result, including aggregate flags and partial operation errors. `events.selection_count` counts actual set callback calls, `sort_count` actual sort calls, with existing saturation/overflow policy. Callback order follows existing write points. No other handler fields are exposed. With a NULL set callback, ignore workspace and userdata (unless sort uses userdata), allow either selection mode, and preserve the sort-only/legacy path. With a non-NULL set callback, require `multiple_selection=true`; this family does not silently reinterpret single-selection state as a set. ### Atomic preflight and alias contract Before **any** reducer bookkeeping, callback, semantics or Styled painting: 1. Validate existing reducer arguments and multi count/capacity invariants without normalization/writes. Require nonzero root ID and valid mode/sort fields, as in the scalar facade. Non-NULL set callback with single selection is INVALID. 2. For set observation, require `state.selection_capacity <= workspace.capacity <= 4096`. Both scratch arrays contain `workspace.capacity` writable entries. A zero capacity permits NULL arrays; a nonzero capacity requires both pointers, suitable alignment and overflow-safe byte extents. Count must not exceed state capacity; the state selection pointer is required when that capacity is nonzero. Scratch shortage reports WORKSPACE_CAPACITY; invalid pointer/alignment/extent, impossible count/capacity or oversized declared capacity reports INVALID. 3. Reject overlap between the **full declared** scratch byte extents, and between either scratch extent and the state object, state selection's full capacity, opaque model object, bound row descriptors or bound mutable column descriptors. These known ranges are available to the private Base implementation. Empty ranges do not overlap. Reject unrepresentable extent/address endpoints before arithmetic; compare checked integer address intervals on supported targets providing `uintptr_t`, never order unrelated C pointers or subtract IDs. Any detected overlap reports OVERLAP. Do not accept two partially overlapping views just because their currently used counts are small. For multiple simultaneous errors, use the above order, with argument/extent INVALID checks preceding capacity shortage and overlap checks. A failure returns `events.valid=false`, `events.submitted=false`, zero counts/overflow, `events.control.error=CUI_TABLE_INVALID`, and the separate precise preflight code. State, columns, both scratch arrays and input consumption remain byte-for-byte unchanged. This intentionally distinguishes facade workspace failure from a later **legacy selection operation** returning CUI_TABLE_CAPACITY. Once preflight succeeds, `preflight=OK` even if a subsequent operation fails; preserve earlier mutations/notifications and legacy Base semantics-on-OK/CAPACITY policy. Scratch is caller-owned exclusive storage for the complete call, including callbacks and render consumption. It must also not alias context/internal model allocations, label/group/string bytes, render or handler userdata, or other live resources. Those arbitrary/opaque allocations cannot all be introspected: their nonaliasing and actual allocation size/readability are explicit caller preconditions, **not** claimed runtime checks. Passing a dangling pointer is not made safe by interval checking. Workspace is passed by value, so no retained workspace descriptor or descriptor lifetime/alias rule is needed. The proposal must not claim universal alias validation from the enumerated checks. ### Exact operation snapshots without allocation Capture primary IDs and copy the current selection entries to `previous` before each actual selection helper/Escape operation. Run the original operation once, then capture primary IDs and copy entries to `value`, even on a partial error. Do not snapshot merely cursor movement or every internal range-array write. Canonicalize each copied span by unsigned lexicographic `(row, column)` order using an iterative in-place binary heapsort: bottom-up heap construction, then max-root extraction/sift-down. Use bounded indices (`root < count/2` before forming children), direct ID comparisons, no subtraction comparator, recursion, `qsort`, variable-size stack array, allocator or sorting of the owner's array. Maximum scratch is exactly `2 * workspace.capacity * sizeof(cui_table_selection)` bytes, supplied by the caller; extra algorithm storage is O(1). Compare counts, primary pairs and sorted entries exactly. Duplicate multiplicity is retained, not deduplicated or repaired: caller-populated duplicates remain truthfully visible under legacy behavior. Storage-order-only changes produce no CHANGE; same set with changed primary does. Deliver one callback per operation with a real multiset/primary difference, including A->B->A in one frame. An accepted no-op or rejected range with no change emits none. Operation failure after actual change must notify that observed change without changing its error. Effective row-header mode and genuine input metadata follow scalar conventions. For a logical operation with n before/m after entries, observation costs O(n log n + m log m) time and O(n+m) copies/comparison, bounded by 4096 entries per snapshot. The existing reducer's range-generation/model lookup cost is unchanged; this is not a claim that the whole reducer is O(n log n). No quadratic set-membership scan is introduced. Scratch reuse avoids per-input allocation. Payload spans are sorted, borrowed and readable **only during the callback**; copy their entries explicitly for retention. Copying the payload struct alone retains dangling/overwritten views. Handlers cannot mutate owner/workspace/model or recurse; no per-item delta, rollback, safe owner mutation or undo promise. ### Required independent production evidence Test all three facades against unchanged legacy results/owner/paint; set+primary changes, same-set order permutations, duplicate multiplicity, exact UINT64 keys, Ctrl toggles, Shift ranges, row/column/cell and row-header mode, Escape, repeated net-zero input, no-ops and capacity errors after progress. Freeze callback spans into test-owned storage and verify subsequent scratch reuse. Exercise both identical and partially overlapping buffers, aliases into state/selection/rows/ columns/model, zero/max capacity, short scratch, count overflow, misalignment and checked extent overflow; failed preflight must preserve state/columns/scratch and input consumption. Do not dereference fabricated invalid pointers in such tests. Pair NULL observer behavior and passive/disabled/loading cases with legacy paths. Test sorted/reverse/equal-key maximum-size heapsort cases, comparator edge IDs, and instrument comparison counts with a generous O(n log n) bound; do not use wall-clock thresholds. Public C11/C++ header checks and private-wrapper CTest remain required. The independent multi-set slice verifies maximum-size snapshots and uses an external instrumented comparator check for the complexity bound. No test instrumentation hook is added to the public API or production source. ## Subsequent independent slices and aggregate exceptions 1. Implemented column CHANGE: distinct pointer-free `{event, column, previous_width, width}` and `{event, column, previous_index, index}` payloads at actual successful resize/move calls, including pointer moves, keyboard resize, Ctrl reorder and drag drop. Indices are operation-time positions; stable column key remains authoritative. No begin/commit/cancel gesture vocabulary until a separate lifecycle audit. 2. Repeated cell/row-header ACTIVATE, context request and mode request: capture at their actual branches, including same-item activation and several context requests per frame currently collapsed in results. Keep activation separate from selection success. Mode REQUEST concerns caller-owned options; ignoring it does not reject/roll back an already-applied row selection. Context REQUEST asks the application to decide popup behavior. No callback return/rejection hook. 3. Viewport/load-more: justified aggregate completion observations, once after reveal/clamp/scrollbar calculations. Emit a typed final rows/columns view with initialization/old window-index facts; do not invent an unavailable old full view or causal wheel event. Load-more observes the actual pending edge, not dataset completion or a network instruction. No synchronous fetch in Core. Only active ordinary enabled/nonloading submissions notify input transitions; passive/layout-only/disabled/loading preserve old normalization/bookkeeping. Aggregate viewport initialization/load policy needs explicit passive tests before activation; no blanket no-mutation promise. Use shared CHANGE/ACTIVATE/REQUEST only where the above meaning applies. Input metadata has root table target and actual frame/index/source when known; HAS_ACTIVATION only when a real snapshot exists. Semantics are submitted after reduction, so never fabricate it. Aggregate completion metadata is UNKNOWN/HAS_FRAME only. No bubbling or new input routing. ## Lifetimes, regression evidence and bridge omissions Callbacks/user borrow synchronously. Stable IDs/scalars are pointer-free copies; model rows, mutable column descriptors, labels, state, selection buffers, group headers/render userdata and any new snapshot workspace keep their existing submission/render lifetimes. Cell label callback must return readable stable borrowed bytes; render callbacks still run only for the virtual window. Typed observers may copy payloads or update unrelated application state, but must not rebind/sort/resize/move model storage, mutate state/workspace, recurse, destroy context/resources or unwind foreign exceptions. Defer edits/removal/teardown until submission and renderer consumption complete. No new retention mechanism. Keep [table tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_table.c) and [selection contracts](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_table_selection_contracts.c) unchanged: virtual/load pending, sort cycles, nonselectable child buttons, manual navigation, row/column/cell mode gates, resize/move/fixed columns, context and row-header mode requests are existing obligations. New per-slice tests should use real queued pointer/key/supported accessibility input, repeated/net-zero transitions, no-ops, capacity after progress, exact copied IDs, optional handlers, frozen metadata, callback-before-render traces, disabled/loading/passive behavior, and paired old/ new owner/result/semantic/geometry/paint comparisons. Add exact multi set snapshots, range/capacity/duplicate-entry policy and workspace bounds/disjointness tests before that API exists. Strict C11/C++ and private-display wrapper checks follow production; this design checkpoint runs no builds and makes no accessibility parity claim. [Bridge rendering](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/bridge/cui_bridge.c#L3628) still calls the old Styled API, emits at most aggregate selection and sort notifications, and returns on any table error before queuing changes. [V1 table payloads](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/bridge/cui_bridge.c#L2839) already preserve uint32 row/column/sort fields, alongside copied legacy JSON; they do not expose native per-transition multiplicity, cui_id-width keys, complete multi sets, column movement/resize, activation/context/mode requests or load edges. Python/Node/Go/Rust manual polling remains a separate post-step queue contract. Do not replace it or claim native observer parity from these new C declarations. ## Implementation checkpoints Sort now has a private common reducer with optional typed observation and additive reduce/Base/Styled facades. Old paths call the reducer without an observer and retain legacy flags/consumed-event handling. Only implemented sort handler/count fields were public at the sort checkpoint. Single selection now adds an optional primary-pair handler at actual selection operations and Escape, preserving their order relative to sort and later result/semantic work. Non-NULL selection handler with multiple_selection is rejected before reduction/paint; nil/sort-only handlers keep old multi behavior. Multi-set/workspace APIs now use the reviewed separate facade, atomic preflight, exclusive scratch buffers and iterative exact multiset comparison described above. Column width/move now notify only successful reducer helper calls, with copied stable keys, pre-operation metadata and actual before/after values/indices. Both scalar and set handlers/results expose the implemented callbacks/counts. Public programmatic helpers remain silent. No activation/context/mode/viewport slice is included. Legacy gesture/cancel and callback-before-paint timing are preserved. --- ## Remaining DataTable events checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/DATA_TABLE_REMAINING_EVENTS_SLICE.md # Remaining DataTable events checkpoint Audited at `4aa3c3d0`. The independently approved activation/context slice is now implemented; mode requests below remain a design checkpoint awaiting their own production slice. This supplements the [original checkpoint](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/DATA_TABLE_EVENTS_SLICE.md), follows the [shared contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_CONTRACT.md), and preserves the current [implemented facades](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TABLE_EVENTS.md). The activation/context implementation adds only the reviewed native facade fields/counters and narrow reducer seams. No new dispatch, Core behavior, bridge schema, generated files or 78-family manifest entries change. ## What the remaining results mean The [public result/options](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_table.h#L109) combine input facts with reduction-completion facts. They are not one callback transcript. Model rows/columns and state remain caller-owned; options, including selection mode, are passed by value. Changing sort state does not reorder application rows. Existing scalar/set/column observers already cover applied value transitions. | Domain | Actual seam and information | Recommended treatment | | --- | --- | --- | | Cell activation | [Cell branch](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_table.c#L1032): accepted activation attempts selection, sets reveal, then writes latest activated row/column. Same-value or failed selection still activates. | Per-accepted-action ACTIVATE, independent of CHANGE. | | Row-header activation | [Row-header branch](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_table.c#L725): attempts effective ROW selection, writes activated row, then possibly requests ROW mode. | Per-accepted-action ACTIVATE with explicit ROW_HEADER area. | | Context request | [Row header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_table.c#L717) and [header/cell](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_table.c#L954): secondary POINTER_DOWN writes target IDs. Does not apply selection or open a popup. | Per-branch REQUEST identifying area and exact keys. | | Selection-mode request | [Row header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_table.c#L729): activation or eligible navigation asks caller to use ROW options, after selection was already attempted in ROW mode. | Per-branch REQUEST; notification of intent, no rejection/rollback hook. | | Visible windows | [Completion](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_table.c#L1168): current full views plus flags comparing prior begin/end indices, initialized on first submission. | Keep the existing aggregate result; not a per-input scroll event. | | Load more | [Completion](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_table.c#L1176): near-end pending edge, suppressed by disabled/loading and reset by leaving threshold, row-count change or option off. | Keep the existing edge result and application-owned asynchronous work. | Important compatibility details: - `activated_row/column` retain last writes, not counts. Row-header activation writes **only row**: after an earlier cell action in the same call the final aggregate can contain that cell's column with the later row-header row. Do not reconstruct a typed action from the returned pair, clear the old column, or reinterpret this legacy aggregate while adding observers. Keyboard actions use the reducer's effective cursor, which need not equal the original routed child's key after prior navigation; freeze those actual branch facts, not a target-ID reconstruction. - Activation is not selection success. Nonselectable cells, selection-only disabled policies, unchanged selection and CUI_TABLE_CAPACITY can still reach the accepted-action branch. No inferred `applied`/`committed` bool is justified. Header sorting/selection already has typed observers; do not add a generic header-invoke callback merely alongside them in this slice. - Context facts refer to the actual hit item, independently of controlled selection. Header requests have row=0; row-header requests have column=0. Header/cell paths reject disabled columns and disabled rows as appropriate; row-header handling rejects disabled rows but works independently of disabled data columns. Global disabled/loading suppresses the input loop. - Row-header mode requests are not options mutations. Activation requests ROW whenever row selection is enabled, even when options already say ROW or the selection operation failed. Navigation requests ROW when a candidate exists, manual selection is off and row selection is enabled. HOME/END can identify the current row and still request mode; do not deduplicate that intent into a value CHANGE. Manual navigation can move focus without a request. The flag being false makes `requested_selection_mode` non-actionable. - Drag/cancel, child controls, routing and consumed-event treatment remain as implemented. The Table loop does not globally skip consumed events. Adding such a filter or treating observer input consumption as rejection would change behavior. A real header drop is not a cell action or context request. ## Reviewed input slices and exact payloads Extend only the existing additive `cui_table_events.h` facades; preserve old public state/options/result layouts and all entrypoints. Both scalar and set handlers must gain the same implemented fields, before `user`, only as each slice lands. The unreleased additive structs require rebuilding clients; use designated C initializers. No retained registration or extra workspace is needed for these pointer-free facts. ```c typedef enum { CUI_TABLE_ACTION_CELL, CUI_TABLE_ACTION_ROW_HEADER } cui_table_action_area; typedef struct { cui_component_event_metadata event; /* ACTIVATE */ cui_table_action_area area; cui_id row, column; /* ROW_HEADER always column=0. */ } cui_table_activation; typedef void (*cui_table_activation_fn)(void *user, const cui_table_activation *event); typedef enum { CUI_TABLE_CONTEXT_CELL, CUI_TABLE_CONTEXT_ROW_HEADER, CUI_TABLE_CONTEXT_COLUMN_HEADER } cui_table_context_area; typedef struct { cui_component_event_metadata event; /* REQUEST */ cui_table_context_area area; cui_id row, column; } cui_table_context_request; typedef void (*cui_table_context_request_fn)(void *user, const cui_table_context_request *event); typedef enum { CUI_TABLE_MODE_FROM_ACTIVATION, CUI_TABLE_MODE_FROM_NAVIGATION } cui_table_mode_request_reason; typedef struct { cui_component_event_metadata event; /* REQUEST, not an applied mode CHANGE. */ cui_table_selection_mode current, requested; /* Current options snapshot. */ cui_id row; /* Effective row at this operation, not a retained row pointer. */ cui_table_mode_request_reason reason; } cui_table_mode_request; typedef void (*cui_table_mode_request_fn)(void *user, const cui_table_mode_request *event); ``` 1. **Implemented activation and context slice:** add optional `on_activate` and `on_context_request`, and shared result counters `activation_count` and `context_request_count`. These recover repeated accepted attempts and repeated requests hidden by the old last-value results. Count actual synchronous calls, saturating with the existing `count_overflow`. Context does not synthesize activation. No coordinates, menu ownership, acceptance return or popup lifecycle are promised; caller can identify the item with keys/area and existing ID helpers. 2. **Implemented independent mode-request slice:** independently add `on_mode_request` and `mode_request_count`. This is deliberately separate from selection CHANGE: the application decides next submission's options, but ignoring the request does not undo the current effective ROW selection attempt. No generalized controlled-selection or options-rejection protocol is introduced. A missing callback ignores unused userdata and retains every old write. Existing scalar `on_selection + multiple_selection` rejection and set-workspace preflight remain unchanged, including atomic failure before callbacks. New input observers must also work with sort/column-only set handlers and ignored workspace when the set-selection callback is NULL. Do not expose the later slice's fields early. ## Ordering, evidence and lifetime Freeze exact IDs, effective area/mode/reason and metadata at the actual branch before the first potentially user-calling selection operation. Do not reconstruct IDs from the final result or look up a moved descriptor after another observer. Preserve source order and existing observer timing: - Cell: selection attempt/optional CHANGE, old activated-pair writes, ACTIVATE. - Row header: selection attempt/optional CHANGE, old activated-row write, ACTIVATE, old mode-request writes, REQUEST if the legacy flag is true. - Row-header navigation: update navigation cursor, selection attempt/optional CHANGE, old mode-request writes, REQUEST, then existing focus/reveal work. A mode callback must not assume focus has already moved. - Context: old context writes, REQUEST at that branch, then existing cursor/ header/navigation handling. It must not assume the context item is selected. Metadata target is the table root. Preserve the actual activation snapshot where available; frame/index/source are genuine operation evidence. Secondary press has POINTER_DOWN provenance but normally no activation: extend the private source classification for this actual input, never fabricate HAS_ACTIVATION. Navigation requests use their real key event, not reconstructed activation. Unknown evidence remains absent. All these callbacks precede final semantics and Styled rendering; none promises refreshed bounds or final viewport state. Callbacks and userdata borrow through the current submission. Payloads can be copied by value; they contain stable native IDs and no row/text pointers. Existing borrowed row/column/label/group/render storage and renderer-consumption lifetimes still apply. No mutation/rebinding/sorting of active owner/model/workspace, recursive submission, destruction or foreign unwinding is supported. Record application intent and defer changes/teardown until the outer call and renderer consumption finish. No retained observer registration or automatic binding fanout. ## Justified completion-result exceptions The original checkpoint tentatively suggested aggregate completion observers. This revision recommends retaining result-driven consumption instead: no extra transition facts were found to justify those callbacks yet. Do **not** add `on_scroll`, `on_visible_rows`, `on_visible_columns` and `on_load_more` merely to replay existing aggregate fields. The existing result already provides the complete supported completion observation once per call: - Final `rows/columns` follow wheel processing, reveal, clamp and Base scrollbar reduction. Their windows use overscan=0; Styled rendering can visit a larger overscanned window. Header/fixed regions have separate layout rules. - Visible flags compare only entry bookkeeping's begin/end indices, not pixel offset or total/width/height changes. First submission marks both flags, even without input. Earlier full views were never stored; only prior indices are available. A same-window pixel scroll is not a missing transition callback. - `load_more` means a newly raised pending edge, including an enabled empty table. It does not mean data arrived, a fetch started/completed, or an accepted request. Supplying data/new row count can re-arm the edge; a pending bit is not a network cancellation or generation mechanism. - Disabled/loading suppress user actions and the load edge, but normalization, initialization and bookkeeping still run. Inert/layout-only submission removes normal input interaction, not this aggregate computation: do not promise an unconditional no-result-change/no-load-edge rule for passive submissions. Keep caller code reading `result.control` (or `set_result.events.control`) after submission and scheduling application work there. This is an explicit aggregate exception, not missing per-transition coverage. Do not add multiple callback side effects alongside the same result use. If a concrete consumer later requires a common completion hook, review **one** separate opt-in completion snapshot after all reducer bookkeeping, before semantics/paint: include initialized/prior-index presence, current full views, changed flags and load edge. It would carry UNKNOWN/HAS_FRAME only when an active frame is proven, no index/source/activation, and no claimed old full view or per-wheel attribution. That future hook is not part of the recommended production slices here. [Styled](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_table.c#L394) resolves theme scrollbar policy before reducing once, then paints. Its late [scrollbar call](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_scroll.c#L59) accepts const state and paints; do not move callbacks into paint or rerun reduction to obtain a viewport. Base wrappers submit semantics for OK/CAPACITY; invalid preflight/arguments do not produce input callbacks. Earlier successful observations survive later capacity errors, as in the existing facades. ## Required evidence and explicit omissions Keep [legacy Table](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_table.c), [selection contracts](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_table_selection_contracts.c) and [typed transitions](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_table_events.c) unchanged in meaning. Add actual queued pointer/key tests through reducer/Base/Styled scalar and set facades, with real Styled geometry priming where Base has no painted bounds: - Repeated same-cell and same-row-header activation, several different items in one frame, selection-disabled/nonselectable activation and capacity rejection; exact copied keys above 2^53/near UINT64_MAX and mixed cell then row-header action whose legacy aggregate retains the earlier column. Verify counts and action area. - Secondary presses on cell/row/column headers, repeated context requests with unchanged owner selection, disabled row/column distinctions and mixed action/ request traces. No popup creation or simulated primary activation as a shortcut. - Mode requests with options CELL and already ROW; activation versus navigation; manual navigation, row-selection-disabled, same-row HOME, repeated requests and capacity-after-progress. Verify selection CHANGE -> ACTIVATE -> mode REQUEST order where applicable and mode callback before later focus work. - Missing callbacks/non-NULL userdata, passive/global disabled/loading, consumed input compatibility, callback copies and deferred teardown intent; paired old/new results, owner arrays/state, semantics, geometry and paint. No active owner edits inside test observers. Strict C11/C++ checks and private-wrapper CTest per slice. - Preserve existing aggregate evidence: first windows, near-end pending/no replay, row-count re-arm, empty table and loading placeholders. Add targeted passive and same-window pixel-offset evidence before any later completion-hook proposal. Current Core permits accessibility FOCUS for these focusable roles, but its [ACTIVATE allowlist](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/core/cui.c#L1246) excludes ROWHEADER/COLUMNHEADER/ GRIDCELL unless explicit pointer_activatable evidence exists. Table submission sets no such override. Test supported focus and rejected ACTIVATE truthfully; no role remap, raw input fabrication or full accessibility parity claim. The [bridge](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/bridge/cui_bridge.c#L3650) still calls legacy Styled Table, queues aggregate selection/sort only, and returns early on Table errors. Native activation/context/mode multiplicity, exact cui_id keys and completion facts are not exposed by initial V1 or the additive value extension. Python/Node/Go/Rust polling remains a separate post-step owned-copy contract; these C proposals add no queued binding events, immediate handlers, request rejection or reordering. ## Activation/context implementation evidence The narrow reducer seam freezes effective IDs and metadata before selection observers, then delivers accepted actions at the old write points, including unchanged/selection-disabled/nonselectable/capacity attempts. Context remains a secondary-press request at its existing fields, with no activation or owner write. Scalar/set facades share the new fields/counters; NULL set-selection permits ignored workspace. Mode-request callbacks are now implemented independently; completion remains result-only. Tests preserve the bounded 256-element/1024-command context fixture while keeping 4096-entry selection coverage. Actual queued keys/pointers cover repeated actions, effective keyboard cursor IDs, mixed cell/row-header legacy column carry, metadata before selection-observer consumption, all three context areas, disabled versus nonselectable distinctions, passive/loading policies, optional observers, callback-before-paint and paired legacy owner/result/semantics/geometry/paint. Accessibility focus is exercised and ACTIVATE rejection checked at the public queue API. Payload copies/deferred teardown intent retain existing lifetime rules. Mode-request implementation checkpoint: both scalar/set facades report actual legacy ROW requests with causal facts frozen before selection observers and notification after old flag writes, before navigation focus/reveal. Verified legacy/facade comparisons across reducer/Base/Styled, repeated intents, manual/ disabled/loading/passive paths, nil-selection workspace, consumed input, exact pointer row keys and selection-capacity errors. No completion hook added. --- ## DatePicker date-only actions: proposed contract Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/DATE_PICKER_ACTIONS_CONTRACT.md # DatePicker date-only actions: proposed contract Reviewed contract, based on `b0405a3c`; implementation is isolated in the new actions files and private fixture. Canonical registration remains integrator-owned. Final validation evidence is recorded in the consumer guide. Scope: presets and clear actions, legacy-preserving Base/Styled composition; no date-time, new visual variants, lifecycle observers or Core dispatch changes. ## Proposed exact declarations New `include/cui/cui_date_picker_actions.h` includes `cui_date_picker_calendar.h`. All declarations use portable C11 existing types. ```c #define CUI_DATE_PICKER_PRESET_LIMIT 8u #define CUI_DATE_PICKER_LABEL_LIMIT 96u #define CUI_DATE_PICKER_TARGET_LIMIT 144u typedef enum { CUI_DATE_PICKER_SINGLE = 0, CUI_DATE_PICKER_RANGE } cui_date_picker_shape; typedef struct { cui_date_selection dates; cui_date_picker_shape shape; } cui_date_picker_value; typedef struct { cui_id id; cui_str label; cui_date_picker_value value; } cui_date_picker_preset; typedef enum { CUI_DATE_PICKER_PRESET_SOURCE = 0, CUI_DATE_PICKER_PRESET_MATCH_SHAPE, CUI_DATE_PICKER_PRESET_MATCH_SHAPE_ENABLED } cui_date_picker_preset_policy; typedef enum { CUI_DATE_PICKER_DELETE_OFF = 0, CUI_DATE_PICKER_DELETE_TRIGGER, CUI_DATE_PICKER_DELETE_SCOPE } cui_date_picker_delete_policy; typedef struct { cui_date_picker_options picker; cui_date_picker_calendar_options calendar; const cui_date_picker_preset *presets; size_t preset_count; cui_id clear_id; cui_str clear_label; bool cleanable; cui_date_picker_delete_policy delete_policy; cui_date_picker_preset_policy preset_policy; } cui_date_picker_actions_options; /* Separate retained Calendar selection is required for source policy. */ typedef struct { cui_date_picker_state picker; cui_date_picker_value calendar_value; cui_date_picker_value observed_value; bool synchronized; /* Previous submission identities, copied values only; do not edit directly. */ cui_calendar_state submitted_calendar; cui_id submitted_root, submitted_presets[CUI_DATE_PICKER_PRESET_LIMIT]; size_t submitted_count; bool submitted_open, submitted_clear; uint64_t prepared_frame, submitted_frame, clear_frame; cui_id prepared_root, prepared_trigger, submitted_clear_id; unsigned submitted_months, submitted_first_weekday; cui_id submitted_targets[CUI_DATE_PICKER_TARGET_LIMIT]; size_t submitted_target_count; } cui_date_picker_actions_state; void cui_date_picker_actions_init(cui_date_picker_actions_state *, cui_id popup, cui_date initial_month); typedef struct { cui_calendar_result calendar; bool valid; bool changed; bool action_activated; } cui_date_picker_actions_result; /* Inside caller-owned open popup scope, after a valid Base reduction. * Publishes bounded prior-submission identity only after full successful submission. * Semantics only: no reduction, callbacks or scope begin/end. */ void cui_date_picker_actions_submit_presets(cui_context *, cui_date_picker_actions_state *, cui_date_picker_actions_options); cui_date_picker_actions_result cui_base_date_picker_actions(cui_context *, cui_id trigger, cui_id calendar, cui_str name, cui_date_picker_actions_state *, cui_date_picker_value *, cui_date_picker_actions_options); cui_date_picker_actions_result cui_date_picker_actions(cui_context *, cui_id trigger, const cui_theme *, cui_str name, cui_date_picker_actions_state *, cui_date_picker_value *, cui_date_picker_actions_options); ``` The new state is necessary: frozen source owns independent picker and child Calendar selections. `init` initializes `picker` with the existing init, sets `calendar_value` to empty single and `synchronized=false`; the first successful preflight synchronizes the supplied outer value under the policy below. `observed_value` tracks the last processed outer value, not the child value. An externally changed outer value is synchronized once, never retried implicitly on every frame after child rejection. This prevents reopening/render from erasing a retained child divergence. A later matcher change alone does not retry it. The caller owns this state; no allocation or hidden retained pointer is introduced. `value.shape` is authoritative for the picker title and clear action. Child Calendar reduction/submission uses `state.calendar_value.shape` and dates; `options.picker.calendar.range` is ignored by this facade. All other picker and Calendar options are forwarded. An accepted complete child activation publishes its child value to the outer value even if the child date did not change (frozen Calendar emits Selected). Actual child edits additionally publish incomplete ranges, preserving CUI's partial-range behavior; upstream subscription delivery is completion-only. Navigation and rejected activation do not copy stale child values over the outer value. Legacy records/functions remain unchanged. Zero-action equivalence to legacy holds only when outer and child selections are synchronized; exact source divergence is new explicit state, not a claimed shared-selection legacy behavior. ## Defaults and eligibility Zero options have no presets, clear affordance or Delete action. The old functions are unchanged; synchronized zero-action calls preserve the corresponding `_ex` path with explicit shape. Divergence is documented separately above. Zero preset policy matches frozen source's shape-changing behavior: a valid single preset can replace a range and vice versa. Source policy accepts the outer picker value independently of child Calendar eligibility; it does not bypass basic validity or bounded preflight. The child sync then validates present endpoints using the live date predicate/bounds. A rejected child update leaves its selection, month/year, view and range phase unchanged while outer value/title changes and popup closes. An accepted nonempty child update replaces child selection, sets phase from endpoint shape and recenters month/year to its start; view and year-page state remain unchanged. This is the source-recentering path, independent of Calendar day-activation recenter policies. Using CUI min/max as well as its predicate is an explicit portable eligibility extension; frozen source uses its matcher. No range interior scan occurs. `MATCH_SHAPE` rejects a mismatched preset activation without mutation, but retains source-style eligibility bypass. `MATCH_SHAPE_ENABLED` additionally requires each preset endpoint to satisfy `cui_calendar_date_enabled` using live options. No interior range scan is implied. These policies have distinct enum values, not an overloaded validation boolean. Clear visibility and Delete are independent. `cleanable` shows a separate clear button only if at least one endpoint is present. Delete defaults off; `DELETE_TRIGGER` handles an unmodified Delete key whose resolved target is the trigger; `DELETE_SCOPE` additionally accepts a target within the open popup scope. Backspace, text input, modifiers and unrelated focused controls do not clear. The DatePicker owns no text-entry child in this slice. Outer `picker.disabled` gates trigger/preset/clear/Delete actions; Calendar-only disabled suppresses day input, not these independent actions. This distinction is documented rather than inferred from the child Calendar. Scope Delete must not intercept future editable children; introducing a time editor requires revisiting this explicit contract. An enabled clear empties the outer and child values while preserving outer shape; empty values cannot be rejected by the date predicate. It resets child `selecting_end`, preserves displayed month/year, view/cursors/year page, closes and performs **no explicit focus request**, matching `clean` rather than `set_open`. Existing overlay close helpers that restore focus must not be used unconditionally for this action; a private no-focus close seam may be necessary. Preset acceptance closes and **unconditionally requests trigger focus**, matching `select_preset`, even if focus was elsewhere. Outside dismissal retains existing conditional focus rules; these are separate paths, not one generic close policy. A clear/preset equal to the current outer value counts as accepted action but `changed` remains false. No observer emission semantics are introduced. `MATCH_SHAPE` rejects a mismatched activation atomically; for matching shape it retains source outer-accept/child-reject semantics. `MATCH_SHAPE_ENABLED` rejects mismatch or ineligible child endpoints before either selection changes. Accepted nonempty values in either policy use the same source-style child recenter/focus behavior. Externally supplied values always use source-style child synchronization once: an opt-in action rejection policy cannot reject a caller's assignment. The alternative architecture is to keep the old shared selection and expose only atomic enabled presets, with a name that does not imply source-equivalent policy. That smaller design cannot offer SOURCE semantics. This checkpoint recommends explicit separate child state if SOURCE remains required; integrator review is needed before implementing that state distinction. ## Preflight, capacity, identity and lifetime Before any focus/state/value changes or event consumption, validate all pointers, nonzero distinct trigger/calendar/popup IDs, enums, value shape, options and all preset records. `preset_count <= 8`; nonzero count requires an array. Each label is nonempty valid UTF-8 of at most96 bytes, without embedded NUL. Active clear support (cleanable or Delete policy not off) requires a nonzero distinct `clear_id` and nonempty bounded UTF-8 clear label. An inactive clear record is ignored, allowing exact zero defaults. Preset IDs must be nonzero, mutually distinct and distinct from trigger/calendar/popup/active-clear IDs. Known generated Calendar navigation/month/year/day/neighbor IDs for the current submission must not collide with action IDs; reject a detected collision during preflight. This is not a universal namespace proof: caller roots and action IDs remain subject to ordinary global collision discipline. Do not claim hash IDs are globally unique. Labels are borrowed through frame/render consumption; array/value records through the call. No pointers, handlers or predicate results are retained. Predicates remain pure and owner-thread only. Dates are either all-zero absent or valid Gregorian1..9999 values. A single value must have absent end; range permits empty, start-only or ordered complete dates, but not end-only or reversed endpoints. Presets must be complete: one date for single, ordered start/end for range. Basic invalidity in *any* preset rejects the entire options preflight, even if not activated. Eligibility rejection is an activation result, not invalid options. Preflight validates finite positive viewport/width/cell geometry under explicitly documented normalization rules; existing valid zero/default width/cell values retain legacy defaults. Calendar min/max/date/options validation must match documented legacy accepted defaults; new strictness must not silently label old valid options invalid. On preflight failure return all-zero result, including `valid=false`, and make no state/value/focus changes (including synchronization), consume no events, submit no control, and call no date predicate. Normal successful preflight sets `valid=true`. Subsequent layout allocation/overlay failure can still occur after reduction; `valid` is not a transactional rollback promise. Document/test this separately from preflight. ## Event ordering and one reduction Preserve the current outer pass order: Calendar-view Escape prepass, overlay outside-dismiss/trigger toggles, then one entire Calendar reduction. Resolve its original grid exactly as current `_ex` does; no second reduction/submission is allowed. New actions form a final pass over the original frame event order. Clear/Delete/preset targets are distinct from Calendar targets, so the earlier Calendar pass does not consume them. This is explicitly **phase ordering**, not global chronological interleaving between day and action events. Action eligibility uses the resulting live shape and current disabled-date predicate. Child and outer shape can differ under source policy; action shape matching always compares with the outer value. Only actions targeted to the prior submitted clear/trigger/open popup controls are accepted; closed popup stale preset IDs cannot reopen or edit. Snapshot whether popup action controls were eligible at the start of this call; current trigger toggling or Calendar auto-close cannot manufacture new submitted action targets. The final action pass accepts at most one action: the first eligible accepted clear/preset/Delete wins; consume only that event, then ignore later action events for this call. Rejected mismatch/eligibility actions do not win, mutate, close or consume. This prevents multiple presets after close and makes clear versus preset deterministic. A day edit may precede the winning action in the same call, consistent with preserved Calendar phase ordering. `calendar` reports the actual Calendar reduction result. `changed` compares the final value (including shape) with the value before this call; a later action that restores the original value yields false. `action_activated` reports one accepted action independently of net change. Do not pass these semantics through the old typed aggregate event wrapper without a separate review. Styled calls the common private reducer once, then paints trigger, separate clear hit target and up to8 preset rows, and submits Calendar using the existing presentation options. Base submits the same trigger/action semantics, with caller-owned layout/popup painting as in the current Base contract. Both share IDs, eligibility, queue/focus semantics and result. Styled uses bounded popup geometry; viewport clipping must not make hidden preset rows actionable. No new scroll service, style variants or custom renderer callback is included. ## Acceptance before production handoff Add a standalone private fixture with Base/Styled runs covering zero-action legacy equivalence, all three preset policies, shape changes, invalid-array last record atomicity, bad UTF-8/count/IDs/geometry, no predicate call on invalid preflight, disabled distinctions, empty and partial range clearing, modified Delete rejection, trigger/scope/outside targeting, original day+action phase ordering, first accepted action wins, stale closed-popup IDs, unconditional preset focus, clear with no explicit focus request, outside-dismissal focus rules and net-zero edits. Add retained child-rejection tests: outer title/value changes while child selection/month/view stay fixed; reopening does not silently retry; accepted child sync recenters month/year without resetting view/year page; clear empties divergent selections without matcher invocation; actual subsequent day edit resynchronizes values. Include software pixels and semantic names/ expanded/controls for the visible clear/preset controls; no live AT claim. Compile C11/C++ header probes and strict warnings. Run fixture via private Xvfb wrapper with meaningful sanitizers. Root owns canonical registration, bindings, metadata, skill and generated distribution updates after reviewing this contract. ## Transitive source evidence correction This revision supersedes the earlier incorrect “preset does not recenter” and conditional preset-focus statements. Frozen paths inspected together: `component/src/time/date_picker.rs:323–340,423–434,484–499,508–526` and `base/src/calendar.rs:118–124,217–235`. Accepted child `apply_date` changes date and current month/year only; rejected matcher updates change none of those. `sync_children` only shares matcher/time configuration and does not resynchronize child dates on each render. Clear emptiness bypasses matcher evaluation and preserves month/year because there is no start. These claims are source evidence, not executed upstream behavior or live focus/AT proof. ## Implemented split submission and identity expiry `cui_date_picker_actions_submit_presets(ui, state, options)` requires the same preflight-valid options and the caller's one open popup scope, after its Base reduction and Calendar submission. It submits semantics only, never replays input, predicates or callbacks. The mutable state receives bounded copied previous-submission identity only after all submissions succeed; failure clears its publication stamp. Duplicate helper calls are invalid Core submission. Base itself submits trigger/clear semantics, not popup semantics. The state stores the prior root/grid/month-count/week-start and at most 8 preset IDs, plus at most 144 actual enabled semantic target IDs, plus context-local prepared/submitted frame stamps. Omission, failed/missing helper, reinitialization and close/reopen invalidate eligibility. Trigger toggles and Escape invalidate the old popup action targets in the current action pass. A genuine previous Core event target/activation is required alongside those records and current policy/list membership. Scope Delete covers actual Calendar navigation, month/year headers and selector/day grids, not only preset buttons. No Core scope introspection or Surface dispatch changes are introduced. Caller must reinitialize before moving state to another context or manually reopening its overlay; a context pointer is not retained. Final identity review: reserved year/month conflicts use decoded part intervals and authoritative ID rechecks, not a 9999-year scan. Successful popup submission copies at most 144 actual enabled semantic targets; Scope Delete requires both that previous set and current view/grid/list eligibility. An absent/off-view generated ID alone is insufficient (Core focus fallback is described below). The private overlay reducer reports open state after its trigger/dismiss pass, before Calendar reduction, so outside-dismiss expiration is distinguished from the explicitly retained Calendar auto-close/action phase behavior. There is no shared Core routing change. Scope Delete excludes the nonfocusable popup root and requires an actually submitted enabled Calendar/preset semantic target plus current view/list eligibility. Tests cover previously submitted year/day targets made off-view before reduction and absence of unsubmitted IDs from the bounded record. Core redirects unknown programmatic focus to an eligible modal target before key dispatch; that resolved target, rather than the invalid requested ID, is authoritative. --- ## DatePicker Calendar extensions: audit and proposed contract Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/DATE_PICKER_CALENDAR_EXTENSIONS_SLICE.md # DatePicker Calendar extensions: audit and proposed contract Design checkpoint only. No declarations, implementation, coverage promotion or new observer are supplied by this document. Baseline: CUI `fca994fd`. Proposed public names below require review before production. ## Frozen evidence and actual coverage Reference checkout `/tmp/cui-upstream-reference`, exact commit `87d10ae5e1299d1be18670a37570c5402f952e34`: | Source | SHA256 | Relevant contract | | --- | --- | --- | | `crates/base/src/date_picker.rs` | `995c7e32ad660e7f1e96d1c429e90374b6479bc9cd8364568683c8305bc8715b` | Controlled composition root; application supplies trigger/calendar/positioning. `on_open_change`, Confirm toggle and Cancel dismissal; ComboBox semantics. | | `crates/component/src/time/date_picker.rs` | `e7c8c87c76b253703a955c578f28278212d54545d9c9a62a76892a3140095248` | Calendar subscription around lines 210–219, date selection/update around 403–431, child policy synchronization around 433–442, close/focus around 444–480, Calendar composition around 827–832. | The frozen Styled picker composes the real Calendar, forwards its month count, first weekday and sizing, and shares the disabled matcher. Its date-only selection path updates the date, closes and emits its own Change; time editing can deliberately retain the popup. Base has a separate controlled open-change callback. This proposal covers access to CUI Calendar capabilities, not frozen date-time/preset/cleanable/appearance or arbitrary styling parity, nor an equivalent source event lifecycle. Calendar source evidence and its explicit policy differences are recorded in `CALENDAR_SELECTION_POLICIES_SLICE.md` and `CALENDAR_KEYBOARD_LOCALIZATION_AUDIT.md`. Current CUI evidence: - `include/cui/cui_picker.h:86–104`: caller-owned overlay plus Calendar state; DatePicker options already contain the complete legacy `cui_calendar_options`. Locale/custom labels, first weekday, 1–3 months, range, cell size, min/max and live disabled policy are already reachable. Year navigation is already present; a new API must not advertise these as newly implemented. - `src/base/cui_picker.c:926–969`: DatePicker reduces Calendar through the zero-extension entry point, closes on accepted single selection or completed range, and submits the trigger's expanded/controls semantics. It does not submit popup Calendar semantics or own popup layout. - `src/components/cui_picker.c:311–394`: Styled reduces before popup creation; formatting is locale-aware; popup submits and paints Calendar with zero presentation. Consequently month toggle, today marker, neighboring occurrences and behavior policies are currently inaccessible through this operation. - `tests/unit/test_picker.c`, `date_picker_presentation`, `picker_year_escape`, `picker_events`: actual trigger/calendar glyphs and locale text, popup open/close, year Escape hierarchy, focus restoration, outside dismissal and disabled handling. - `tests/unit/test_picker_events.c`, `dates`: legacy-vs-facade equality, Italian accessible date labels, same-date close without CHANGE, incomplete/completed ranges, keyboard queues, late viewport failure after mutation, callback close/focus timing, null/invalid IDs and omission. These are existing evidence, not proof of the proposed extension. - `tests/unit/test_calendar_presentation.c` and `test_calendar_behavior.c`: extension reducer/semantics/paint and original-grid occurrence routing are tested as Calendar. Those results do not establish DatePicker popup integration. ## Recommended additive API New authoritative header `include/cui/cui_date_picker_calendar.h`, including `cui_calendar_behavior.h` (which includes presentation and legacy picker declarations). Do not resize any legacy public record or modify existing function signatures. ```c /* Proposed only. Value record; zero is the exact legacy DatePicker path. */ typedef struct { cui_calendar_presentation_options presentation; cui_calendar_behavior_options behavior; } cui_date_picker_calendar_options; cui_calendar_result cui_base_date_picker_ex( cui_context *, cui_id trigger, cui_id calendar, cui_str name, cui_date_picker_state *, cui_date_selection *, cui_date_picker_options, cui_date_picker_calendar_options); bool cui_date_picker_ex( cui_context *, cui_id trigger, const cui_theme *, cui_str name, cui_date_picker_state *, cui_date_selection *, cui_date_picker_options, cui_date_picker_calendar_options); ``` The existing options remain authoritative for locale/month count/year navigation/disabled policy/viewport/width/placeholder. The new record composes existing presentation and behavior types without copying their fields into a third competing schema. Existing invalid-enum fallback, invalid/omitted host-today handling and single-month-only month toggle apply unchanged. No ambient clock, locale lookup, ownership transfer or allocation is added. Keep existing required-pointer and ID behavior; strengthening legacy ID validation is outside this slice. Legacy functions delegate shared private bodies with a zero extension. Base calls `cui_calendar_reduce_with_behavior` once; Styled uses that Base body, `cui_calendar_submit_ex` and the existing paint helper with the same presentation record. Do not call a composed Calendar entry point after reducing: that would consume input twice and change close timing. The Base caller continues to position/open its overlay and submit Calendar with `cui_calendar_submit_ex` and the same presentation; no second reduction. Styled keeps its legacy bool, including false on late popup/viewport failure after an applied edit. Base retains the full aggregate Calendar result. A richer Styled lifecycle result is a separately reviewed addition; do not silently reinterpret the existing bool as an event count or success code. Optional helper to review with this API: `cui_id cui_date_picker_calendar_id(cui_id trigger)`, exposing Styled's existing private tag-900 Calendar ID for checked occurrence resolution and host integration. Return zero for trigger zero or a zero derived ID. No claim of collision impossibility; caller IDs retain the existing collision discipline. This is useful but not required for display: tests may inspect actual semantic IDs. A new helper must not reassign any legacy ID. Alternative: take presentation and behavior as two trailing arguments, matching Calendar. This avoids a wrapper type but makes long DatePicker calls harder to scan. Enlarging `cui_date_picker_options` is rejected because it changes an existing by-value ABI; introducing a new Calendar reducer or copying its state machine is rejected because it creates divergent routing and phase rules. ## Ordering, close and focus contract Preserve these stages exactly, including their existing limits: 1. If the popup began open in month/year view, the existing Escape prepass returns to days and focuses the year header before overlay dismissal. It scans the original event list; do not claim strict cross-stage chronology or that two queued Escapes equal two separate frames. 2. Update previous popup bounds, apply overlay dismissal, then process trigger activations in list order. Trigger toggles are a separate pass before Calendar reduction; arbitrary interleaved trigger/day events are not a new globally ordered dispatcher. 3. If still open, merge outer disabled into Calendar disabled and reduce Calendar once with the extension. Calendar preserves the original submitted grid/month plus date-and-panel target snapshot for its whole queue, while applying live pure policy checks per activation. Recenter must never reinterpret a queued cell as a different civil date. 4. After the full Calendar queue, close when `activated && (!range || !selecting_end)`. Do not close midway through the queue or truncate later Calendar activations. This final-phase aggregate rule differs from per-event close notification and remains unchanged. 5. Submit trigger semantics; Styled formats and paints its trigger, then either returns, closes on invalid viewport, or places/begins/submits/paints the popup. On newly opened popup it focuses the existing canonical cursor/year/month destination; close restores trigger focus through overlay logic. Preserve modal scope removal before further submission. Explicit policy consequences: earlier pending endpoint restart keeps the popup open; accepted completion closes; a rejected completed candidate with a newly disabled old start leaves both selection/phase and popup unchanged. Same-date single activation closes even without a value change. Year/month navigation and today decoration do not close or emit CHANGE. Opening must not reinitialize caller Calendar state, force days, recenter selection or resynchronize `selecting_end` merely because the new endpoint-shape policy was supplied. Changing policies while closed has no activation effect. Outer disabled closes the popup through existing overlay policy; Calendar-only disabled leaves the trigger operable and suppresses Calendar actions. Read policy resources live under the existing pure-predicate contract. If omitted, this component does not process input or synthesize dismissal. State/options/locale strings/predicate resources remain borrowed through the existing frame/render-consumption boundary. Extension values are copied and not retained. Base layout and Styled viewport clipping remain separate contracts, including bounded month geometry near years 1 and 9999. ## Observer and lifecycle gap: separate work Existing `cui_*date_picker_events` calls the legacy outer operation once, then compares final endpoints and optionally invokes one borrowed CHANGE callback. Styled notification occurs after painting, close/focus restoration and any late failure. Metadata target is the trigger, source UNKNOWN, with proven active-frame metadata only. It may notify an actual applied value change even when the legacy Styled bool is false after an invalid viewport. An incomplete range can notify; a completed same value, phase-only change, opening or dismissal cannot. Callbacks must defer teardown/UI mutation; unrelated application flags may change. Those wrappers must remain on the zero-extension path in this first slice. Do not wrap a Calendar observer inside DatePicker or claim that a returned aggregate result observes lifecycle. A future `*_ex_events` could reuse the same final-value CHANGE payload/timing around the extended outer operation, but requires explicit tests and separate approval. Frozen Base open-change and Styled date-only/time-completion notifications are not represented by this payload. Open/close reasons, per-activation delivery, exact pointer/key/AT causes, cancellation and controlled/rejectable requests require an independently designed lifecycle facade; they are not covered by this proposal. ## Implementation ownership and acceptance evidence Production would need the new header, Calendar/DatePicker-only private seams in `src/base/cui_picker.c` and `src/components/cui_picker.c`, a new `tests/unit/test_date_picker_calendar.c`, worker fixture and compiling guide. Do not touch ColorPicker/time fields. Canonical CMake, distribution implementation entry mapping, SDK source copies, metadata/usage mirror/skill and WASI registration follow integration ownership. Builders/FFI have no new record marshalling in this slice; a packaged C header is not builder support. Required headless tests before claiming coverage: - Zero extension vs legacy: Base result/state/selection and Styled bool, semantic IDs/names/expanded/controls, focus, actual draw commands and software pixels; both themes, closed/open, 1–3 months, each view. Unknown behavior enum fields independently fall back while valid sibling fields work. - Actual pointer, Enter, Space release and AT trigger opening, header/month/year navigation, neighboring date activation, canonical roving focus and selection close/focus restoration. Original-grid queued duplicate/neighbor targets remain stable across recentering. Compare final-phase queue behavior with legacy, including complete-then-start and net-zero endpoint queues. - Restart/swap and completed-endpoint validation independently and in combinations; live newly disabled anchor, allowed disabled interior, phase-shape disagreement, same-date close, incomplete remains open and rejected completion remains open. Recenter and year-to-days preserve selection and are silent for existing CHANGE regressions. - Locale/custom-label trigger and popup semantics/paint; host today disabled/selected precedence; month toggle only one month; year extremes 1/9999, leap cursor clamp and disabled-month/year focus fallback; popup width/clipping using actual viewport bounds. - Escape hierarchy across frames and documented same-frame prepass; outside dismissal, repeated trigger toggles, disabled-vs-Calendar-disabled, layout/inert/omitted component, null inputs, invalid viewport after mutation and no modal scope left behind. Regression observer callbacks retain exact legacy final-state/focus timing and metadata. - Strict C11 Release via private Xvfb wrapper; compiled C usage, C++11 declarations, standalone generated-header entry and pinned WASI suite. Browser extension coverage remains unclaimed until an actual headless WASM fixture passes. This is a cohesive forwarding/composition slice, not a DatePicker parity completion. No production changes are authorized by this document itself. --- ## DatePicker completion audit Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/DATE_PICKER_COMPLETION_AUDIT.md # DatePicker completion audit Design checkpoint only, 2026-10-20. CUI baseline is `3ddd91bad33a16c3732f0fd05482f2cbf7126783`; frozen upstream kit 0.7.1 is `87d10ae5e1299d1be18670a37570c5402f952e34`, verified in the local reference checkout. No runtime, public header, canonical registration or parity status changes are authorized by this document. Preserve all 78 catalog entries. ## Source authority Frozen source links below point to the exact revision, not moving documentation: - [Styled DatePicker](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/crates/component/src/time/date_picker.rs): `DateTime` (52), `DateRangePresetValue` (113), state/builders (153–395), date selection/clear/preset transitions (403–538), Styled builders/render (542–866). - [Base DatePicker](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/crates/base/src/date_picker.rs): controlled root (17–55), child/style composition (58–76), ComboBox semantics, Confirm toggle and Cancel dismissal (80 onward). - [Upstream tests](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/crates/kit/tests/date_picker.rs) are secondary evidence; implementation controls the distinctions below. This audit does not claim that upstream Rust tests were executed. CUI authority is [picker declarations](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_picker.h), [Calendar forwarding contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_date_picker_calendar.h), [Base reducer](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_picker.c) and [Styled composition](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_picker.c), all at the stated baseline. ## Feature matrix “Implemented” means the stated CUI capability exists, not that all upstream behavior, bindings or live assistive-technology behavior is equivalent. | Frozen requirement | Current evidence | Status / remaining boundary | | --- | --- | --- | | Single/range values, popup trigger, outside dismissal, disabled control | `cui_date_selection`, `cui_date_picker_state/options`; Base lines891–989; Styled321–404 | Implemented date-only foundation. Single acceptance/completed range closes; partial range remains open. Does not include time-mode close behavior. | | Locale, first weekday, multiple months, min/max and disabled-date matcher | `cui_calendar_options`, `cui_date_locale`, locale formatting; forwarded by both DatePicker paths | Implemented, with CUI's documented numeric locale formatting and bounded displayed-month policy. Not an OS locale/time-zone provider. Do not relabel these missing. | | Year/month navigation, year bounds, today/neighbor cells and range policies | `cui_date_picker_calendar_options` carries `cui_calendar_presentation_options` and `cui_calendar_behavior_options`; Base978, Styled395 | Implemented opt-ins. `_ex` forwards once and preserves legacy defaults. Today is supplied by the host, not read from a clock. Year destinations/range restart/endpoint validation/recenter policies are explicit. | | Preset labels and single/range/date-time choices | Upstream113–150,508–526,638–641,806–822; CUI picker records have no preset list/action | Missing reusable DatePicker feature. An app can compose buttons and assign values, but that supplies neither standardized validation nor close/focus/event semantics. | | Single-date time precision, hour cycle and default time | Upstream261–291,359–393,403–416,667–697,848–854; CUI `cui_time`, `cui_time_state/options`, `cui_time_field` exist separately | Partial building blocks; integrated date-time value, popup time field, precision truncation and time-aware Change are missing. A separate TimeField is not DatePicker completion. | | Clear affordance and Delete action | Upstream cleanable defaults false (604), builder630, clean484–499, on_delete459; CUI options only calendar/viewport/placeholder/disabled/width | Missing integrated clear button/key behavior. Empty date values are representable and host-clearable. No current clear action resets range phase/time or emits a DatePicker change on its own. | | Custom trigger | Upstream Base owns arbitrary children/style and controlled open; Styled DatePicker exposes no custom-trigger builder | Partial/composable: CUI `cui_base_date_picker_trigger` submits semantics and toggles caller state; caller owns layout/paint. Full Base reducer and split Calendar submission permit custom composition. Styled trigger is fixed. Do not invent an upstream Styled custom-trigger API requirement. | | Appearance/size/style/focus-ring controls | Upstream `Styled`, `Sizable`, `FocusableExt`, `appearance` (569–589,650–654); CUI Styled335–351 fixed outline button/calendar icon | Partial: theme, width, calendar cell size and Base custom painting exist. No equivalent DatePicker appearance flag, per-control size/focus-ring override or arbitrary styled refinement. | | Placeholder and displayed format | Upstream `placeholder`, `date_format` and `display_format`; CUI placeholder + locale date order/separator | Placeholder implemented. Arbitrary date/time patterns and formatted date-time/range title missing. Locale formatting is explicitly not an arbitrary pattern parser. | | Change and open lifecycle | Upstream Change carries `DateTime`; Base `on_open_change`; CUI `cui_picker_events.h`, Base/Styled picker event implementations | Date-only aggregate CHANGE exists. `_ex` Calendar forwarding has no corresponding extended typed wrapper; open/close notifications and date-time payloads missing. No common observer or dispatch redesign is implied. | | Accessible trigger/popover relationship | Upstream Base ComboBox, expanded/value; CUI Base921–925,966–970 uses Button + expanded/controls, localized label | Partial semantic correspondence, not absence of semantics. No current claim of matching ComboBox/value model or live AT announcements. Adapter/DOM/live AT evidence must be evaluated separately. | ## Frozen behavioral constraints that affect design The source only edits times when `time_precision` is configured **and the current value is single**, via `edited_time_precision`. A range can store start/end times through `set_date_time` or a date-time preset, but the popup does not edit both range endpoint times. Two single pickers are the upstream recommended composition. No timezone-aware or daylight-saving conversion requirement follows from its `NaiveDateTime` model. CUI should retain calendar dates and wall-clock times, with host-owned timezone conversion, rather than inventing a UTC/OS clock dependency. In single time mode a changed day emits immediately and leaves the popup open; activating the same selected day confirms/closes without another value edit. Time-field changes emit through `emit_change`, which only emits a complete value. Date-only `update_date` closes and emits. Clear restores default times, empties both endpoints according to current shape, and closes through `update_date`. Delete is wired on the root independently of whether the cleanable button is visible: `cleanable` controls the visible affordance, not that action registration. A future CUI clear-key policy must explicitly choose/document whether to reproduce this distinction, including empty/no-op Change behavior and disabled gating. Preset buttons are rendered with `tab_stop(false)` upstream. Their transitive state updates matter: `select_preset` calls `update_date` (or `set_date_time`, which calls it), which first changes the picker's independent date and then calls child Calendar `set_date`. In frozen `crates/base/src/calendar.rs:217–235`, `apply_date` rejects a matched candidate without changing the child date or view; otherwise it changes the child date and recenters current month/year to a present start. It does not reset Day/Month/Year view, year page or other cursor state. `Matcher::is_match` (118–124) checks a present single or both complete range endpoints, not the interior. Thus a disabled preset can change the outer picker value/title and emit Change while retaining the previous child selection and month/year. This is independent retained child ownership, not atomic rejection of the picker action. `select_preset` then unconditionally focuses the trigger. Clear also calls `update_date`, after restoring default times. Empty single/range values do not match `Matcher::is_match`; the child date therefore empties as well. No start exists to recenter, so current month/year and Calendar view remain. `clean` does not explicitly focus the trigger, unlike `select_preset`; it calls neither `set_open` nor conditional `focus_back_if_need`. Its actual event focus can depend on clear-button/root handling and must not be described as an explicit focus restoration guarantee. A future CUI facade sharing one caller selection cannot reproduce rejected-child divergence without separate retained child value state. Alternatively it must document a deliberate atomic-eligibility policy rather than call it source-equivalent. Relative presets receive resolved dates from the host; no clock access is required. ## Recommended additive slices 1. **Date-only actions and composition first.** Introduce a separate extension header/entry points and value-only options, leaving `cui_date_picker_options`, state layout, old calls and zero-extension behavior unchanged. Define bounded, caller-owned preset records with explicit single/range shape, labels and stable action IDs; clear is its own target, not trigger activation. Specify capacity, duplicate IDs, invalid UTF-8/invalid dates, disabled policy, mismatch between preset and picker shape, close/focus behavior and whole-queue ordering before implementation. Borrow arrays/labels only through submission/render consumption; never retain handlers or invoke UI from predicates. A small bounded preset list and clear affordance are preferable to an unbounded list with implicit scrolling. Reuse the existing Calendar extension in the new facade rather than losing its policies. Ship an actual compiling Base custom-trigger example with the same reducer, overlay and focus contract; no arbitrary C callback renderer is needed. 2. **Styled presentation and typed wrapper.** Add explicit minimal/outline and supported size/focus presentation options without promising Rust-style arbitrary refinements. Use existing theme/Button primitives, preserve clear hit targets, keyboard focus and trigger controls/expanded linkage. Add an extended aggregate date CHANGE wrapper with exactly the old post-reduction notification restrictions. Decide open/close event scope separately; comparing caller-owned `overlay.open` is already possible but is not a lifecycle subscription API. 3. **Single date-time composition.** New explicit value/state/options records can combine `cui_date` and `cui_time`; do not append time fields to legacy date selection/event layouts. Reuse TimeField and define minute/second precision, default-time truncation, 12/24-hour presentation, external updates, draft preservation, repeat-day confirmation, clear and preset time reset/preservation. Keep range time editing out of this first slice. Define a dedicated date-time event payload and bounded formatter contract; a supplied formatted title or narrowly specified formatter avoids introducing a general chrono-pattern parser. Add range date-time storage only with a separately reviewed model contract. No new Core state machine, platform types, networking, allocation service or new dependency is required by the first slice. Public types remain portable C11. Base must continue to reduce once; Styled must paint/submit that result, not reduce a second time. Existing `_ex` behavior permits a late invalid viewport/overlay failure after a selection edit; new wrappers must not mistake the legacy boolean for a transaction rollback. Updating shared headers requires matching distribution sources/bindings and integrator-owned metadata/skill regeneration in production. ## Meaningful acceptance evidence Existing source tests inspected: `tests/unit/test_picker.c` covers locale models, year grids, picker Escape, custom locale presentation, picker presentation and trigger interactions; `test_picker_events.c` covers aggregate notification behavior; `test_date_picker_calendar.c` covers range policies, queue validation, localized headers, neighbors, paint/boundaries, zero/invalid options, lifecycle/errors and combinations. `tests/test_calendar_distribution.py` checks additive declaration/ implementation distribution. These support the existing Calendar capability claims, not presets/time/clear claims. Existing web locale/year and Calendar presentation fixtures do not establish missing DatePicker actions or live AT behavior. For slice1 require headless Base/Styled parity tests for pointer, keyboard and semantic activation; clear on empty/single/partial/completed range; no trigger retoggle after clear; mixed clear/preset/day queues; disabled/no-op/rejected cases; focus restoration versus outside focus; stale IDs; borrowed-label consumption; viewport failure after edit; and old/zero-extension state+semantic+software-pixel comparisons. Check preset endpoint policies explicitly. Slice2 adds actual headless browser hit-target/focus/popup checks and event ordering; do not substitute fake DOM snapshots for the actual WASM path. Slice3 adds actual TimeField draft, precision rollover/truncation, date preservation, same-day confirm and complete payload tests, including externally changed values while a draft is active. This checkpoint is a source audit, not a new execution claim: no full build, native window, browser, upstream test suite or AT session was run. Future native tests must use `scripts/test_local.py` private Xvfb; browsers remain headless. --- ## Single-date DatePicker time editing: design checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/DATE_PICKER_DATETIME.md # Single-date DatePicker time editing: design checkpoint Design only; no new declarations or behavior are implemented by this checkpoint. Worker base: `0849cf6eeed95bdbc084ca0c9360699deec087ca` (next59 gallery regressions). Frozen reference: `87d10ae5e1299d1be18670a37570c5402f952e34` at `/tmp/cui-upstream-reference`. Legacy date-only APIs and layouts remain unchanged. ## Source and current evidence Frozen `crates/component/src/time/date_picker.rs`: - 215–227: Calendar Selected calls `select_date`; TimeField Change updates retained start time and calls `emit_change`. - 261–291: minute/second precision truncates times; hour-cycle configuration marks the field for synchronization; changing default time resets current times too. - 327–343: `set_date_time` sets supplied times (empty uses default), pushes the child time, then updates date without Change; the update closes the popup. - 359–399: only single values edit time. Child configuration is pushed on explicit picker changes, not every render, to avoid overwriting undelivered field edits. Change is emitted only for complete values by `emit_change`. - 403–420: a different accepted day changes date and emits Change while staying open; the same accepted day closes without another Change. This comparison is with the OUTER picker date, not the possibly divergent retained child date. - 423–447: programmatic/preset update stores outer date before child Calendar acceptance, closes directly; a rejected child may retain its old selection. - 484–499: clear restores default time, clears date, closes and emits Change, without an explicit trigger-focus request. - 508–526: date-only presets preserve current time; date-time presets replace and truncate time. Both close, emit Change and unconditionally focus trigger. - 529–538,646–670,844–854: default display adds precision/hour-cycle formatting; popup time row uses a localized label and TimeField. Range values can store times upstream but do not edit both endpoint times in the popup. Transitive authority remains `crates/base/src/calendar.rs:118–124,217–235`: matcher rejection retains child state; accepted nonempty assignment recenters month/year without resetting view/cursors. Actual day selection must adopt the child even when its value is unchanged but differs from outer ownership. Current C contracts are `include/cui/cui_date_picker_actions.h`, `docs/DATE_PICKER_ACTIONS.md`, `include/cui/cui_date_picker_calendar.h`, and `include/cui/cui_picker.h:105–123`. Current action state already retains separate outer observation and child selection. Its Base implementation invokes `cui_picker_actions_reduce`; `src/base/cui_picker.c` then automatically closes on complete Calendar activation. Calling this facade and reopening afterward is not acceptable: shared close can already restore focus/withdraw semantics. Current TimeField retains `segment`, `digit_count` and `draft`; its reducer (`src/base/cui_picker.c:1041–1160`) updates valid numeric prefixes, advances after second digits, clamps/wraps via keys, and submits segment semantics. It does not own a date or distinguish an external assignment from repeated controlled values. The wrapper must own that distinction. No general text parser, timezone, locale service or clock is required. ## Architectural decision proposed for review Add a separate `cui_date_time_picker.h` with explicit state and single-date value. Do not append time fields to legacy selections/events or change date-only presets. Reuse the bounded action identity machinery and Calendar/TimeField primitives through private composition helpers, not a second public-facade reduction. A narrow private Calendar composition seam must return its activation/change result BEFORE choosing close/focus policy. Existing callers retain auto-close; new datetime composition compares accepted child date with outer date, then chooses keep-open or same-day confirmation. If this cannot be implemented without changing shared Core/Surface dispatch, stop for architecture review. Proposed exact public declarations (names/layout subject to review): ```c #include "cui_date_picker_actions.h" typedef enum { CUI_DATE_TIME_MINUTE = 0, CUI_DATE_TIME_SECOND } cui_date_time_precision; typedef struct { cui_date date; /* All-zero means absent; otherwise a valid Gregorian date. */ cui_time time; /* Valid even when date absent: explicit retained time of day. */ } cui_date_time_value; typedef struct { cui_id id; cui_str label; cui_date date; /* Presets require a present valid single date. */ bool has_time; cui_time time; /* Valid when has_time; ignored otherwise. */ } cui_date_time_preset; typedef struct { cui_date_picker_options picker; cui_date_picker_calendar_options calendar; cui_date_time_precision precision; bool twelve_hour; cui_time default_time; cui_str time_label; /* Empty uses "Time"; borrowed UTF-8. */ const cui_date_time_preset *presets; size_t preset_count; cui_id clear_id; cui_str clear_label; bool cleanable; cui_date_picker_delete_policy delete_policy; cui_date_picker_preset_policy preset_policy; } cui_date_time_picker_options; typedef struct { cui_date_picker_actions_state actions; /* Internal ownership/identities. */ cui_time_state time_field; cui_date_time_value observed; cui_time applied_default; cui_date_time_precision applied_precision; bool applied_twelve_hour, configured, assignment_pending; /* Copyable state, not user-editable bookkeeping. No pointers retained. */ } cui_date_time_picker_state; typedef struct { cui_calendar_result calendar; bool valid, value_changed, source_change; bool time_edited, action_activated, confirmed; } cui_date_time_picker_result; void cui_date_time_picker_init(cui_date_time_picker_state *, cui_id popup, cui_date initial_month); /* Between frames: checked assignment marks even an identical value for sync. */ bool cui_date_time_picker_assign(cui_date_time_picker_state *, cui_date_time_value *controlled, cui_date_time_value next); cui_id cui_date_time_picker_time_id(cui_id trigger); cui_date_time_picker_result cui_base_date_time_picker( cui_context *, cui_id trigger, cui_id calendar, cui_id time, cui_str name, cui_date_time_picker_state *, cui_date_time_value *, cui_date_time_picker_options); cui_date_time_picker_result cui_date_time_picker( cui_context *, cui_id trigger, const cui_theme *, cui_str name, cui_date_time_picker_state *, cui_date_time_value *, cui_date_time_picker_options); /* After Base reduction, inside caller's one open popup scope. Semantics only. */ void cui_date_time_picker_submit_presets( cui_context *, cui_date_time_picker_state *, cui_date_time_picker_options); ``` The explicit time while date is absent is a C representation difference: upstream `DateTime::Single(None)` hides retained start time. It permits deterministic controlled ownership without a hidden second writable time value. Consumers must test date presence before treating this pair as a committed date-time. `value_changed` compares both fields; an empty-date time edit can therefore change storage without `source_change`. This is not a new source Change emission. MINUTE truncates seconds to zero; SECOND retains seconds. No timezone, UTC offset, DST interpretation, epoch conversion, leap seconds or implicit current time. `cui_time` stays a 00–23 hour civil time even in twelve-hour presentation. ## Synchronization, reduction and result contract All options/value/IDs preflight before edits, predicates or event consumption. Reject malformed/partial dates, invalid active time, unknown enums, non-single `picker.calendar.range`, invalid bounds/viewport, duplicate/reserved IDs, capacity or active UTF-8 errors. Reuse action limits (8 presets,96-byte labels), exact ID collision checks and whole-list validation. SOURCE permits outer preset assignment when child matcher rejects; ENABLED rejects in advance using the existing explicit policy including bounds. Shape policy is vacuous because this facade is single. First valid reduction configures children, using supplied controlled value as the initial outer value; default time does not overwrite a present supplied value. An absent initial value starts with the truncated configured default. Record the normalized observed value after all accepted changes, preventing self-feedback. On later frames, a changed external value or explicit `assign` is source setter intent: reset time draft, truncate supplied time (empty assignment uses default), sync Calendar with retained-child rejection semantics, close directly without an explicit focus request, and emit no `source_change`. An equal ordinary value is NOT a setter: preserve draft, view and divergent child. Explicit assign validates all next value fields atomically, writes controlled storage and marks pending; NULL/invalid inputs do nothing. It only queues child/UI synchronization for the next valid frame. It does not consume events or require a context between frames. Configuration changes apply once, before input: default-time change resets current time (matching its source builder); precision change truncates time/default; hour-cycle change resets draft but retains civil time. On simultaneous changes: configure first, external setter second (external value wins), queued UI input last. No source Change is invented for configuration alone. Changing matcher or reopening does not implicitly resynchronize a previously rejected child. Reducer phase order is explicit, preserving CUI's phase-based action behavior: external/config sync; Escape/overlay/trigger pass; one Calendar reduction; one TimeField reduction if still open; one ordered clear/preset/Delete pass. It is not a promise of global chronological interleaving across Calendar and TimeField. Calendar selection compares against outer date BEFORE adoption: - Different accepted day: adopt child date, preserve current time, remain open, `source_change=true`; no trigger focus request. - Same accepted day: close through ordinary conditional focus restoration, `confirmed=true`, no date Change. A no-op child activation with a divergent outer date follows the different-day rule. Disabled/rejected days cannot confirm. - Time edit with a present date: preserve date, stay open, source Change on actual TimeField change. Empty-date edit updates retained time but emits no source Change. - Clear/Delete: restore truncated default, empty date/child, reset draft/range phase, preserve Calendar view/month, direct close without explicit focus, source Change even if already empty. Presets: date-only preserves time, timed replaces/truncates; sync child, close, source Change even if identical, unconditional trigger focus. Outer disabled gates all user actions; Calendar-only disabled gates Calendar input, not clear/presets or time editing. No additional readonly policy in this slice. Ordinary close/Escape retains draft; reopening alone does not push time again. While time UI is omitted, no TimeField reducer runs and stale targets cannot edit. Published identity records expire on omission, failed helper, or close/reopen as in existing actions. Scope Delete includes actually submitted eligible time segments as well as Calendar/preset targets. Popup root and unsubmitted namespace IDs do not suffice. Core may resolve invalid programmatic focus to a real modal target; that resolved event target remains authoritative. Approved Base correction: Base reduces input once but submits no TimeField bindings before the caller opens its popup scope. The private TimeField seam splits reduce and submit, while the legacy public TimeField still does both. After Base reduction, inside the one actual popup scope: submit Calendar, call `cui_date_time_picker_submit_time(ui, time_id, state, value, options)`, THEN call `cui_date_time_picker_submit_presets`. The latter snapshots actual eligible Calendar/preset/time targets. Both helpers are semantics-only; neither reduces, starts a scope, invokes predicates through input reduction, or replays callbacks. Call the preset helper even for zero presets to publish the bounded admission set. Failure or omission of either helper prevents stale time admission next frame. Caller paints those segment IDs, Calendar and helper rows. A later Styled facade must use paint-only seams; calling the public TimeField again would reduce twice and is prohibited. Slice1 has no unimplemented Styled declaration. Define/verify derived root and segment IDs against clear/presets and Calendar before reduction. The previous frame must provide genuine bindings; retaining numeric IDs cannot synthesize activation. `source_change` is a coalesced per-submission fact that one or more source Change conditions occurred, not an ordered callback stream. `value_changed` is final vs entry storage; `confirmed` is same-day acceptance. No typed observer is included; future events must separately specify order, repeated equal notifications and empty-vs-complete payload. Late Core/layout failures are not transaction rollback; `valid` describes preflight only. Invalid options never partially normalize value. ## Lifetimes, formatting and limits State and controlled storage belong to one owner UI thread and context. Reinit before moving context; init(NULL) is a no-op. State contains copied values only; no callbacks/OS resources/timers are retained. Pointers must be readable for calls; labels/locale/predicate resources remain valid through frame/draw consumption. Predicates remain pure and must not reenter UI. No allocation/new dependency. Default display combines existing date locale formatting and bounded time format: minute/second and explicit 12/24-hour appearance. Offer a checked bounded format helper during implementation if necessary; do not implement chrono patterns or parsing of arbitrary human strings. Time-label translation is explicit. General style, responsive scrolling, full lifecycle observers, range-time storage/editing, OS localization and live AT remain excluded. Existing modal outside-clear rule continues: dismiss before activating clear outside an open popup. ## Independently reviewable production slices and acceptance 1. Portable value/config/sync + Base composition. Review exact public layout and private suppress-auto-close/paint-only seams first. Preserve old state/layout and zero-option source behavior. Native/WASI tests: first/external/equal/forced assign; drafts across idle/reopen vs reset; 12/24 hour and precision; leap-day/ midnight fields; different-day keep-open and same-day close; divergent retained child no-op adoption; bounds/matcher changes; invalid preflight; disabled and consumed/stale events; mixed Calendar/time/action phase order; empty-time storage vs source-change distinction; repeated clear/preset; identity expiry. 2. Styled popup and presets/clear integration, bounded formatter and distribution. Actual semantic targets and software paint assertions across sizes/themes, full popup fit/failure, segment focus/Tab, clear focus vs preset focus, and legacy pixel/memberwise semantic equivalence. C++ include, strict C11 and ASan/UBSan through `scripts/test_local.py`; same deterministic WASI vectors. 3. Explicit opt-in WASM gallery mode preserving date-only defaults and copyable compiling snippet. Real headless desktop keys/pointer and CDP touch: day then time editing, same-day confirm, draft preservation, clear/preset and disabled paths, narrow bounds and Escape. No desktop launch or calendar-clock oracle. Bindings/builders and typed picker observers do not automatically gain this API. Integrator must explicitly register public headers/sources, distribution, metadata, consumer guidance and any later binding builders. Do not promote full DatePicker parity: existing date-time range/source formatting/style/event boundaries remain. No tests were executed for this documentation-only checkpoint. Source inspection is evidence for the proposed contract, not proof that it is implemented. Production slice1 clarification: `time_id` and `time_submitted_frame` are copied bookkeeping in the new state. A successful time submission precedes publication of the aggregate target set. Final value changes and coalesced source Change are separate; regression vectors include time edit followed by timed preset restoring the entry value. No production Core/Styled/canonical registration change belongs to the Base-only slice. ## Review checkpoint: ordered accepted-day decisions (implementation paused) The phase-final Calendar result is insufficient for date-time confirmation. With outer date A, accepted B followed by accepted A must adopt B, then A, emit two source Change conditions, and remain open. Comparing the final Calendar value with the entry value would instead close incorrectly. Production slice1 is not ready to ship until this is corrected; its existing single-acceptance tests do not establish this multi-event behavior. Authority is frozen `87d10ae5e1299d1be18670a37570c5402f952e34`: `crates/base/src/calendar.rs:260-269` commits the Calendar selection before emitting Selected; `crates/component/src/time/date_picker.rs:403-420` compares that selected value against the picker's *current* date, closes and returns on equality, or stores the new date and calls emit_change on difference. `emit_change:395-401` emits only for a complete date. This establishes the order of individual source handlers; it does not establish equivalence between upstream's queued event scheduler and CUI's frame input queue. ### Smallest proposed private seam (not yet approved or implemented) Add these private types to `src/base/cui_picker_composition_internal.h`; no public Calendar state, result, event schema or Core dispatch changes: ```c typedef enum { CUI_PICKER_ACCEPT_CONTINUE, CUI_PICKER_ACCEPT_STOP } cui_picker_accept_flow; typedef cui_picker_accept_flow (*cui_picker_accept_visitor)( void *context, size_t event_index, cui_date_selection accepted); ``` Extend only the private Calendar reducer implementation with visitor/context arguments. All existing public Calendar and legacy picker entry points pass NULL/NULL. The private datetime reducer supplies one stack-owned accumulator. No visitor, context pointer or event index survives the synchronous reduction. This is a private internal function pointer, never an application callback. Invoke the visitor exactly once at the single successful activation site in `src/base/cui_picker.c` (currently immediately after `result.activated = true`), after candidate validation/selection commit and existing recenter/focus updates. Pass a copied selection and the current Core event index. Navigation alone and rejected candidates do not invoke it. Existing range reducers use NULL; datetime preflight prohibits range. This preserves existing CUI matcher/bounds admission; it does not newly claim exact source notification behavior for rejected dates. The datetime visitor compares each accepted single date with its accumulator's current outer date, initialized after external assignment/configuration sync: 1. Different: adopt that date immediately in the accumulator, retain current time, set coalesced source_change, and return CONTINUE. 2. Equal: set confirmed and return STOP without setting source_change for this acceptance. Retain any earlier source_change already observed. STOP breaks only this Calendar reduction's remaining event loop. Existing final cursor normalization, net Calendar changed calculation and invalidation still run. After the reducer returns, datetime copies the accumulator's final date to its controlled value and performs overlay close/focus handling once. The visitor must not call CUI, invoke predicates, dispatch input, mutate Calendar state, allocate, or call any user callback. Time reduction is skipped after confirmation, as it already is for a closed popup. This avoids reentrant overlay mutation inside Calendar reduction. Stopping at the first confirmation is an explicit CUI popup-generation routing policy: later queued Calendar events cannot mutate a popup that has confirmed. It is not a claim about upstream scheduling after an emitted close. Thus A→B→A remains open; A→B→B confirms B and ignores subsequent Calendar events; A→A→B confirms A and ignores B. Public source_change remains a coalesced fact and value_changed remains final-versus-entry; neither is used to decide confirmation. Source callbacks/event-stream parity remains excluded. ### Capacity, failure and compatibility The seam uses constant stack storage and no trace array, so there is no trace capacity, allocation failure or truncation policy. At most one visit occurs per input event that the existing bounded Core frame admitted, and processing stops on confirmation. The seam adds no independent queue or event retention. An invalid enum returned by this internal visitor is treated as STOP defensively; no partially published trace or callback state exists. Preflight failures still happen before the reducer and do not invoke the visitor. Core frame/layout failure remains the existing nontransactional failure boundary, not rollback. NULL visitor preserves the exact existing loop and legacy result semantics, including processing later events and computing changed from final versus entry. No public state layout changes; the new date-time state needs no additional retained fields. There must be no second Calendar reduction or event replay. This seam addresses accepted Calendar ordering only. TimeField currently reports net phase change; its Up→Down cancellation/event-notification fidelity must be reported separately rather than inferred from this Calendar correction. ### Required focused proof before production handoff Use actual prior-frame semantic day targets and queued events, not direct visitor calls alone. Cover A→B→A (open, source_change true, value_changed false), A→B→C (open, final C), A→B→B (closed B, changed and confirmed), A→A→B (closed A, no source_change), and divergent outer/retained child followed by multiple accepted days. Include rejected/disabled candidates between accepted ones, navigation preceding acceptance, matcher rejection with no visitor, and subsequent TimeField input suppressed after confirmation. Record legacy Calendar/date-only picker results for equivalent queues with NULL visitor. Run native wrapper, strict C11/C++ header checks, sanitizer and deterministic WASI vectors. No claim of corrected behavior until those tests pass. ### Base slice1 implementation result The ordered visitor checkpoint above was approved and is implemented by the Base-only slice. The public header declares only implemented Base/value/sync and semantics-only helper functions. The helper split and private visitor add no Core/public Calendar state or dispatch changes. Native wrapper and ASan/UBSan wrapper each pass the three focused suites (datetime, legacy picker, date-only actions); datetime has 579 assertions, with the same 579 passing under pinned WASI. The standalone fixture also compiles the C++11 public-header probe. Strict warning builds and pinned clang-format checks pass. No Styled facade, canonical build registration, bindings, gallery or full DatePicker parity is claimed. See `docs/DATE_TIME_PICKER.md` for phase-order and net TimeField source notification limits and the exact consumer composition order. --- ## Dialog lifetime cancellation: builtin reducer checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/DIALOG_BUILTIN_CANCEL_MARKER.md # Dialog lifetime cancellation: builtin reducer checkpoint Status: **unpublished prototype; no production marker/query or Base change**. The copied candidate passes 38 headless checks, including frozen reducer traces, numeric stale-key/idle fixes and bare-scope Escape routing. Remaining reducer coverage and explicit scope-ID alias limitations still gate production transfer. See [the consumer audit](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SCOPE_INPUT_CANCEL_CONSUMERS.md). ## Actual counterexample Session 36366 compiled the input fixture with strict C11/O3/warnings-as-errors, then ran three private-Xvfb cases. Nested Body and independent gesture owner passed. The actual public Base overlay scrollbar failed: after parent close/open, its retained mouse drag applied the old MOVE+UP and changed child scroll from 0 to 285.714. The strict expected value remains zero. Log: `/home/matteo/.cache/cui-hover-raw-build/dialog-gesture-actual-basebar-runtime.log`. `src/base/cui_scroll.c:cui_base_scrollbar` keeps dragging/grab in caller-owned `cui_scroll_state`. It uses `cui_event_target` without checking consumption. Core capture cancellation and selective event consumption therefore cannot reset that separate reducer state. The earlier custom-drag proof does not cover this builtin. Changing targets would corrupt diagnostic identity; globally honoring consumption would change existing Base behavior. Neither is proposed. ## Recommended narrow opt-in seam Add a private `bool input_cancelled` to each current focus-scope record, initialized false on `cui_begin_focus_scope`. The explicit cancellation helper, after its existing full validation and before any mutation, resolves the current target scope. Its atomic commit marks that scope. No previous-scope marker is read. A descendant submitted later inherits cancellation by walking current parent links; already submitted descendants see the same ancestor marker. Closing the scope does not undo the frame-local marker. Next frame reconstructs all markers false. This stores lifetime-reset intent, not a new input-dispatch decision. Proposed portable read-only API: ```c bool cui_scope_input_cancelled(const cui_context *ui); ``` The query returns true only inside an ordinary active current scope whose own or ancestor marker is set. Outside submission, inert/layout-only/measurement/prepaint, errored frames and missing scopes return false without mutation. It performs a bounded current-parent walk; no ID folding, geometry, resource lookup or allocation. It does not report cancellation of arbitrary other scopes and does not authorize raw input acceptance. Calling cancellation late cannot roll back earlier callback or reducer effects, consistent with the existing accepted-receipt contract. The Base scrollbar reads this once during submission. When true, it clears its local dragging flag before processing any samples, including idle frames. It skips pointer/key samples marked consumed by explicit cancellation; non-touch CANCEL retains the existing unconditional drag cleanup. Unconsumed input retains the old math/page/key behavior. The marker does not itself consume unrelated wheel/text/accessibility input, nor reset values/grab or alter semantics/focus. When the explicit helper was never called, the new branch is false and the old reducer statements/order/consumed-event behavior remain unchanged. This is deliberately an opt-in reducer policy. Custom raw reducers must observe `cui_event_consumed` and clear their persistent press state when this query is true; Core cannot mutate arbitrary caller storage. Public interact/pressed and activation receipts continue using the already proved cancellation operation. No claim that arbitrary custom callbacks can be retroactively undone is made. ## Memory and alternatives Current `cui_core_focus_scope` is `{cui_id id; size_t parent; bool modal, active;}`. There are two arrays of 256 records. Original/candidate compiler probes show that the added bool fits padding on the measured native and WASM32 configurations: record sizes remain 24 and 16 bytes, and context sizes remain 255520 and 229568 bytes respectively. The [metadata receipt](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/validation/dialog-marker-metadata.json) records exact offsets and source hashes. This establishes zero storage-size delta on those two configurations, not on every ABI. The operation adds no allocation. Initialization adds one scalar store per submitted scope; there is no zero-runtime-cost claim. Previous array copies carry an unused marker byte; the query never reads it. A per-event bitset costs at least 64 bytes for 512 samples and cannot represent idle-frame local dragging cancellation without another scope marker. Reusing an activation-slot sentinel risks reserved-state ambiguity and still lacks idle scope intent. A lazy resource sidecar avoids unconditional record changes but introduces allocation/capacity failure into a previously allocation-free helper and a lookup on each reducer query. A public explicit reset hook on each custom/bar state would require the parent to discover independently owned nested state, the failure that this scoped operation is intended to handle. These alternatives are not preferred. ## Proof and transfer gate First measure record/context sizes and query behavior in the isolated test adapter; no production header/Core/Base change before review. Then retain the actual old Base-bar failure and make its captured MOVE+UP, idle-held and touch counterparts pass, followed by genuine fresh DOWN success. Verify parent reset reaches nested modal/portal descendants but leaves siblings/background/trigger unchanged. Test late-created descendants, next-frame marker reset, repeated cancellation, invalid phase/graph/count preflight and no allocation. Test custom reducer cleanup using the explicit query contract. Preserve delivered receipts and targets byte-for-byte. Finally compare the uncalled-helper Base route against a frozen original reducer trace across pointer/page/key/CANCEL/ordinary-consumed samples and disabled/hidden bars, with fieldwise state comparison. Rerun the existing lifecycle, action, gesture, drag, failure/recovery and legacy surface proofs. Only then propose public Core/query and Base transfer plus metadata/generation. Full Dialog composition, Root/native-host and all five foreign facades remain open. ## Independently checked metadata The integrator extracted original/candidate compiler constants and checked their values directly; [the receipt](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/validation/dialog-marker-metadata.json) records assembly hashes and sizes. Native scope/context stay 24/255520 bytes (marker at 18); WASM32 stay 16/229568 bytes (marker at 14). Scope-array offsets also match. These two measured layouts do not establish portability to every ABI or runtime correctness. Query/reducer compatibility and consumer coverage remain open. --- ## Dialog component after Core region V2 Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/DIALOG_COMPONENT_AFTER_CORE_V2.md # Dialog component after Core region V2 Design checkpoint against signed `d4a1d847`; no component implementation is approved by this document. It supersedes obsolete single-flex-region, exclusive Header and whole-Outer defaults in earlier proposals. Core layout-record V2 is independent of draw ABI2; ordinary draw-list frames remain supported. ## Authority and concrete remaining scope Pinned upstream Kit0.7.1 revision `87d10ae5e1299d1be18670a37570c5402f952e34`: `crates/component/src/dialog/dialog.rs:560-745`, `base-dialog.rs:568-635`, `content.rs`, `header.rs`, `title.rs`, `description.rs`, `footer.rs`. Existing verified raw cache and executed28-row Taffy receipt remain authoritative; no new dependency or engine execution was needed for this checkpoint. C authority: `include/cui/cui_surface.h`, `include/cui/cui_scroll.h`, `include/cui/cui.h`; `src/base/cui_surface.c:361-458`, `src/base/cui_scroll.c`, `src/components/cui_surface.c`. Ledger status is not evidence of API absence. | Concern | Available foundation | Component work still required | | --- | --- | --- | | Independent Header/Title/Description | Ordinary wrappers/semantics | Six typed slots; source Description is an explicit composable Header child, not a source automatic sibling | | Content plus Body | Public144-byte V2,24-byte policies | Actual callback tree/default policies and conditional spacers | | AUTO, min/max, Footer overflow |28 production source/dist oracles | Current-font composition, owner bounds and descendant dismissal policy | | Body bar | Public48-byte real-node track projection | Shared Base behavior, skin/fade, queued wheel/touch/drag/page/key/CANCEL | | Close/cancel/confirm | Existing synchronous decide/close | Explicit owner actions, recursive-call guard, exact event ordering | | Open/teardown | Existing overlay focus/state | New-route reset helper, retained geometry lifetime, omission/reopen tests | ## Proposed API correction, before declarations are frozen Keep the exported names and callback-only top-level ownership proposed in `DIALOG_SLOTS_V1.md`: layout_init/open, Base/Styled compose, manual slot wrappers, and Base/Styled owner-action helpers. No existing public struct grows; no old surface/alert helper delegates to compose. The earlier candidate byte constants are NOT approved ABI. The next implementation must measure actual LP64/ILP32 layouts and assert offsets before publishing constants. Use new `cui_dialog_sizing_v1` containing size/version/reserved plus width and Panel AUTO/EXPLICIT requested/min/max, followed by the two exact public `cui_scroll_region_sizing_v1` records. Panel authority exists only here; `surface_options.width/height` are inactive for the new route. Content default FLEX1+INTRINSIC minimum; Body default FLEX1+ZERO minimum. Explicit presence maps to OMIT versus present-empty; absence never depends on counting callback output. Content or Body absent requires its policy OMIT; defaults resolve that before validation. Present+NULL callback remains an authored empty region. Use the corrected caller-owned layout with surface pointer, context binding, reentry flag, sequence marker, outer-zero destination and ten retained rectangles (Panel, Header, Title, Description, Content, BodyViewport, BodyContent, Footer, Outer, Column). It and surface must outlive end_frame; never retain stack callback tokens or borrow a temporary offset/bounds array. Slot/style descriptors are read only during compose and values copied into submitted nodes. No per-dialog hidden heap or registry; context-owned overlay drag/fade resources remain bounded and must be measured separately from the caller layout and Core15416-byte plan. Header, Title and optional explicit Description callbacks run independently in order, then Content, Body, Footer, each exactly once. Custom Header does not suppress Title. Application may put a Description manual wrapper inside Header and omit the independent Description callback. Name/description semantic strings remain explicit; visual children do not implicitly replace them. Manual wrappers cannot cross callbacks. Compose owns all structural begin/end balance; no manual top-level begin/end route. Distinct nested dialogs are allowed, same-layout recursion/duplicate active submission rejected. Inert/measurement sequence0 is not a unique frame marker and must not suppress every subsequent submission. ## Geometry and paint route Submit Panel -> Outer -> Column -> BodyFrame -> BodyViewport -> BodyContent; optional Content precedes BodyFrame in Column, optional Footer follows Outer in Panel. Header/Title/explicit Description are intrinsic Column siblings. Column gap0 with conditional explicit fixed spacers; no phantom spacing around OMIT. Source defaults:16px horizontal/vertical padding, inner gap8px at explicit rem16, Panel-to-Footer gap max(top padding,8). Refinement uses explicit logical values, not an undocumented rem inferred from theme font size. Padding belongs in slot children, not the zero-padding structural viewport/frame. Register public V2 after balanced callback submission. Preserve automatic Content minimum overflow inside clipped Inner and Footer outside Inner, even Footer400 beyond bounded Panel260. Outer is NOT a scroll owner in source policy; range/model0. Body alone scrolls. Old whole-Outer reachability policy remains old route behavior, not an implicit fallback. Mandatory internal Body chain remains for OMIT, but submits no Body semantics, callback, input helper or bar. Use real fixed track/thumb nodes plus Core track registration. Core projects current bounds/clip/culling/shadow ownership; no prepaint geometry bridge, previous-bounds current paint, private Core access or renderer negotiation. INTERACTIVE authoritatively enables a placeholder bar; disabled policy clears it, while owner/ancestor disabled and bar readonly still gate. Visible disabled paint is retained. Hidden/zero-range bar semantics are omitted, wheel remains enabled. Fade opacity applies once; no opacity multiplication in a private paint hook. ## Input, close and lifecycle sequence Extract a narrow PRIVATE surface reducer entry taking a new-route policy bit; public old update calls it with legacy behavior. Gate ONLY legacy Body6 wheel statements and reserved1/2/3 activation handling for compose. Preserve pending request_close, resize, Escape/outside checks and ordering, synchronous decision, accepted close, focus restoration, on_close exactly. No exported new dispatcher. This requires explicit ownership of the small `src/base/cui_surface.c` helper hunk in addition to new Dialog files; do not duplicate the full reducer. For source route reduce Body with public Base scroll begin/finish discipline: children first, then changed-only wheel consumption; once consumed never replay or pass residual delta. Use previous successful semantic/bounds input routing, Core current layout/clamp for publication. Overlay Base helper owns drag state; use previous viewport/content dimensions for input only, synchronize its model back before finish/Core registration. Do not call old overlay paint. No Outer input/bar helper in source route. A separately approved whole-Outer policy would need separate two-owner tests; it is not part of this default. Owner actions validate token/context/open/eligibility then reduce the actual button interaction once. Accepted activation calls existing synchronous decide with ACCEPTED/CANCELLED/CLOSED, then surface_close immediately; veto keeps open. No queued veto, synthetic Enter or second consumption. If a callback closes the owner, later slots/actions are skipped and internal boxes still balance. Earlier callbacks are not rolled back. Recursive compose/double-close must not notify twice. Legacy request_close keeps next-update timing. Source global Enter, Root deferred-confirm and host removal remain explicitly separate work. New open helper is required for EVERY closed-to-open transition, including between-frame close/reopen; validate context/layout before changing state. Reset Body scroll/max and retained geometry plus outer-zero destination, then delegate surface_open. Already-open succeeds without reset. Close/request_close stay existing APIs. Rebinding layout to another context requires explicit reinit while unmounted; no dereference of a dead former context. Omission does not implicitly notify close; resource collection follows existing Core rules. ## Decisions and test gate before component production 1. Approve source placement mode now or preserve centered CUI placement as an explicit mode. Recommended additive placement enum SOURCE_TOP/CENTERED; source preferred y=viewport/10 plus explicit layer offset, snap up to margin when oversized. Do not claim full placement parity from a centered Mount. Current Core can center an intrinsic child, but source min(preferredY, availableHeight-currentPanelHeight) needs a current-height alignment strategy; prove that tree before approving SOURCE_TOP, never use previous height. 2. Approve the narrow private reducer ownership above. No legacy statement may be retimed merely to accommodate new action helpers. 3. Keep full slot/refinement scope, including styles on independent wrappers and named Panel/track/thumb ownership; no fixed-height/demo-only shortcut. Component gate: callbacks-once and actual-font narrow/wide/AUTO resize; all28 source allocations through real slots; Header+Title+Description/manual children; omitted versus empty; Footer overflow and actual eligible descendants; Body wheel/child consumption/touch/drag/page/key/CANCEL, hide/fade/reappearance and nonunit opacity; synchronous accept/veto/close/reopen including between frames; nested/modal/inert/measurement/failure/recovery; frozen old route geometry, input and observer timing. Source placement requires its own current-size proof. No component production claim follows from Core28 geometry tests alone. Root/native-host controlled state, mount/removal/deferred-confirm/Enter and all five facades remain required subsequent slices. Foreign synchronous veto needs explicit exception/panic/thread/reentrancy/lifetime contracts before bindings. --- ## Dialog/AlertDialog current-height checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/DIALOG_HEIGHT_CURRENT_AUDIT.md # Dialog/AlertDialog current-height checkpoint Status: source-only on integrated139695; no production edit or compiler run. The Table touch production branch is preserved separately. This checkpoint does not transfer the unpublished scope cancellation/marker or other raw reducers. ## Revalidated authority and actual causes Pinned upstream Kit0.7.1 is87d10ae5e1299d1be18670a37570c5402f952e34. All ten raw cache files under `~/.cache/cui-dialog-audit-87d10ae5` were rehashed against the original acc877f24 source anchors and match. No dependency/fetch was required. Actual inspected authority: `dialog.rs:554-752`, `alert_dialog.rs:295-335`, `header.rs`, `title.rs`, `description.rs`, `content.rs`, and existing28-row executed Taffy receipt/golden under `tests/reference/dialog_flex`. | Current integrated C behavior | Consequence | Source behavior | | --- | --- | --- | | `cui_surface_geometry`: nonpositive height ->260, capped to usable viewport | Short plain Dialog stays unnecessarily tall if caller expects intrinsic content | Panel AUTO with min96/max usable height | | `cui_alert_dialog`: nonpositive height becomes **prior** body_content.h+padding | First presentation is260; first-open/content/font/width changes can lag | Current layout determines Panel size | | Alert opens Body6/Content7 before title/description/actions and centers everything | Title and actions are inside one scrolling body; no independent Header/Footer | Alert supplies Header containing Title/Description, Footer outside Inner | | Dialog title row/description are fixed siblings above one GROW Body | No independent custom Header/Content allocation | Header and standalone Title are independent; Content and Body are separate flex regions | | Existing Alert test warms4 frames; wrapping test inspects after4 frames | Does not prove first-open or same-frame resize | Need strict first-presented-frame witnesses | C sources: `src/base/cui_surface.c:223-244`, `src/components/cui_surface.c` body begin, begin_internal, footer_begin/end and alert_dialog; `tests/unit/test_surface.c:846-909`. The legacy unspecified Dialog height is genuinely a fixed fallback, while Alert's current docs explicitly promise eventual measured fitting. Do not silently redefine all surface kinds. Source Panel has16px vertical padding, inner gap8 at explicit rem16, min96 and current usable max. Header/Title/Content/Body are conditional children of a clipped flex Inner; Footer is outside Inner. Content is FLEX1 with intrinsic min, Body FLEX1 with zero min; missing Body is not a present-empty flex participant. Header does not suppress standalone Title. Alert's automatic Header nests an icon/text row and Title/Description text column with gap4; it does not manufacture a separate standalone Title as well. Close is overlaid independently. ## Minimal compatible implementation direction Reuse the already reviewed six-slot composition contract in `DIALOG_COMPONENT_AFTER_CORE_V2.md` and current public Core144-byte layout V2; do not invent a new Core solver or use previous bounds for present sizing. Use the existing source-placement tree proved in DIALOG_SOURCE_PLACEMENT_PROOF. Current96-min normalization when usable max<96 remains explicit; do not clamp away that source minimum or fabricate a fixed readable spacer. Keep `cui_surface_begin` and its manual end/footer ownership, pure surface geometry, explicit positive heights and existing state/options ABI unchanged. Introduce the additive Base/Styled composition route already proposed as `cui_base_dialog_compose_v1` / `cui_dialog_compose_v1`, with caller-owned retained layout storage and a separate descriptor; do not resize existing public structs. The next test-only fixture should exercise its actual tree before declarations are finalized. All six slots remain in scope: Header, Title, Description, Content, Body, Footer/actions. Conditional presence and present-empty are explicit; callbacks run once in source order, measurement may repeat. Tree: current-size Mount -> optional bounded top spacer -> Panel -> Outer/Inner -> Column -> Header/Title/Description/Content and BodyFrame -> BodyViewport -> BodyContent; optional Footer is a direct Panel child after Outer. Conditional fixed spacers reproduce source gaps without phantom omitted-Body space. Register current public V2 after balanced callback submission. The second stored-tree calculation allocates Content/Body and Panel from current intrinsic sizes and clamps scroll before final positioning. Reuse public real-node track projection for any visible Body bar; no prior-bounds paint fallback. An Alert convenience adapter can fill Header and Footer slots from its known strings/buttons, omitting Body unless caller children exist. Initially this is an additive source-layout entry, not an implicit rewrite of the old Alert tree. A separate old-helper first-frame fitting correction is compatible with its AUTO intent only if it preserves the old all-content-scroll policy; do not claim it supplies independent Header/Footer or source parity. Prefer the one complete new tree rather than shipping a warmed-bounds workaround under a new API. ## Public compatibility and explicit remaining gate Use existing surface owner, synchronous decide/on_close and focus helpers. Keep old exported reducer/wrapper timing untouched and retain its independent frozen trace. No new Enter/global dispatcher, queued veto, cancellation marker, contact ledger or input replay. Supported callback close must avoid registering geometry for a dismissed scope and must retain borrowed storage through end_frame. The new geometry route must not claim stronger close/reopen press-lifetime protection than integrated Core provides. The separately audited held-input problem remains open; do not smuggle its prototype into this height slice or claim full lifecycle parity. Before production, integrator must explicitly accept the new route's legacy-compatible input scope or require the independent Core lifetime operation first. This is a real remaining contract gate, not a reason to substitute first-frame blank/lagged Body geometry. ## Independent focused headless witnesses to prepare 1. Capture current old Alert on its first presented frame with a short title, description and actions, then change all strings/action widths and viewport in the next frame without priming. Preserve old fixed260 behavior as a compatibility oracle, not the new route's expected result. 2. Actual current-font provider: short/long title, description and body at wide, narrow and wide-again widths; each transition is asserted immediately after one end_frame. Line counts come from an independent provider/text-style oracle; no expected height recaptured from candidate bounds. Use verified Inter regular/bold or report exact fallback font coverage honestly. 3. Assert short AUTO Panel is intrinsic (source min96), never always viewport height. Independently compute padding+current fixed/intrinsic regions using the pinned28-case flex golden where applicable. Explicit height remains exact. 4. Header+standalone Title both present; description nested in Header versus independent slot; Content+Body intrinsic-min freeze, Body omitted versus authored-empty, Footer omitted/present/oversized. Verify FooterY and Inner clipping separately, preserving actual Content-overflow source policy. 5. Current tracked Panel/region bounds, semantic clips/ranges and software pixels must agree on first-open and every resize. Long Body scrolls while fixed Header/Footer remain stationary; current shrink clamps offset in that frame. UI slot/callback counters once; borrowed bounds storage outlives end. 6. Existing callback veto/accepted-close/on_close/focus ordering and frozen legacy traces; no input-event fabrication. Held-stream reopening stays an explicit separate gate, with no all-consumer/full-family/binding claim. No new runtime result is claimed by this checkpoint. The next authorized step is a bounded test-only current-tree/current-font fixture against139695, not an arithmetic-only proof or an immediate public contract transfer. ## Integrator decision (2026-11-01) Approved the current-tree/current-font witnesses and compatible additive six-slot implementation described above. Existing input semantics are accepted for this layout slice; held-stream reopening remains an explicit unfinished lifecycle requirement. No new dispatch, cancellation marker or stronger input guarantee is approved. Measure current record layouts before publishing ABI constants. After geometry and compatibility validation, migrate the gallery Dialog and AlertDialog demos to the new route and document it as the recommended composition path. Preserve old helpers and their legacy behavior tests. Production and browser acceptance are still required; this decision is not completion evidence. ## Implementation delta after review Reuse the corrected six-slot contract, rather than introduce a new layout architecture. The new files are `cui_dialog_composition.h`, the Styled companion header, and Base/Styled composition modules. Existing public surface records and old helpers remain unchanged. The new route accepts existing Core held-input semantics; it does not promise cancellation across close/reopen. No unpublished scoped cancellation, marker, event-query or dispatch code is transferred. Candidate records retain the prior reviewed field layout: slot style32, refinement232, sizing96 (two24-byte region policies and explicit placement), composition152/84 on LP64/ILP32, layout208/200 with ten borrowed tracked rectangles. These are prior measurements and current expectations, not a fresh compiler measurement. Exact current native/WASM sizes and offsets must pass the metadata oracle before publication. No numeric byte constants are introduced publicly. The retained source golden cases and current-font fixture will run through the actual new functions. First-frame and changed text/viewport/content/action cases must pass without warm-up frames. Gallery Dialog/AlertDialog call sites are assigned to this worker only after geometry proof; surrounding gallery controls remain outside this slice. Root owns combined browser execution. ## Source-only preservation checkpoint Status: **SOURCE ONLY, UNVERIFIED**. This checkpoint preserves the isolated draft before runtime validation or possible reboot. It is not a tested production handoff. The exact source hashes and pending checks are recorded in `docs/validation/dialog-six-slot-source-checkpoint.json`. Owned changes are the new Dialog Base/Styled headers/modules and focused fixtures, plus narrow CMake/source-metadata/amalgamation registration. Existing Core, Table, old surface helpers, bindings and gallery are untouched. The draft corrects `labelled_by` to reference only an actually admitted Title wrapper; fixtures inspect empty, omitted, fallback, custom and authored-empty Title cases. Only static whitespace, Python syntax, JSON syntax and module-path existence checks ran. No C/C++ compile, native/WASM ABI measurement, runtime, current-font layout, software pixels, callbacks, configured distribution, generated freshness, skill suite or browser test ran for this draft. Canonical generated outputs are intentionally not refreshed in this source-only checkpoint, per integrator instruction; regeneration and required checks remain mandatory before handoff. The ABI assertions encode prior expectations and can still fail on this base. Gallery migration waits for geometry proof. The held-input lifecycle limitation and separate Root/host/five-facade scope remain open. --- ## Dialog per-open press admission proposal Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/DIALOG_PRESS_ADMISSION_PROPOSAL.md # Dialog per-open press admission proposal Status: design, not implementation approval. Supersedes the touch-only264-byte candidate; keeps all strict old-release failure assertions. No generated/public production API has been published for the component. ## Evidence and required behavior Private-Xvfb63930 executed three independent plain caller-child cases. Held touch, mouse and Space each produced actions1/accepted1/snapshot1 after close/reopen, two empty frames and old release. The copied public accepted-activation snapshot was read inside the callback, independently of the child counter. Existing Body/bar generation is therefore insufficient. Actions/request_close timing and new pointer/wheel behavior passed separately in5482 --actions. Keep Dialog owner, all caller IDs, focus relations and ordinary widget semantics stable. Do not synthesize events, alter Core contacts/capture, replay decisions or require a post-end finalizer. Accessibility/programmatic activation and ordinary Enter remain their existing independent paths; no global Enter mapping. ## Bounded state and lifetime Proposed private record (actual sizeof/offset probe still required): ```c typedef struct { uint64_t id, device; uint32_t type, button; } cui_dialog_press; /* candidate24 */ typedef struct { uint32_t count, flags; /* only SPACE_ADMITTED flag */ cui_dialog_press pointer[17]; } cui_dialog_press_state; /* candidate416, alignment8 */ ``` One lazy public Core resource keyed by stable Dialog owner and a fixed private namespace; no new context pointer, public layout growth or global registry. Seventeen entries cover existing sixteen Core touch contacts plus one ordinary primary mouse/pen capture. Only primary ordinary pointer capture is quarantined; other buttons keep existing noncapturing semantics. No extra Core contact slots. One416-byte local trial is used during preflight. Actual payload/allocation/slot cost must be tested, including unavailable slot/bytes and ordinary omission GC. Allocate only when a relevant fresh DOWN/Space-down needs storage. Missing or collected storage never grants admission to a continuing press. Unready composition clears admission (new open, skipped generation, failed snapshot, clear-alone, previous Body omission where applicable). Inert/layout-only/measure must not mutate admission, allocate or consume. Ordinary frame-gap detection invalidates admission on resumption. Nested-modal ineligibility invalidates local admission without consuming another scope's events. ## Ordered guard before application callbacks Run after the actual owner scope is begun, before any selected slot callback or widget reducer, only on ordinary admitted/current-eligible composition. Require public event_within_scope(owner), still-unconsumed event, and the existing same- open prior-ready gate. Unready composition keeps its reviewed owner-only guard. Never consume an event merely because its screen coordinate lies inside Dialog. Prescan in event order against a local trial. Fresh touch DOWN admits its exact (type,id,device,button). Fresh primary mouse/pen DOWN replaces the previous ordinary-pointer admission, matching Core's single ordinary capture. Duplicate Core-suppressed/consumed DOWN cannot grant admission. A matching admitted press allows continuation and release; an unknown old continuation/release is consumed before children. Remove entries on genuine terminal evidence, including converted SCROLL/GESTURE ENDED/CANCELLED; observe terminal bookkeeping outside scope without consuming that outside event. Global CANCEL clears local state but is not stolen. Fresh nonrepeat, non-IME/non-preferred-character Space KEY_DOWN admits Space; Space KEY_UP requires that admission and clears it. Other keyboard, text, accessibility and programmatic paths stay unchanged. Repeated Space-down cannot turn an old held key into a new press. Scope consumption is independent of eventual child acceptance/disabled state. Current children still apply their own eligibility. Finish all capacity/size/resource checks before committing trial or consuming any event/calling application callbacks. Then replay only the deterministic guard scan against the same immutable routed event list, consume rejected scoped events through public consume_event, and commit state. This is not input dispatch or application callback replay. consume_event's existing Core implementation clears pending/accepted activation slots; prove this through the unchanged strict public receipt oracles rather than manually changing Core activation/capture. Core retains quarantined physical contacts until genuine UP/CANCEL, preserving existing multitouch blocking. No promise to free a physical contact early; after UP/CANCEL there must be no orphan state and a genuine fresh press must succeed. ## Remaining precise public seam Touch continuation and key release are identifiable from event metadata. Ordinary mouse/pen MOVE carries no button-held bit. Suppressing all MOVE would steal normal hover; allowing all would let a custom drag reducer mutate from an old capture. Existing cui_pressed combines pointer and Space capture and says "submit behavior before querying". Calling it before arbitrary children is not currently an advertised contract. Even relaxing that timing leaves pointer-versus-Space ambiguity. A conservative guard could suppress movement on any pressed target, while ordinary unpressed hover and position-derived hover visuals remain intact; that stronger suppression requires explicit review, not a full hover claim. A precise alternative is a narrowly reviewed read-only primary-pointer-capture query usable during ordinary submission before target behavior, returning only current routed capture ID, with zero outside admission/inert/layout-only/error. No new state, dispatch, observer, contact cancellation or event mutation. This is an architectural/API decision for root, not authorized worker code. It would let the guard leave all truly uncaptured hover MOVE untouched and quarantine only old captured pointer movement. Stable caller IDs alone cannot reveal that fact. ## Gate before production Approve the movement seam first, then test-only admission proof: unchanged Body, action and plain child old touch/mouse/Space failures become successes; fresh DOWN/Space-down works afterward; unpressed hover, actual dragging, bar capture, CANCEL, two-contact blocking, unknown ongoing contact, nested scopes/background/ trigger, error/omission/inert, allocation/slot failures and cleanup. Prove public accepted receipts remain absent for quarantined releases and present for fresh presses. No full Dialog lifecycle claim before these pass. ## Revised comparison: prefer test-only two-phase scope cancellation The previous single final-capture query is NOT sufficient: MOVE+UP in one queued batch clears final capture before callbacks, although earlier MOVE was captured. A precise query alternative would need per-event evidence and a separate storage/ phase audit. Also, consuming events cannot make persistent cui_pressed false on idle frames. The416-byte ledger therefore cannot establish arbitrary-child capture closure by itself. Do not implement that ledger or query as recommended. Proposed additive Core API, subject to root review and test-only proof first: ```c /* Cancel owned persistent/pending press input; no focus/semantic withdrawal. * Ordinary submission, active named scope; no measurement/inert/layout-only, * prepaint/diagnostic/resolution or known-error mutation. */ bool cui_cancel_scope_input(cui_context *ui, cui_id scope); ``` No public record/version, context pointer or resource allocation. Proposed implementation scans bounded existing current/prior scope/semantic arrays, activation/event arrays and sixteen contacts. Resolve ownership through explicit logical scope ancestry, never coordinate bounds/fold aliases. Require full IDs. Unrelated scopes/background/trigger remain untouched. A valid scope with nothing to cancel succeeds idempotently; invalid scope/phase fails without partial state mutation. Exact diagnostic precedence follows existing mutation APIs. Owned pointer capture and Space capture are cleared; matching capture-start evidence is invalidated. Owned pending release and activation/accepted-receipt slots are canceled explicitly, not inferred from event consumption. Preserve event target/coordinates for diagnostics and existing genuine terminal routing. No focus changes, semantics removal, model callback or application event replay. The component's existing unready scoped-event guard separately consumes stale owned events before children; no broad global consume is added to Core. For an owned retained contact, clear owner and viewport and mark blocked until real UP/CANCEL. Both clearing and blocked are required: pinch checks can otherwise use retained viewport even when blocked. Do not mark inactive/free the physical contact early; preserve existing multitouch blocking while physically held. Identify touch capture contacts by copied capture-start type/id/device before clearing capture, including owner0/viewport0 button/bar contacts. Scroll/gesture contacts resolve by owner/viewport semantic membership in current OR prior scope. The Dialog calls twice on an unready/new-lifetime ordinary eligible submission: (1) after its actual scope begins and before any application callback, cancel ownership resolved from prior scope/targets; then run the scoped stale-event consume guard. This clears held mouse/Space before even idle child callbacks. (2) after children have submitted, while scope remains active and before end, resolve newly current owners and cancel remaining retained contacts. This catches scroll-owner IDs that vanished across an omitted/failed prior frame and reappear in arbitrary children, before the next frame can route against those new IDs. If a callback synchronously closes owner, scope dismissal/withdrawal is preserved; never recreate semantics or call the late helper against an inactive owner. Why the late phase is plausible without retained ancestry growth: when a contact's owner is absent from the prior snapshot, touch scroll_hit rejects it with no fallback; a missing captured child also clears capture at end_frame. Such an old contact must not mutate the first new callbacks; current submission then provides ownership for the second cancellation. A completely unowned contact with no owner/viewport/capture cannot acquire a new owner except through a genuine DOWN. This is a required runtime proof, not an assumption that current publication can roll back an earlier callback. Invalid partial ownership/current scopes and ID reuse across unrelated scopes must be tested explicitly or rejected by the component's ordinary identity contract. Expected zero additional bytes is only a candidate: prove implementation uses existing arrays/flags with actual before/after sizeof and allocator counts. If missing/failed/nested ownership disproves this two-phase argument, stop and propose bounded retained full-ID ancestry metadata; do not claim zero growth or quietly add128 bytes to opaque context. No production Core edit approved here. Proof gate extends all strict old-release cases with idle pressed-state, actual child drag, MOVE+UP batch, omitted/failed prior scope, unknown ongoing contact, new genuine DOWN after UP/CANCEL, nested modal/portal/background/trigger and inert/layout-only/error no-mutation. Verify callback counts/order, current enabled semantics, frozen legacy trace and no duplicate cancellation/dismiss callbacks. ## Integrator review resolution The final two-phase scoped-cancellation alternative is approved for an unpublished proof only. The earlier ledger and final-capture-query alternatives are withdrawn. This is an explicit additive lifetime operation over existing dispatch, not a new input-dispatch architecture; legacy routes must remain unchanged. Production API publication waits for the complete proof gate above and source review. Pending activation cancellation must use the explicit existing cancellation operation, independently of event consumption. No new storage or zero-allocation claim is established by this design approval. ## Nested component counterexample and pending-stream decision Actual89767: a same-context nested modal remains open/adjacent while the parent controlled-closes/reopens; a queued continuing child Body MOVE changes child scroll30 to40 in the first new parent frame. Gate-only18869 removes pointer- scope-allowed from explicit lifetime cancellation; the same strict assertion still fails40 versus30. Separate small logs are retained in the reused build. No generic event_within_scope modal policy changed. Reason: begin_frame already routed a touch SCROLL to the child. Contact blocking prevents future dispatch, but does not revoke that current routed delta. The parent's ordinary modal-aware stale-event guard correctly cannot act as that nested modal's input consumer. The child independently remains ready and reduces its already-routed delta. The explicit lifetime operation needs a separately reviewed pending press-stream consumption contract. Proposed bounded extension, not implemented/approved in this checkpoint: preflight a second mask for still-unconsumed owned pointer DOWN/MOVE/UP/CANCEL, Space/Enter key press samples, and touch SCROLL/GESTURE samples. Ownership is explicit current/prior full-ID scope ancestry via event target/routed touch owner or matching owned contact, not screen bounds or pointer routing permission. After all validation, atomically mark selected pending samples consumed AND cancel pending activation slots independently. Do not infer cancellation from consumption and do not call blanket origin invalidation across delivered slots. Preserve event target/coordinates for diagnostics, focus, semantics, copied snapshots, already accepted live receipts and callback/owner effects. Late cancellation cannot undo a callback that already read an unconsumed raw sample. Such raw samples may subsequently become consumed, but accepted receipt slots and their down origins remain protected from activation invalidation over the whole pass. Already accepted release events remain protected themselves. This distinction must be tested for default pointer/Space and release-policy same-batch DOWN+UP, plus independent later unaccepted activation cancellation. This is not a general input flush: unrelated scopes/background/trigger, non-touch wheel, text/composition, accessibility and programmatic input are unchanged by this Core operation. The component's existing stale-event guard remains a separate owner/modal-aware policy. Persistent physical contacts remain blocked until genuine terminal input; no synthesized event or dispatcher alteration. Before production: turn the actual nested failure into success, verify fresh child input after UP/CANCEL, add nested captured pointer drag and gesture cases, then rerun all previous strict receipts/phase/atomicity/legacy gates. Report any remaining one-shot-input/independent nested-owner policy limit explicitly. ### Integrator decision on the pending-stream extension The bounded extension above is approved for the unpublished prototype only. Selective raw-input consumption and pending activation cancellation are separate operations; neither constitutes value acceptance, callback rollback or platform default prevention. Preserve all delivered receipt evidence and unrelated input. The actual nested failure, fresh-contact recovery and previous compatibility gates must pass before any production Core/API publication is approved. --- ## Remaining retained consumer audit after the 38-case proof Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/DIALOG_RETAINED_CONSUMER_AUDIT.md # Remaining retained consumer audit after the 38-case proof Source-only checkpoint. No new reducer policy, production changes or runtime coverage beyond signed eae79383. All added fixtures below remain unexecuted. See [the canonical consumer inventory](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SCOPE_INPUT_CANCEL_CONSUMERS.md) for the integration contract. | Actual path | Submission/order and current contract | Classification / next oracle | | --- | --- | --- | | Table resize/reorder (`cui_table_reduce_common`) | Reduces before current semantics. Retained resizing/dragging consumes raw MOVE/UP before target checks; no consumed check. Borrowed column array changes in place. Width/move observers run synchronously after successful operation; programmatic changes silent; cancel does not roll back. | Source-confirmed mutation path after explicit Core cancellation. Actual nested `--retained-table-resize`, `--retained-table-reorder`, `--retained-table-idle` prepared. Require no stale width/order/callback and no orphan local press; no reset implementation until actual failure. | | Color panel (`cui_base_color_picker`) | Submits root/part interactions, ORs old dragging bits into local pressed. Raw target pointer/key samples ignore consumption, mutate HSV/RGBA, rebuild dragging bits even with zero samples. Public bool reports change and invalidates; no synchronous change callback in this Base helper. | Source-confirmed mutation/idle state path. Actual nested `--retained-color-drag`, `--retained-color-idle` prepared; compare color channels and press bits. No policy change or broader color-picker work. | | Sheet resize (`cui_surface_update_impl` / resize_event) | Surface loop skips consumed before resize helper. Retained resizing clears on global CANCEL, no_sheet_resize/kind change, routed primary UP; no idle capture-loss check. Size mutations/invalidation stay in original surface timing. | Stale consumed MOVEUP size path already guarded by source, but local resizing can persist idle. Must distinguish harmless retained flag versus later mutation with an actual Sheet fixture; not declared fixed or broken from source alone. | | Chrome title move (`cui_base_title_bar`) | Current interaction then target&&!consumed gate before move/menu actions. UP unconditionally clears move_armed/moved, even when consumed. CANCEL or non-target DOWN clears pending click/press. Host perform is synchronous and capability-gated. | Stale consumed MOVEUP host action appears guarded; idle armed and double-click history persist. Need mock-host actual idle/late-action proof before any reset rule. No native window test is needed or claimed. | | Single-line input (`cui_base_input_reduce_event`) | Clears dragging/word state on CANCEL and consumed primary UP before consumed/target guard. Fresh primary DOWN clears word state and starts selection. No idle capture-loss reset. Edits/notifications follow the existing checked synchronous engine operation. | Consumed terminal already cleans press state; idle flags still require proof. Do not erase model selection/history or fabricate edit/CHANGE notification. TEXT/composition remain outside this helper's selective suppression contract. | | Textarea (`cui_base_textarea`) | Layout/current interaction precede event loop. CANCEL clears dragging, but consumed/target check precedes primary-UP selection cleanup. External edit revision also clears dragging; no general idle loss check. | Selection mutation from consumed samples guarded; consumed terminal may leave local drag flag. Need actual selection/idle and genuine fresh-DOWN oracle before policy. No fake selection/edit callback. | | Editor multi-selection | Clears multi_pointer/column_dragged on global CANCEL or focused/revision/style mismatch. Consumed check precedes pointer-UP cleanup; no generic idle loss check. | Source boundary only; user deprioritized Editor, no polish/implementation planned here. Do not infer safety from Textarea or broaden text/IME behavior. | | Typed Slider (`cui_base_slider_model_events_v1`) | Existing consumed check and post-reduction capture-loss cancellation: when snapshot ready, dragging and !cui_pressed(captured_target), emits CAPTURE_LOST with no input. Earlier option/source/domain/axis/omission precedence and immutable owner snapshot remain intact. | Existing focused tests cover Escape/capture loss. Actual nested `--typed-capture-lost` prepared to exercise this explicit helper, idle CANCEL/no fake input and fresh BEGIN/COMMIT. No typed reducer change proposed. | ## Prepared fixtures and honest boundaries The six prioritized modes use the actual public Base reducers in a still-open nested Dialog child while the parent is controlled closed/reopened. Table uses real header/resize hit boxes and synchronous width/move observers; state is not manually seeded as dragging. Color uses its actual hue part and model. Typed Slider uses actual thumb capture, existing CAPTURE_LOST request and fresh gesture. All borrowed model/state/bounds storage survives end-frame and is destroyed only after the completed frame. These source fixtures have not compiled or run yet. If Table/Color fail, propose only clearing their owned local pending press flags and suppressing explicitly canceled samples under the opt-in marker, preserving already delivered model changes. A fake width/move/completion callback or rollback would contradict their existing contract; exact disposition still requires the actual failure and root review. No generic ordinary consumed semantics change. Source checks alone do not establish all-phase safety. For example the raw Table and Color paths lack an obvious general ordinary/inert admission guard, whereas the explicit cancellation operation rejects inert/layout-only/measurement. Those legacy behavior questions must not be silently folded into this lifetime slice or addressed with a new global dispatcher policy. TEXT/COMPOSITION still retain their original event payload, target, consumption and model-session rules, as the 38-case matrix proved. That preservation is not proof that a retained text editor inside a reopened owner has complete lifecycle closure. Any suspected stale-text or composition-session mutation needs its own strict actual counterexample and reviewed policy; no new selection is proposed. --- ## Dialog slot composition V1: Base/Styled contract checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/DIALOG_SLOTS_V1.md # Dialog slot composition V1: Base/Styled contract checkpoint Status: proposal only; no Base/Styled implementation approved by this checkpoint. Base: `6c69bb1d`. This replaces the withdrawn prior-frame/settling geometry in `44e182d4`; it uses the landed Core contract in `docs/SCROLL_LAYOUT.md`. The runtime proof remains `3d9d8544`; Core production originated at `b3e03bc9`. Existing surface, options, events adapter and Root public structs do not grow. Subsequent scrollbar design authority is `SCROLLBAR_TRACK_LAYOUT_V1.md`: real fixed track/thumb nodes staged before the existing second calculation, with independent visibility/interactivity policy. The earlier paint-hook and semantic projection discussions below are preserved review history, not the recommended final scrollbar representation. Its test-only proof does not approve Dialog production or close the Root/host/five-facade scope. ## Authority and scope CUI authority: `include/cui/cui_surface.h`, `include/cui/cui_surface_events.h`, `src/base/cui_surface.c` (`cui_base_surface_update`, begin and body submission), `src/components/cui_surface.c` (styled begin/footer/end and scroll skin), and `src/base/cui_overlay.c` (focus capture/restore). Existing tests are in `tests/unit/test_surface.c`; Core admission/failure tests are in `tests/unit/test_scroll_layout_contract.c` and `test_scroll_layout_geometry.c`. Pinned comparison: upstream component 0.7.1, commit `87d10ae5e1299d1be18670a37570c5402f952e34`, `dialog.rs` render and `base-dialog.rs` render/action handlers; `header.rs`, `title.rs`, `description.rs`, `content.rs`, `footer.rs`, `dispatch_anchor.rs`, `root.rs`. The earlier signed `acc877f24` audit records full paths and hashes. Required raw files already exist locally; this checkpoint needs no dependency installation. Source header/title/description/content/footer admit children and refinement; body is the scrolling children region, footer remains outside it. Header/content builders and body children are distinct. Source title/description visual content must not be confused with accessible name/description. Source base actions veto synchronously. Source Root defers confirmed close and closes cancellation immediately; this C slice retains C's existing immediate close and observer order. This slice supplies all six visual slots and owner-scoped C actions. Root/host registration, source global Enter dispatch, source placement/animation fidelity, and all five foreign builders are separate work. No claim of complete Dialog parity follows from landing this slice alone. ## Concrete additive declarations New portable header `include/cui/cui_dialog_composition.h` includes surface and scroll headers. Names below are the proposed exported names, not existing APIs. Enums use C enum parameters; record discriminants/masks use fixed uint32_t. ```c #define CUI_DIALOG_COMPOSITION_VERSION_1 1u typedef enum { CUI_DIALOG_HEADER, CUI_DIALOG_TITLE, CUI_DIALOG_DESCRIPTION, CUI_DIALOG_CONTENT, CUI_DIALOG_BODY, CUI_DIALOG_FOOTER, CUI_DIALOG_SLOT_COUNT } cui_dialog_slot_kind; typedef enum { CUI_DIALOG_CONFIRM, CUI_DIALOG_CANCEL, CUI_DIALOG_CLOSE } cui_dialog_action_kind; typedef struct cui_dialog_frame cui_dialog_frame; /* borrowed callback token */ typedef void (*cui_dialog_slot_fn)(cui_context *, const cui_dialog_frame *, void *); typedef struct { cui_dialog_slot_fn emit; void *user; } cui_dialog_slot; typedef struct { uint32_t fields; cui_color foreground; float font_size, padding, gap; uint32_t align_x, align_y, reserved; } cui_dialog_slot_style_v1; typedef struct { uint32_t struct_size, version, panel_fields, reserved; cui_dialog_slot_style_v1 slots[CUI_DIALOG_SLOT_COUNT]; cui_color background, border; float radius, padding, gap, border_width; } cui_dialog_refinement_v1; typedef struct { uint32_t struct_size, version, present, reserved; cui_str name, description; cui_dialog_slot slots[CUI_DIALOG_SLOT_COUNT]; const cui_dialog_refinement_v1 *refinement; } cui_dialog_composition_v1; typedef struct { uint32_t struct_size, version, mode, reserved; float width, requested_height, min_height, max_height; } cui_dialog_sizing_v1; typedef struct { uint32_t struct_size, version, reserved[2]; cui_surface_state *surface; float outer_y; uint32_t reserved2; cui_rect completed[8]; uint64_t last_submit_frame; } cui_dialog_layout_v1; typedef struct { bool valid, submitted; } cui_dialog_submit_result; bool cui_dialog_layout_init_v1(cui_dialog_layout_v1 *, cui_surface_state *); bool cui_dialog_composition_valid_v1(const cui_dialog_composition_v1 *); bool cui_dialog_sizing_default_v1(cui_surface_options, cui_dialog_sizing_v1 *out); cui_dialog_submit_result cui_base_dialog_compose_v1( cui_context *, cui_dialog_layout_v1 *, cui_surface_options, const cui_dialog_sizing_v1 *, const cui_dialog_composition_v1 *); cui_dialog_submit_result cui_dialog_compose_v1( cui_context *, const cui_theme *, cui_dialog_layout_v1 *, cui_surface_options, const cui_dialog_sizing_v1 *, const cui_dialog_composition_v1 *); bool cui_dialog_slot_style_v1_get(const cui_dialog_frame *, cui_dialog_slot_kind, cui_dialog_slot_style_v1 *out); bool cui_dialog_slot_begin_v1(cui_context *, const cui_dialog_frame *, cui_dialog_slot_kind, cui_id wrapper_id); void cui_dialog_slot_end_v1(cui_context *, const cui_dialog_frame *); cui_interaction cui_base_dialog_action_v1(cui_context *, const cui_dialog_frame *, cui_id, cui_str name, cui_dialog_action_kind, bool disabled); bool cui_dialog_action_v1(cui_context *, const cui_dialog_frame *, const cui_theme *, cui_id, cui_str name, cui_dialog_action_kind, cui_button_options); ``` Record masks: six `present` bits correspond to slot enum values; no other bits. Slot fields are FOREGROUND=1, FONT_SIZE=2, PADDING=4, GAP=8, ALIGN_X=16, ALIGN_Y=32. Panel fields are BACKGROUND=1, BORDER=2, RADIUS=4, PADDING=8, GAP=16, BORDER_WIDTH=32. Align values are the public Core alignment values. All reserved fields zero; exact struct_size/version required. Active floats finite; font_size positive; padding/gap/radius/border_width nonnegative. Sizing mode is Core AUTO or EXPLICIT and follows Core requested/min/max rules; width finite positive. No infinity sentinel. Unknown masks/modes fail before callbacks. Candidate LP64 layouts: slot=16, slot_style=32, refinement=232, composition=152, sizing=32, layout=168 bytes. These are field-layout calculations, not compiler measurements; implementation must measure LP64/ILP32 and add offset assertions before declaring an ABI byte constant. No existing options ABI growth. `completed` order: Panel, Header, Title, Description, Content, BodyViewport, BodyContent, Footer. Absent parts clear their retained rectangles on submission; completed geometry becomes usable only after a successful end_frame. Outer/column ranges can be obtained through named IDs and Core scroll semantics. ## Callback and manual ownership Compose is the sole owner of panel, structural boxes, focus scope and end balance. There is deliberately no public manual top-level begin/end API in V1: the complete closed tree must be registered with Core before compose returns. Each selected callback runs once in declared order. No layout/measure pass re-enters application composition. Text measurement can repeat, exactly as documented by Core. The frame token is valid only during its callback; it borrows the layout, options and resolved styles. A callback may emit arbitrary ordinary CUI children, including nested dialogs with a different layout/state, and manually balanced slot wrappers using begin/end above. A wrapper styles the requested slot using an explicit caller ID; it does not invoke another slot callback or change slot presence. No automatic anonymous wrapper is silently substituted for a failed caller ID. Manual wrappers cannot span callbacks. Leaked boxes, reused owner/layout in the same frame, structural IDs reused by callback children, and foreign frame tokens are errors. Public helpers cannot make arbitrary malformed application trees safe. Absent bit selects fallback; present+NULL callback means deliberately empty. Header fallback emits Title then Description; custom or authored-empty Header suppresses both automatic children, and simultaneous Header plus Title/Description presence is rejected. CONTENT fallback empty; BODY fallback empty; FOOTER fallback empty. Title/Description fallback renders semantic strings only when nonempty. Custom visual content never replaces `name`/`description` implicitly. Header, Content, Body and Footer are invoked in that order; Title/Description callbacks occur inside fallback Header. Title/Description wrappers remain independently styleable. Theme defaults resolve before panel/slot explicit fields; Base uses neutral unpainted defaults and never fabricates a theme. BODY padding applies inside BodyContent, never to the zero-padding structural clip/frame. ## Geometry, constraints and bars New named parts via existing public `cui_surface_part_id`: preserve Close=1, Confirm=2, Cancel=3, Title=4, BodyViewport=6, BodyContent=7; propose Header=9, Description=10, Content=11, Footer=12, OuterViewport=13, Column=14, BodyFrame=15, Mount=16. Validate all full IDs and folded aliases using Core's normal rules, including custom child collisions; no copied hash or allocator. Mount is a transparent portal over options.viewport inset by options.margin; Panel (owner ID) is its ordinary centered child, with current intrinsic height. The existing backdrop remains separate. Panel has fixed constrained width `min(sizing.width, usable_width)` and may have padding. Nonpositive usable extent fails instead of inventing a readable spacer. Final current-frame centering follows normal layout of Mount; no previous height, guessed height or first-frame blank. This preserves C's centered Dialog placement. upstream's preferred y=viewport/10, layer offsets and oversized snap-up policy remain an explicit placement gap, not a claim of this composition API or an alteration of the old route. Exact Core chain: Panel -> OuterViewport -> Column -> BodyFrame -> BodyViewport -> BodyContent. Outer/Viewport have only the named flow child; BodyViewport attaches to BodyFrame with inherited clip, GROW at offset zero. Header, Content and Footer are fixed intrinsic siblings of BodyFrame in vertical Column. Outer/BodyViewport clip; Column/Frame do not; structural clip/frame padding zero. BodyContent FIT Y, width fixed from the constrained width minus resolved horizontal padding. GROW descendants under a width-constrained ancestor are allowed; height-dependent widths, percentage/aspect feedback and reserved scrollbar gutters are not admitted. Ordinary nested independent-width constraints follow Core validation, not a general constraint closure promise. Let P be panel vertical padding, F measured fixed regions plus gaps and I current intrinsic BodyContent height. AUTO H=clamp(P+F+I,min,max); EXPLICIT H=requested. Effective max=min(sizing.max_height, usable viewport height); reject min>effective max, or EXPLICIT outside that interval, before composing. Styled convenience sizing initializer (proposed `cui_dialog_sizing_default_v1`) selects width420, AUTO/min0/max usable height. A source-like minimum96 must be explicit, not an unconditional spacer for short content. Base requires a sizing record. If F<=H-P, Body receives remaining height. Otherwise Body receives I and the whole Column scrolls in OuterViewport, preserving reachable fixed controls. This is Core's admitted oversized-fixed-region policy, not footer clipping or silent header/footer shrinkage. Empty Body has intrinsic zero; authored-empty callbacks still run exactly once. Both scroll offsets clamp using current final dimensions. Overlay bars only: no reserved width feedback. NULL options.scrollbar_style resolves theme for Styled; Base emits no paint. Explicit invisible style omits paint while scrolling and semantics remain. Body/outer bars appear only for a positive current range; omit Body bar in the oversized-fixed policy when its body is fully exposed. Current final rectangles/ranges are read at one registered prepaint paint hook, never from last-frame scroll-skin geometry. No model mutation, input replay, semantic duplication or child composition in that hook. Its bounded frame descriptor must live through end_frame. The existing legacy scroll skin remains untouched. Validate hook/resource capacity before application callbacks where possible; a later failed opt-in frame follows Core failure semantics. ## Owner actions and close compatibility A new action helper uses the ordinary Button reducer/activation and existing surface decision and close functions; no action queue, dispatch graph or global Enter interception. CONFIRM->ACCEPTED, CANCEL->CANCELLED, CLOSE->CLOSED (C legacy reason). On accepted activation, decide runs synchronously in the same callback; veto leaves open. Acceptance closes immediately, restores focus, then on_close, matching existing C order. Consumed events, disabled controls and held key repeats follow ordinary Button rules. Enter activates only the focused Button. There is no source global confirm or implicit default action in this slice. Important implementation requirement: refactor the private surface update reducer into common dismissal/scroll handling plus optional legacy reserved-action handling. Existing public update/begin call it with legacy handling unchanged. New compose calls it with reserved action handling disabled; default/custom helpers own their Button activation, so parts1/2/3 cannot trigger a second decide before helpers run. This is a private reducer split, not a new input dispatcher. Pending public request_close still resolves at update entry with existing next-update timing; escape/outside still resolve there. Imperative surface_close still bypasses veto. New helper closure does not stop already-entered callbacks from balancing boxes; subsequent helpers cannot re-close a closed owner. No retry or replay after veto. Default visible Close uses part1 and helper CLOSE, honoring hide_close and Alert's show_alert_close. No automatic confirm/cancel buttons: authored Footer owns those. Custom actions may use parts2/3 or distinct IDs but never a structural ID; kind is explicit, not inferred from numeric ID. Alert uses identical slot topology and existing Alert dismissal defaults; no implicit change to old alert_dialog helper. No action helper is valid outside an active owner callback. During decide/on_close, retain existing events adapter restrictions on reentrant mutation/destruction; no stronger observer rollback guarantee is introduced. Existing observer wrapper options can be passed unchanged. Synchronous foreign veto is not implemented by this C helper; its language-specific exception/reentrancy contracts need review. ## Lifetime, allocation and failure Layout is new caller-owned stable storage, one per surface; initialize while closed, do not copy/move while a frame borrows it. Surface and layout outlive end_frame and any attached events adapter. `outer_y` and surface.body_scroll are borrowed writable Core clamp destinations. Retained completed rectangles live in layout, never callback stack. Records/callback descriptors/refinements are borrowed only for the compose call; emitted strings use ordinary Core text lifetime rules. Frame-only style/paint copies must use bounded Core frame storage, not retained callback pointers. No process-global active layout or hidden application heap. Per compose consumes one Core body link/two clamps (32/64 global frame caps). No per-dialog permanent heap; caller layout168 candidate bytes plus existing state. Implementation must measure frame descriptor/paint-hook storage and resource cost; reserve before callbacks and report capacity failure rather than truncate slots. No numeric allocation claim beyond the landed Core7216-byte lazy plan is proven here. Closed owner returns valid=true/submitted=false without callbacks/resources. Invalid descriptors fail with INVALID_ARGUMENT before user callbacks; malformed submitted topology/fold collisions or Core resource failure invalidate the frame. Return submitted is admission only, not final geometry success. A failed opt-in end_frame has non-OK error, empty draw and no prepaint/valid snapshot guarantee; no stale completed rectangles may be advertised as current. Error clearing within the same frame cannot salvage it. Clear/rebuild next frame recovers. Application callback effects and delivered input/observer calls are never rolled back. Teardown needs no new layout destructor: close through existing API, finish any borrowed frame, detach event adapter under its existing closed-only contract, then discard layout/state. Clearing or reinitializing only layout while open is invalid. Reopen resets outer/body offsets to zero in the new route; legacy reopen behavior stays unchanged. Switching old/new routes on an open surface is a caller contract violation: close first and reinitialize explicitly. Same-frame duplicate new-route submissions are diagnosed; without growing legacy state this V1 does not promise detection of every cross-frame call to an old API. Do not claim an unavailable route registry. ## Independently reviewable implementation and proof First slice: new Base/Styled header/implementation, private reducer split, bounded current-geometry bar hook, C example, docs/metadata and all generators. No Root, native host or bridge ABI changes. Keep legacy public structs and old begin/end, footer and alert helper bodies behaviorally unchanged. No new Core/vendor phase. Root/host follow-up owns mount/removal, focus restoration and confirmed deferred close compatibility; it cannot be represented as completed by this C slice. Required C tests: callbacks-once (including nested dialogs and present-empty), rich/custom Header/Title/Description and semantic names, Content versus Body versus Footer order, refinement defaults then overrides, first-open short AUTO and long AUTO, narrow/wide wrapping and height resize, explicit/min/max and invalid sizes, oversized fixed controls reachable by outer scroll, same-frame shrink clamp with draw/hit/semantics/caret, empty/hidden/overflow bars, inert/measurement no offset commit, allocation/capacity failure and next-frame recovery, late retained aliases, custom structural collisions, nested focus and independent owner actions. Test same-frame decide/veto once, close reasons, focused Enter/no global Enter, disabled and consumed events, deferred public request_close, observer-after-focus order. Legacy oracles compare old begin/footer/alert draw geometry, event timing, semantics, focus and state transitions before/after the private reducer split. Headless and portable C11; native wrapper/private Xvfb only; no claim from arithmetic-only tests. Second slice: Root/native host sidecar and real ownership/teardown tests, separately reviewed. Third slice: bridge plus Python, JavaScript, TypeScript, Go, Rust typed slot trees and owner actions. Preserve each runtime's rollback and app-selected library authority, old missing-symbol loads, copied bounded node state and node reuse. Native C callbacks are not foreign synchronous veto support. Before that slice, specify NAPI/cgo/Rust/Python callback lifetime, exceptions/panics, reentrancy and thread restrictions with tests; never substitute queued foreign veto. Typed TS must match JS. All five remain planned, not implicitly satisfied by C examples. ## Review correction: two viewport paint owners, no cross-part bounds query The single-hook wording above is withdrawn. `cui_bounds` checks previous semantic bounds first; retained tracking publishes after prepaint. Neither is a current cross-part geometry seam. Proposed replacement needs no new public API: * Register one local prepaint callback on OuterViewport13 and one on BodyViewport6, while each actual box is open. Each uses only its own `info.bounds`, `info.clip` and `info.visible_bounds`. Never use `cui_bounds` or retained rectangles there. * Submit a current scroll semantic for each viewport during ordinary composition. In each callback call public `cui_semantics(ui,&count)` and copy the matching own-owner details.scroll_y/scroll_max_y to locals. Do not retain the returned array or use its bounds, parent links or eligibility as completed snapshots. Require exactly one matching owner with finite nonnegative range and finite offset in range; otherwise return false and diagnose an internal composition invariant before advertising a successful frame (implementation must choose existing error reporting, not silently hide mandatory missing semantics). * Current phase authority: `cui_core_scroll_layout_end` commits both clamp ranges to ui->semantics before returning to end_frame; then `cui_core_prepaint_prepare` invokes callbacks. `cui_semantics` directly returns that current array and has no phase ban. This is a read-only current submitted semantic view, not final accessibility publication: semantic filtering/bounds assignment and previous snapshot commit occur later. The new consumer guide should explicitly document this narrowly tested read contract; no generic current-part geometry query or observer is introduced. * Infer own content height only as own viewport height + its current maximum; compute thumb with public cui_scrollbar_thumb_ex. Own zero range means no paint. The body's zero range naturally omits its bar in oversized-fixed-region mode. Local stream clips to own visible bounds; no deferred paint or caller clips. Proposed copied payload (private component type, not public ABI): ```c typedef struct { cui_context *ui; /* borrowed through end_frame */ cui_id owner; cui_scrollbar_style style; /* full value copy, no pointers */ float opacity; /* ordinary-submission fade result */ } cui_dialog_bar_paint; ``` Candidate LP64: offsets0/8/16/60, sizeof64, align8. Style candidate sizeof44 (enum4, five bools, padding3, six floats, two colors). Verify these with actual compiler before implementation handoff; ILP32 ABI alignment is not assumed. Two payloads=128 bytes plus at most30 alignment bytes (Core max_align_t=16 candidate) in existing frame storage; no tail, theme pointer, layout pointer or retained semantic pointer. Two hook registrations consume two max_elements prepaint slots and reserve eight command units total: per hook at most track RECT + thumb RECT + two Core-owned clips. Hidden/zero-range paint emits nothing; no callback-driven budget expansion. Existing Core per-element prepaint metadata/command backing is already allocated by configuration; these consume capacity, not an additional persistent allocator. Measure metadata sizeof and actual frame-copy accounting in the test fixture. The hook never invokes opacity reducer or application callback: resolve skin and existing fade state during normal submission, copy opacity, then geometry alone changes at prepaint. VISIBLE is the deterministic first-open proof case; AUTO_HIDE must separately test existing fade scheduling/hover policy, without claiming that this geometry seam changes that policy or adds current-frame scrollbar input. Prototype required before production approval: a TEST-ONLY public-API fixture on the landed Core tree, two hooks with copied payloads, persistent tracked bounds, current semantics and recorded emitted RECTs. After first-open long AUTO, resize narrow/wide and shrink height/body from the bottom. Assert each hook's bounds against its post-end tracked viewport and range against final semantics; assert thumb geometry from those exact values, and that a previous-geometry sentinel would produce different expected output. Include first-open short/empty (no bars), oversized fixed regions (outer only), nested owners, hook/payload capacity failure, no duplicate composition or input effects, and failed Core frame (zero hooks). Do not count a static phase audit as runtime proof. No fixture has been run for this checkpoint; compiler slot remains with root until explicitly released. Reducer correction is intentionally narrower than a generic policy parameter: only the three activation comparisons for parts1/2/3 are gated off for new compose. Pending request processing, Escape, outside pointer, scroll, consumed checks, focus restore and observer ordering retain their existing statements and order. Legacy update/begin pass that gate enabled. Tests must compare both routes for dismissal/observer timing and prove helper-owned activation is decided once. ### Test-only prototype results (portable Linux, pending production review) `test_scroll_layout_geometry unused --probe-dialog-bars`, registered as `dialog_scrollbar_prepaint_probe`, exercises the proposed public seam. The hook itself uses only public APIs; existing test-only Core instrumentation separately measures storage and confirms no resource/input/text mutation across layout. No production source, public header or vendor change accompanies this prototype. Measured LP64: copied payload64, shared style44, existing Core prepaint metadata192 bytes per registration. Two hooks consume384 bytes of existing metadata capacity, 128 payload bytes plus actual max_align_t padding, and reserve8 command slots. The parent fixture's18 registrations used1339 frame bytes including187 alignment bytes (not a constant per-frame allocator charge); two payloads can require up to 30 padding bytes when max_align_t alignment is16. Caller geometry storage remains persistent through end_frame. Test payload stack is overwritten after registration and the copied data still drives the final paint correctly. The prototype emits track/thumb RECTs, checks their final geometry against post-end retained viewport bounds, and reads each own current semantic range at prepaint. Long first-open, narrow/wide and height resize, bottom-offset shrink, short/empty Body, oversized fixed Header and nested independent owners exercise both bars. The independent range oracle checks final tracked content-minus- viewport dimensions and committed offsets. Final command alpha is50 for original alpha200 × fade.5 × ancestor.5, and25 beneath two .5 ancestors. The payload never multiplies prepaint_info.opacity; Core performs inherited opacity exactly once. This is a draw-command alpha proof, not a raster/text/GPU comparison. Command reservation exhaustion and frame-copy byte exhaustion reject registration, produce no partial callback output, and recover the next frame after error clear. A failed Core constraint frame invokes no prepaint callback. Ordinary composition counts remain once per callback. Nested test marker colors were initially shared and caused a parent-vs-child oracle mismatch; distinct markers fixed the fixture without changing expected geometry or tolerances. No production fault was inferred. AUTO_HIDE fade scheduling/interaction, production skin resolution and full Styled integration remain unimplemented and unproven by this geometry prototype. Validation on this checkpoint: focused warnings-as-errors Release target build, then 4/4 selected CTests passed through private Xvfb, including the original current-font geometry/AUTO and draw/hit/semantic/caret clamp tests. Reproduce in an existing configured portable build (no native windows): ```sh nice -n 19 taskset -c 0 cmake --build BUILD --target test_scroll_layout_geometry --parallel 1 nice -n 19 taskset -c 0 python scripts/test_local.py --build-dir BUILD \ -R '^(dialog_scrollbar_prepaint_probe|scroll_layout_geometry|scroll_layout_scroll_resize|scroll_layout_auto_size)$' -V ``` Instrumentation helper tests2/2, installed skill tests18/18, canonical skill freshness, clang-format23.1.2 on changed C/header files and diff checks passed. No whole-library rebuild, Windows/browser/GPU run or production API claim. ## Input review addendum: two owners and a remaining bar-hit seam Static authority: `src/base/cui_scroll.c` functions cui_base_scrollable / cui_base_scrollable_finish / cui_base_scrollbar_overlay / cui_base_scrollbar; `src/core/cui.c` cui_core_touch_owner, cui_core_touch, cui_core_scroll_hit and cui_defer_scroll_event; public `cui_scroll.h` and `cui.h` comments. No input prototype or production change is included here. ### Wheel, touch and nested consumption proposal Both OuterViewport13 and BodyViewport6 are actual semantic scroll owners. Each uses vertical-only public cui_base_scrollable with hide_scrollbars=true before its children, and cui_base_scrollable_finish after its children. Fixed header, Content and Footer sit inside Outer, so their overflow is reachable. Body is a semantic/layout descendant of Outer; nested callback-owned scroll owners remain ordinary descendants. Do not give Outer an explicit parent that skips the modal scope, and do not flatten nested parents. Core publishes final ranges from the registered two clamps, as already proven by the paint prototype. Input options use the *last successfully completed* retained viewport and content extents, wheel_step48, vertical=true, horizontal=false, axis_lock=false, gesture_lock=false, trap_horizontal=false, disabled=false. First-open has no previous hit region; zero-range placeholder geometry must not advertise an interactive scrollbar. Previous input geometry is intentionally allowed; it is never passed to the current paint hook. Nonfinite stored model values are handled under the Core registration error contract, not silently repaired after admission. Use one stack-local cui_scroll_state per owner for wheel reduction, initialized from its stable model Y (surface.body_scroll or layout.outer_y), with x=0 and no persistent drag flags because hide_scrollbars=true. Copy Y back after begin and finish; Core registration borrows the stable model destinations, never this stack state. If an overlay drag helper changes Y between begin and finish, synchronize the stack reducer Y from the model before finish so finish cannot overwrite it. Update each clipped box via cui_set_box_scroll_offset after finish. The ordinary Base helpers may invalidate on changes as appropriate; no event replay in layout. Core input chooses a previous-frame eligible scroll hit and, for touch, a bounded contact owner. Touch threshold/cancellation, capture and precise pan conversion remain Core's existing path; Dialog adds no raw touch handler. A child wheel that changes its value is consumed by the existing Base reducer. An unchanged child calls public cui_defer_scroll_event to an eligible ancestor; the parent's finish runs after the child, processes only still-unconsumed events now targeted to that parent, and may defer onward. Do not loop until exhaustion or replay residual partial deltas: existing Base behavior consumes the whole event if any value changes. Core may route directly to Outer when Body cannot scroll in that direction. Touch scrollbar priority is already role-based (SCROLLBAR suppresses competing ancestor pan); no new touch dispatcher is proposed. Platform gesture-lock limits, modal clipping and previous-frame ancestry remain exactly the Core contract. A necessary correction to the earlier reducer gate: gating ONLY reserved action parts1/2/3 while retaining the legacy Body6 wheel execution in the new route would double-apply Body scroll before Base reduction (the old wheel branch does not consume). That arrangement is rejected. New compose must select a private reducer route with **both** legacy reserved-action reduction and legacy Body-wheel reduction disabled, because public Base owns those operations there. The old public update/begin route executes the existing wheel statements, arithmetic and ordering unchanged. Pending request_close, Escape, outside dismissal, focus and observer statements retain their exact ordering on both routes. This additional route gate needs explicit review; it is not permission to change legacy wheel semantics or move observer timing. Do not run the old branch and restore the value afterward: a close observer could already have observed the transient mutation. Retain OuterViewport/Column bounds separately for input. Amend the proposed NEW layout record's completed array from8 to10 (append OuterViewport and Column), adding32 caller bytes: computed LP64 layout200, not168. No old public struct grows. Do not use raw cui_bounds(Column) mid-submission as a guaranteed retained snapshot. A failed completed frame does not refresh the last-successful input geometry; there is no valid current UI snapshot to interact with until recovery. ### Visible overlay drag: public reducer reuse and precise limitation After each owner's Base begin and before child composition, call public cui_base_scrollbar_overlay with that owner's previous positive viewport/content extents, vertical-only options, a copied/resolved VISIBLE or AUTO_HIDE skin, local x=0 and stable modelY. The helper owns persistent dragging/grab state in the context via its existing resource key; no private resource lookup by Dialog. Use public cui_scrollbar_id(owner,true) for its semantic ID. The helper handles track page click, thumb grab/move/release, keyboard Home/End/Page/arrow, primary button selection and CANCEL through existing cui_base_scrollbar. Hidden bars still run the scroll-owner begin/finish path but reset/omit overlay controls through existing helper policy; wheel/touch scrolling stays enabled. Opacity is computed in ordinary submission only and copied as fade, never ancestor opacity. Do not call the old overlay paint helper with previous dimensions; current paint remains the two proven own-viewport hooks. However this reuse alone is NOT a complete visible control. The Base overlay helper submits scrollbar semantics but creates no layout box. Its drag reducer uses cui_bounds(bar_id), i.e. previous completed bar bounds. The old Styled overlay paint helper creates fixed geometry boxes during submission. A prepaint RECT does not create a semantic hit region. Emitting those old fixed boxes from retained geometry would leave the NEXT hit snapshot stale relative to the current painted bar after resize/shrink. That is beyond ordinary previous-frame input routing: next-frame input should hit the bar actually painted in the completed frame. Existing public absolute boxes allow parent-fill height, but the admitted Core scroll layout explicitly rejects nonregistered floating descendants with nonfixed width/height (`cui_core_sl_floating`). It also has no public right-edge attachment or semantic-only current hit-rectangle setter. A nonflow GROW track is therefore not a currently admitted shortcut, and a fixed previous-height track is not current geometry. Prepaint cannot submit semantics/layout or mutate drag state. The passing prototype proves current paint, not this missing hit projection. The remaining narrow seam for review is a bounded opt-in **scrollbar semantic projection associated with an already registered viewport clamp**, not a generic observer or arbitrary hit rectangle API. It would associate public-derived bar ID with its viewport, resolved thickness and visible/fade eligibility; compute the current right-edge track from final viewport bounds; publish current clipped bar bounds, owner parentage and maximum/value to the completed semantic hit snapshot; and expose that same projected hit region to prepaint occlusion. Next input then uses that completed bar via the unchanged Base overlay reducer. Zero range or hidden/zero-opacity eligibility withdraws the control and capture according to existing disappearance rules; current paint is omitted as today. Inert/layout-only and errored opt-in frames must not publish it. Projection must not compose a callback or dispatch input, and must not update state during prepaint. This requires a separate concrete Core contract/implementation review: final semantic bounds alone are insufficient if current prepaint occlusion still uses the viewport-wide layout node. Both consumers must use the same clipped projected region; no fake passive whole-viewport hitbox, private Clay access from components, second action node, or source ID hash copy. Capacity must reserve at most two projection associations per composed Dialog, with full/folded alias validation, atomic registration and resource budget before callbacks. Exact record/storage and phase placement are intentionally not invented as approved APIs here. The no-new-Core alternative is an explicitly limited wheel/touch-only Dialog with noninteractive decoration bars. It does not satisfy the requested full visible bar controls and is not the recommended completion claim. Therefore Base/Styled production remains gated on the narrow projection decision (or a separately proved currently admitted layout representation), even though the two-owner wheel/touch route can reuse the existing public reducers. Required follow-up proof: queue real wheel and touch frames against completed snapshots; long Body versus oversized fixed Outer; nested child consumes, edge defers and outer consumes once; hidden bars preserve scrolling; track click and thumb drag/cancel/release for BOTH owners; current resize and shrink while dragging; painted track equals completed hit region and next-frame target; no stale bar after range vanishes, inert/failed frame publication and recovery; legacy surface wheel and observer byte/state/timing oracles unchanged. All Root/host/global-Enter/source placement and five-facade gaps listed above remain open. --- ## Dialog source placement: existing-tree proof Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/DIALOG_SOURCE_PLACEMENT_PROOF.md # Dialog source placement: existing-tree proof TEST ONLY on Core `d4a1d847`, following component contract `7431bdd3`. No source-position component API is admitted by static preparation alone. ## Frozen source authority upstream Kit0.7.1 `87d10ae5e1299d1be18670a37570c5402f952e34`, `crates/component/src/dialog/dialog.rs:560-745` computes preferred y as viewport height/10 plus layer index*16, width constrained by horizontal margins, and Panel max height as viewport height minus margins and layer offset. `crates/base/src/positioner.rs:210-225,303-324` resolves a top-left corner and clamps bottom overflow upward, then clamps top to margin. Exact raw file is 26213 bytes, SHA256 `7034aaeee0a19d301c814d38487ab13103a3e83a3d5f733ac4e5183c0478f883`. Only this missing pinned source was fetched into the existing audit cache; no crate, engine, application or dependency was built. Existing28-row Taffy engine oracle remains unchanged. Positioner itself is inspected source, not executed upstream; numerical constants below follow its explicit clamp statements. ## Candidate tree using public APIs only Root-attached portal Mount fills usable inset viewport; horizontal alignment CENTER. Before the ordinary V2 Panel submit a GROW spacer with maximum `max(0, preferred_top-margin)`. For zero cap OMIT the spacer: public max_height0 means uncapped, so a zero maximum would be incorrect. Panel width is fixed and independent of allocated Y. Core V2 stages current Panel height before its already-approved second stored-tree calculation; spacer then receives remaining height up to its cap. No prior bounds, callback replay, third calculation, private Core access, prepaint mutation or new Core record is involved. This tree should place Panel at `margin + min(max(0,preferred_top-margin),usable_height-current_panel_height)` for admitted current Panel height <= usable height. Exact Positioner equivalent is its bottom-overflow shift followed by top clamp. Oversized Footer may extend beyond Panel by existing source geometry policy; it must not change Panel's placement demand into a whole-descendant bounds union. ## Frozen expected runtime cases Margins16; same UI transitions between every row, without priming frames. | Viewport | Current Panel height | Preferred top | Expected top | Panel width | | --- | --- | --- | --- | --- | |400x600|40|60|60|240| |400x600|550|60|34|240| |400x600|568|60|16|240| |180x220|188|22|16|148| |180x220|40|22|22|148| |800x800|80|96|96|420| |800x800|740|96|44|420| |400x600|40|0|16|240| |400x600|568|60|16|240| |400x600|40|60|60|240| The explicit preferred96 case models viewport/10+one16px layer offset; its caller-provided Panel max in this fixture is deliberately independent, not an assertion that component layer defaults have already been implemented. Fixture asserts current Panel/Body/tracked/semantic/prepaint positions, ranges, software pixels immediately inside/outside top/bottom and callbacks once. This remains synthetic numerical content; current-font wrapping and component wheel/touch/action/lifecycle proof are separate required gates. Runtime: actual production source and generated distribution both PASS, ten placement transitions plus the unchanged28 source rows/contracts in each target. Final session23912 compiled four steps (two fixture TUs/two links), strict C11 O3 Wall/Wextra/Wpedantic/Werror, nice19 CPU0 single job in the reused builddir. Private-Xvfb wrapper source/distribution2/2PASS0.29s. No Core TU was rebuilt. The first attempted run rejected a parent-attached absolute Mount without a parent before any geometry oracle; changing the TEST fixture to the specified root-attached portal fixed that API misuse. No source oracle or production algorithm was altered to obtain passing positions. ```sh cmake --build "$BUILD" --target test_dialog_flex_regions test_dialog_flex_regions_distribution -j1 python scripts/test_local.py --build-dir "$BUILD" -R '^dialog_flex_regions_(native|distribution)$' -j1 -V ``` No CMake/public API/production mutation, engine execution or new build directory. The source-compatible placement tree is now demonstrated for this admitted synthetic-content matrix, not a completed Dialog component or font/raster claim. Canonical skill freshness and offline reference authority are checked separately. ## Source minimum beyond a small viewport Separate `small_viewport.rs` uses the exact existing verified Taffy0.13.0 rlib; original28-row main/CSV/receipt remain byte-identical. Actual warning-clean rustc session85403, edition2021/O1/debug0/codegen1, produced four rows: min96 wins max48 for body20 and body900; min96 wins max8 for empty Body; ordinary max568 also yields96 for short Body. `small-viewport.csv` is captured actual output; its separate receipt includes driver, old engine receipt, rlib, binary and CSV hashes/features/toolchain. Added binary571296 bytes, existing reference cache now9.5MiB, no engine rebuild/fetch/new dependency or buildtree. Source CSS/Taffy accepts min96>raw max48/8 and gives the minimum precedence. Core's public record deliberately rejects min>max. The component must normalize its EFFECTIVE Core maximum to max(source minimum, source constrained maximum), retaining source minimum96; it must not lower the minimum or reject an otherwise ordinary small viewport. This is typed source-style normalization before strict Core admission, not a relaxation of Core validation or a new layout solver. Three additional actual CUI source/distribution placement rows pass: viewport 180x80, Body20/900, effective Panel96, top16; viewport180x40, empty Body, effective Panel96, top16. The same GROW spacer collapses0 when Panel exceeds usable48/8. Current bounds, semantic/prepaint heights/top and once-only callback remain96/16; long-body software pixels clip at the host bottom. Ordinary Panel and Footer overflow policy is retained; no whole-Outer fallback appears. Session23510 strict five steps and private-Xvfb source/distribution2/2PASS0.30s. Besides two fixture TUs/two links, Ninja correctly rebuilt the touched generated Core distribution probe once after canonical selective regeneration. No source Core algorithm or public API was changed. The existing target now checks13 placement transitions plus its original28 source rows/contracts. Offline receipt and engine authority checks7/7PASS. Component default normalization and real font/input/lifecycle validation remain subsequent production work. --- ## Table/Color lifetime counterexamples and narrow candidate plan Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/DIALOG_TABLE_COLOR_CANCEL_PROOF.md # Table/Color lifetime counterexamples and narrow candidate plan Unpublished test proof and source-only reset proposal. No production reducer, Core or public API change. The existing 38-case proof and its frozen no-helper traces stay preserved. Compiler was released after this bounded six-case batch. ## Actual captured paths Session 41096: strict C11/O3/Wall/Wextra/Wpedantic/Werror one fixture TU/link passed, CPU 1 / nice 19 against existing objects/archives; private-Xvfb six diagnostics yielded five strict failures and one success (CTest exit 8, 0.77 s). Initial Core capture and reducer pending-state assertions all passed; no flags were manually seeded. - Table resize: stale MOVEUP changed width100→138 and emitted width observer1. - Table reorder: stale MOVEUP changed caller columns[1,2]→[2,1], move observer1. - Table idle: no new samples, width100 unchanged, resizing column1 remained armed. - Color drag: post-DOWN RGB204/255/0 became204/0/255 from stale MOVEUP. - Color idle: same post-DOWN color retained, but dragging bit1 remained armed. - Existing typed Slider path passed: explicit helper caused one CAPTURE_LOST with no input/metadata flags, then genuine new gesture BEGIN/COMMIT succeeded. No typed reducer change is needed for this proved path; other permutations remain separate coverage, not a universal inference. The [canonical receipt](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/validation/dialog-retained-consumer-counterexamples.json) records the fixture and log hashes. Worker checkpoint `b8e7075a` additionally records source/object/archive hashes and the full first log. Earlier failures are not rewritten as passing checks. ## Exact proposed test-only Table reset In a copied `cui_table_reduce_common`, compute the existing explicit current-scope marker once after argument/selection validation and existing disabled/loading clear, before old selection/hash/row/column normalization and event reduction. Only when true, clear: ``` s->resizing = 0; s->dragging = 0; s->drag_active = false; s->scrollbar.dragging_x = s->scrollbar.dragging_y = false; ``` Do not modify resize_x/resize_width/drag_x, model widths/order, selection, sort, cursor, scroll offsets, viewport/load fields or observer registrations. New real DOWN overwrites the old scalar origins through existing code. Existing normal model/selection normalization still occurs in its old order; lifetime reset does not create a new rollback boundary. Inside the old raw loop, keep global CANCEL cleanup in its original position; then skip a consumed sample only when marker=true, before resize/reorder/selection operations and any resulting observer. No fake width/move/completion/selection callback. Already delivered model operations and copied observer facts remain applied. When marker=false, ordinary consumed semantics and all callback timing remain byte-for-byte source-equivalent statements to frozen original reduction. ## Exact proposed test-only Color reset After existing initialization/external-color synchronization and root interaction, before building local pressed[7] or submitting part interactions, read marker; when true set only `s->dragging = 0`. Do not restore HSV/color/last_color or clear initialization. Existing Core capture has already been canceled explicitly. Keep existing global CANCEL local pressed/bit cleanup first in the raw loop; then skip consumed samples only when marker=true, before palette activation or pointer/key mutation. Preserve final per-part semantics, rebuilding dragging, last_color, bool changed and invalidation in their existing order. No new callback or fake change/invalidation is emitted merely for ending a pending press. A color change delivered before parent reset stays the comparison baseline, not initial red. No readonly/disabled precedence change. ## Compatibility and next proof Both candidates are exact checked copies inside the existing builddir, no public field/symbol/record/ABI growth, no allocation or event replay and no dispatcher change. No-helper code paths retain existing ordinary consumption behavior. Table/Color callbacks and owned storage retain their existing lifetime contract. Before publication: keep the five failures, make the copied candidate pass with fresh DOWN success; test mouse/touch and idle, and preserve earlier width/order/ color mutations plus existing callback counts across reset. Freeze exact original Table/Color bytes and run independent fieldwise no-helper traces across ordinary consumption, keys, CANCEL, disabled/readonly/loading options and successful width/ move observer ordering. No context/pointer/padding memcmp. Rerun the 38 prior gates. Sheet/Chrome/text remain separately unproved; TEXT/composition selection is not broadened here. Root review remains required before any production transfer. --- ## Disclosure applied event proposal Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/DISCLOSURE_EVENTS_SLICE.md # Disclosure applied event proposal Design-only audit at `52b10b90`. No proposed facade below exists. Keep existing Accordion/Collapsible APIs and all 78 manifest entries; no parity promotion. ## Actual contract and nonuniform results [`cui_disclosure.h`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_disclosure.h) gives callers ownership of expanded bool storage, item arrays and optional stable per-panel motion arrays. Item and descendant IDs must be unique, nonzero and stable. Header and panel callbacks render arbitrary UI; they are not change handlers. No current typed expanded-state observer exists. [`cui_base_collapsible`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_disclosure.c) registers a button with expanded/controls semantics, processes matching activations by toggling `*open`, then updates semantics. Its bool means a toggle occurred, not final inequality: two activations may return true with unchanged final state. `cui_base_accordion` registers all triggers, then handles activation/navigation. Opening a closed item toggles it; closing an open item requires collapsible=true. Opening with multiple=false first clears **every** open slot, including disabled siblings, then opens the chosen slot. Thus disabled means that item's direct input is suppressed; it does not guarantee its expanded value cannot be closed by single-open policy. Multiple=true leaves siblings untouched. The reducer does not normalize arbitrary preexisting multi-open arrays on idle. Up/Down/Home/End move focus among enabled triggers without changing expanded state. It updates all trigger semantics at the end and returns whether any accepted toggle occurred. The outer bool cannot identify changed panels, multiplicity, input or final delta. [`cui_collapsible_ex` and `cui_accordion`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_disclosure.c) call Base once, then render headers/panels with the resulting bools. The simple `cui_collapsible` delegates to `_ex`. Without motion, closed panels are omitted. With motion, callbacks continue during exit; closed content is inert, and progress zero uses layout-only measurement. Motion measured bounds are written at end_frame, so storage must outlive submission. Progress/velocity, initial/reduced-motion snaps and panel measurement are presentation, not applied expanded CHANGE or lifecycle completion. Omission does not execute cleanup or cancel retained measurement work. Existing evidence: [`test_disclosure.c`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_disclosure.c), notably `test_custom_disclosure_headers`, `test_disclosure_box_overrides`, `test_measured_reveal`, `test_accordion_reveal_storage`, `test_configured_disclosure_springs`, and main's single/multiple/collapsible, disabled, keyboard-focus and panel-count assertions. These tests prove old behavior, not new dispatch. ## SUPERSEDED: initial aggregate workspace option (comparison only) Start with aggregate final-delta notifications. Use a new `cui_disclosure_events.h` including the existing disclosure and metadata headers: ```c typedef struct { cui_component_event_metadata event; cui_id item; size_t item_index; /* Model index, NOT a frame event index. */ bool previous, expanded; } cui_disclosure_change; typedef void (*cui_disclosure_change_fn)(void *, const cui_disclosure_change *); typedef struct { cui_disclosure_change_fn on_change; void *user; } cui_disclosure_handler; typedef struct { bool changed; size_t change_count; } cui_disclosure_event_result; ``` `changed` preserves the exact old bool. Counts are actual callback invocations; missing observer still edits and yields zero count. No rejection/REQUEST/COMMIT or animation-completion contract is added. Event target is the compound identity; item is the affected trigger, not a fabricated activating cause. Metadata is CHANGE, UNKNOWN source, proven nonzero active frame with HAS_FRAME only. Payloads are pointer-free/copyable, with no input index/activation or strings. 1. **Collapsible, independently first.** Proposed `cui_base_collapsible_events(ui,id,label,open,disabled,handler)` and `cui_collapsible_events(ui,id,theme,label,open,options,panel,panel_user,handler)`. The latter mirrors `_ex`, not the convenience bool-disabled signature. Return the new result. Capture one bool before Base, invoke it once, finalize then notify zero/one on final inequality. Item/target=id and item_index=0. Styled uses a narrow private common implementation at its existing Base seam, before render callbacks/panel; legacy path unchanged. Two toggles can leave legacy changed=true with callback count zero. No additional persistent state required. 2. **Accordion, separate review because snapshot ownership matters.** Propose a caller-provided temporary snapshot descriptor, avoiding hidden allocation or a new arbitrary family-size cap: ```c typedef struct { bool *before; size_t capacity; } cui_disclosure_event_workspace; cui_disclosure_event_result cui_base_accordion_events( cui_context *, cui_id target, const cui_disclosure_item *, size_t count, bool *open, cui_accordion_options, cui_disclosure_event_workspace, cui_disclosure_handler); cui_disclosure_event_result cui_accordion_events( cui_context *, cui_id container, const cui_theme *, const cui_disclosure_item *, size_t count, bool *open, cui_accordion_options, cui_disclosure_panel_fn, void *panel_user, cui_disclosure_event_workspace, cui_disclosure_handler); ``` For an installed observer and nonzero count, workspace must have capacity>=count, be writable and disjoint from open/items/state/resources. Copy bool values before one Base call; afterward dispatch once per final changed slot, in **model index order**, after all group semantics are finalized and before Styled rendering. Single-open side-effect closes are included even for disabled siblings. This is not chronological input order. Net-zero slots do not notify, and one activation can yield several panel callbacks. No handler needs no snapshot/workspace; unused user/workspace is ignored. Do not store workspace or borrowed payload pointers. Required pointers/nonzero compound target and installed-handler workspace capacity must be admitted before mutation; invalid admission has no callbacks or writes. Legacy empty-array/admission behavior must remain intact in old functions. This workspace is a real API tradeoff requiring integrator acceptance, not an implicit authorization to allocate. An alternative per-transition hook inside the Base assignment loops avoids whole-array snapshots but changes multiplicity and callback timing: a listener may see intermediate group state, and automatic sibling closes need distinct item/cause identity. It requires deliberate reducer refactoring and evidence rules. A whole-call wrapper without any snapshot cannot recover the previous bool for arbitrary count; do not fake it from final state or the old bool. Do not choose a fixed small array and silently truncate notifications. ## Policy, routing and lifetime constraints Keep disabled/direct-input, single-open side effects, custom header controls, roving focus, controls IDs and input routing unchanged. Inert parent routing must remain Core-owned. Layout-only/disabled/passive maintenance may still run, but new observers should require active painted work, proven frame and global enabled state. Do not filter a disabled sibling's actual policy-driven close just because its own direct input was disabled. No readonly option exists, and no new propagation/consumption guarantee is implied by adding observers. Accessibility facts may only come from actual routed Core activation; aggregate events do not manufacture an activation snapshot. Caller must preserve arrays, bools, styles, motion slots, measured bounds, header/panel/observer users and context. Observer must not mutate/free/rebind these resources or recursively submit UI. Render callbacks retain old order; under the new facade they must not mutate the active model or snapshot while rendering. Unrelated application flags may change; defer omission/removal/reorder/teardown until outer return plus frame/render consumption, and honor motion's end_frame storage requirement. Reading results does not dispatch. Existing render callbacks are not transformed into change callbacks and closing animation is not a late expanded-state notification. ## Meaningful verification and binding omissions Use paired old/new contexts and real queued pointer/key actions. Compare expanded arrays, exact bool result, focus, semantics, header/panel ordering, draw commands and retained motion/measurement state. Test two toggles/net-zero; multiple final changes; single-open sibling close including disabled-open sibling; collapsible false rejection; multiple=true preservation; navigation-only silence; custom interactive header children; consumed/inert/modal/layout/disabled paths; existing invalid multi-open model unchanged on idle; missing handler edits; copied payload through later frames/destruction; callback-before-panel order and deferred omission. Accordion additionally needs exact workspace capacity, no-handler ignored workspace, disjoint-buffer preconditions and invalid admission atomicity. Verify reduced-motion and exit-panel rendering do not add notifications or change callback counts. Retain the existing Disclosure suite and strict C11/C++ header checks; native tests use private display and browser fixtures headless once implementation is authorized. C facades would not expose Python/JS/TS/Go/Rust typed disclosure events. Their queued notifications need a separate schema/wrapper slice with full stable IDs, typed expanded state, bounded ownership and exception containment; queued notifications cannot reject past writes. See [binding audit](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_BINDINGS.md). This checkpoint ran no builds and changes no production source, manifests or ledgers. ## Revised preferred slice: per-transition reducer hooks This amendment supersedes the aggregate/workspace recommendation above. Actual write sites are narrow and available in `src/base/cui_disclosure.c`; neither family needs caller snapshots, allocation, a command queue, nor a new dispatch architecture. Keep the typed change/handler/result declarations above, but define `change_count` as the number of **actual applied bool-transition callbacks**, with a saturating `count_overflow` flag added to the result. `changed` remains the exact legacy bool. The same entrypoint names are proposed, with **no workspace argument**: ```c typedef struct { bool changed; size_t change_count; bool count_overflow; } cui_disclosure_event_result; cui_disclosure_event_result cui_base_collapsible_events( cui_context *, cui_id, cui_str label, bool *open, bool disabled, cui_disclosure_handler); cui_disclosure_event_result cui_collapsible_events( cui_context *, cui_id, const cui_theme *, cui_str label, bool *open, cui_collapsible_options, cui_disclosure_panel_fn, void *panel_user, cui_disclosure_handler); cui_disclosure_event_result cui_base_accordion_events( cui_context *, cui_id target, const cui_disclosure_item *, size_t count, bool *open, cui_accordion_options, cui_disclosure_handler); cui_disclosure_event_result cui_accordion_events( cui_context *, cui_id container, const cui_theme *, const cui_disclosure_item *, size_t count, bool *open, cui_accordion_options, cui_disclosure_panel_fn, void *panel_user, cui_disclosure_handler); ``` ### Exact assignment and notification sequence Refactor each existing Base reducer into a private common implementation with an optional dispatcher/result sink. Legacy functions pass NULL and preserve the old statements/order, admission, semantics, routing, bool result and callback-free behavior. Styled private common implementations choose the new Base entry at the existing seam; do not wrap the old aggregate bool or reduce twice. Collapsible's existing matching-activation loop executes `*open = !*open`, then sets its local changed=true. Capture previous, perform that write and old bookkeeping, then notify immediately, before the next input and before final semantic updates. Two accepted toggles therefore emit true→false and false→true (or the inverse), even if final state equals entry state. Missing handler never changes reduction. Accordion processes inputs in existing event-loop order. When the current cursor is eligible and `!open[cursor] || collapsible`: 1. Compute `next_open = !open[cursor]` as today. 2. If next_open and !multiple, visit j=0..count-1 exactly as today. For each `open[j] = false`, capture its preceding bool, do the write, and notify only if it was true. Already-false assignments stay silent. This includes disabled siblings, because the existing single-open policy clears them too. 3. Perform the existing `open[cursor] = next_open`, set changed=true as today, and notify for its actual bool transition. If closing a collapsible open item, no sibling reset occurs. With multiple=true, only this final assignment occurs. 4. Continue the existing keyboard focus logic and subsequent events, then execute the original final group semantic update loop without moving it earlier. On opening, the selected cursor was false, so its reset-to-false assignment is silent and its later false→true transition emits once. Opening another item can emit several true→false siblings in model order, followed by the opened item's false→true. There is no duplicate observer for an assignment that leaves a bool equal. Do not suppress a real sibling close merely because that sibling is disabled. Do not normalize arbitrary idle multi-open input or create events for animation. ### Metadata and timing honesty At the accepted activation branch, before the **first** affected write/callback, copy `cui_event_activation_snapshot` when available and initialize shared metadata with `cui_component_event_from_activation`. Both reducers already call `cui_interact` to register Button semantics before their activation loop, so genuine accepted activation evidence must not deliberately be discarded. Override only `metadata.target` with the explicit compound ID; retain the original snapshot's `activation.target` unchanged. Payload item/item_index identifies the affected bool slot. In particular, keyboard cursor redirection and automatic sibling closure do not turn the originating activation into an activation of that affected item. If an accepted snapshot is unavailable, freeze only the actual local frame/index and known event-type source: pointer-up POINTER, key-down/up KEYBOARD, accessibility-action ACCESSIBILITY, otherwise UNKNOWN. Do not fabricate activation fields or infer a physical device/timestamp. Every transition caused by the same activation shares this frozen original evidence, including automatic sibling closes. An input index is causal identity, not an activation of the affected sibling. Never register semantics early to manufacture evidence. Observe only a nonzero active frame and ordinary painted, globally enabled submission. Core's inert activation/target suppression remains authoritative. If metadata cannot be proven, preserve legacy writes but emit no fabricated callback. Capture evidence once before the closure loop; observers must not mutate active dispatch/input state. Existing semantics are finalized at their original later points, not before notifications. Callbacks are synchronous **immediately after each applied bool write**, not after whole-event/group semantic finalization. They can read an intermediate group: while opening in single mode, some siblings may have closed while later ones are still open; immediately before the final open there may be no open panel. Existing invalid multi-open input remains visible until its existing reset loop finishes. No exactly-one-open invariant is promised inside the callback. `open` has the newly written value, but semantic expanded flags, motion and Styled panels still reflect their original later update points. Do not read them as already-finalized state. Do not reposition semantics, render callbacks or spring stepping to conceal this. Observer callbacks must not mutate, rebind, free or destroy the active expanded array, items, context, states, style/motion arrays or callback resources, consume input, or reenter UI. This includes owner writes to a sibling bool: these are post-mutation notifications, not owner-rejectable requests. Unrelated application flags may change, with omission/removal/reorder/teardown deferred until outer return plus frame/render consumption. No new runtime mutation guard is implied. Legacy render/header/panel callback order and ownership remain unchanged; new observer rules do not authorize reordering their arbitrary child UI. The observer is not a render slot and cannot submit CUI. Retained measurement still survives end_frame. ### Alternatives, risks and proof obligations Immediate hooks are preferred because they preserve every actual transition with constant auxiliary memory and no externally owned snapshot workspace. Their cost is explicit intermediate-state/stale-semantics visibility and more callbacks than an aggregate result suggests. Consumers needing only final state should coalesce copied payloads in unrelated application storage and apply effects after submission; that does not change native observer timing. Dispatching all closures only after the opening write would preserve a stronger within-event model invariant, but storing arbitrary changed siblings/previous bools requires bounded caller/frame storage or a new count cap; the existing model has no such bound. Reconstructing the old true set from the now-false array loses data. A two-pass notification scan cannot recover it without storage. Do not introduce hidden allocation, truncate callbacks or reorder writes for convenience. The initial aggregate-workspace option is valid only as a separately chosen API and loses repeated/net-zero transition information; it is not the preferred implementation. New tests must assert exact ordered transition tuples, not only final state: Collapsible double toggle gives two callbacks with unchanged final state; Accordion single-open closes prior true slots in index order then opens cursor, including a disabled-open sibling; multiple=true never closes siblings; collapsible=false open activation produces none. Verify every callback's current slot value and explicitly sample allowed intermediate arrays/stale semantics. Confirm metadata is frozen once per cause, source/index and original copied activation same for sibling closes, HAS_ACTIVATION when genuine snapshots exist, fallback only when unavailable, and repeated same-frame inputs each retain their own index. Missing observers keep old results and writes, counts are actual invocations, unused user ignored, saturation is safe. Pair old/new contexts for state/focus/semantics/draw/motion/render-callback equivalence after reduction; prove no early semantics, no double input, and unchanged custom header child routing. Cover pointer/key/accessibility where genuinely supported, consumed/inert/layout/disabled suppression without altering old maintenance, copy-after-frame/destruction and flags-driven deferred omission. Run strict C11/C++ headers plus existing Disclosure tests via the private wrapper after approval. This remains a signed design amendment only; no production implementation or tests were added or run, and no foreign binding/lifecycle/parity claim follows. ### Collapsible implementation checkpoint Base and Styled Collapsible now use the approved immediate-write seam. Accepted activation snapshots are copied before writes; legacy entry points remain available. Accordion production remains pending its independent implementation/test commit. ### Accordion implementation checkpoint The preferred per-transition seam now covers Base and Styled Accordion. Each single-open sibling write is observed immediately in its original model order, then the chosen write; already-equal assignments remain silent. Genuine activation snapshots preserve their originating target even across keyboard cursor redirection. No caller workspace, allocation, event cap or legacy state-layout change was added. Tests distinguish initial Button checked values from not-yet-finalized expanded details, rather than promising previous-frame expanded details inside callbacks. --- ## DropdownButton metadata forwarding checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/DROPDOWN_BUTTON_METADATA.md # DropdownButton metadata forwarding checkpoint 2026-10-22. Design only at this commit; CUI base `5a0d1165`, frozen source `87d10ae5e1299d1be18670a37570c5402f952e34` (v0.7.1). All 78 entries remain. | Contract | Exact evidence and present gap | | --- | --- | | Inner action retains Button metadata | `crates/component/src/button/dropdown_button.rs:70-80,167-189` moves the supplied Button and changes only explicit outer properties; its name/tab/toggled settings survive. CUI's legacy options have no equivalent forwarding fields. | | Explicit accessible name, including empty | `button/button.rs:391-394,737-740,805-808`: an optional explicit name wins over the visible label. CUI currently passes the same action name into Base and visible paint; a custom body does not change that name. | | Signed order and independent eligibility | `button.rs:230-231,281-282,472-481,817-818`: default index 0, tab stop true; an explicit signed index does not replace tab-stop policy. Existing CUI Button uses `custom_tab_index`, `tab_index`, `skip_tab` with Core setters; `test_button_tab_order_source.c` covers negative ordered indices independently of eligibility. Split controls currently expose neither. | | Toggle is metadata, not selected paint | `button.rs:490-498,809-815` forwards optional true/false `aria_toggled`; source selected does not imply toggled. CUI Button currently maps `toggle_semantics && toggled` to semantic checked/value, independently of selected. Dropdown does not expose that convention. | | Genuine end-to-end toggle gap | `cui_semantic` has checked/value but no optional button-toggled presence. `backends/accesskit/cui_accessibility.c:183-186` emits Toggled only for check/radio/switch roles, not Button. Forwarding existing checked/value cannot establish source `Some(false)` versus `None`, or end-to-end pressed-button AT output. No role substitution or Core/adapter change is proposed here. | | Trigger | Source `dropdown_button.rs:193-219` constructs a new internal Button with default tab/name/toggle properties. Independent trigger name/tab overrides are a useful explicit CUI extension, not inherited action properties. Existing CUI menu_name remains its legacy default. | ## Bounded additive contract Proposed independent `cui_dropdown_button_metadata.h`, leaving legacy option/state layouts unchanged: ```c typedef struct { bool custom_name; cui_str name; bool custom_tab_index; int tab_index; bool skip_tab; } cui_dropdown_button_part_metadata; typedef struct { cui_dropdown_button_part_metadata action, trigger; bool toggle_semantics, toggled; /* action checked/value convention only */ } cui_dropdown_button_metadata; ``` Add `cui_dropdown_button_with_metadata_ex` and `cui_dropdown_button_with_metadata_events`: existing Styled argument sequence, then optional `const struct cui_dropdown_button_styles *`, optional metadata pointer, and (for events) the existing handler record. NULL/zero metadata keeps the exact legacy registration, semantic values, layout, paint and callback path; NULL styles independently keeps legacy paint. Existing functions remain unchanged. The metadata header includes only Choice and forward-declares the style tag; the existing style typedef gains that named tag without changing its fields or layout. This avoids a Base-to-Components include dependency and adds no ABI size. Names are independent of the visible label/custom body. `custom_name=true` with zero-length name explicitly clears the accessible name, including NULL+0. Active custom names require valid UTF-8 with no embedded NUL, using the existing checked string validator. Nonempty NULL and malformed UTF-8 reject before state, handlers, reduction or paint. Unmasked name/index values are ignored. Validate only visible halves: hidden-half records are ignored and need no string lifetime. All native `int` indices are accepted, including negative values; this is the existing portable CUI ordering range, not an arbitrary source `isize` range. `skip_tab` independently removes the half from Tab navigation; pointer and accessibility activation remain governed by existing disabled/loading policies. Selected, expanded, checked/value and busy stay separate. Action checked/value is `toggle_semantics && toggled` / 1-or-0, exactly the existing Button convention; it does not toggle the application model and does not close the AT presence gap. Trigger checked/value remains its existing false/0; menu expanded/controls and loading description/busy must survive. ## Ordering, private seams and lifetime Copy the two descriptors at submission entry; names remain borrowed for the submission, and Core copies semantic name bytes into its frame arena. No new retained owner, observer, callback contract or dispatcher is introduced. Preflight occurs before `state->drag_scroll` and existing Base reduction. Semantic name overrides enter the original registrations, while paint retains the original labels. Apply action tab/checked metadata immediately after its existing Button registration and loading details, before existing action-event enumeration. Apply trigger tab metadata immediately after its original popup trigger registration, before menu command callbacks or the closed-menu return. Thus existing handlers can inspect the current metadata without changing their order, multiplicity, accepted evidence, bool result or mutation privileges. This needs a narrow optional metadata parameter in the private Base Dropdown reducer and the shared private menu-trigger registration seam. Every existing menu/Choice caller passes NULL and retains its exact path; only the new Dropdown entry supplies the trigger record. A small private header shares the internal submission declaration; it adds no public Base entry or second reduction. Outer actions, menu handlers and custom body callbacks may mutate owner/options as before; copied descriptors prevent those mutations from changing this submission. Pointer/key/AT targeting and dynamic tab changes use existing Core previous-frame routing/focus-generation rules; no retroactive rerouting is added. ## Proof and integration - Independent legacy/zero draw, pixel and memberwise semantic oracle; unchanged action/menu result counts, callback order and body-once behavior. - Explicit named/empty/localized/custom-body labels; malformed/NULL/NUL inputs, omitted halves, borrowed-name copying and descriptor mutation in legacy handlers. - Real Tab/Shift-Tab with signed order and skip independently; pointer/touch, Enter/Space, accessibility activation, live disabled/loading, selected versus checked/value and open-menu focus restoration. Inspect metadata inside handlers. - Existing Choice/Dropdown/style regressions, strict C11 guide/C++ declarations, private Release wrapper, pinned WASI, standalone legacy/new/CUI_ALL definitions and runtime proofs, metadata human mirror and explicit foreign-builder omissions. - Register and regenerate SDK/dist/skill only for the bounded shipped API. No web, workflow, Editor, Button implementation, Core, AccessKit or role changes. Full source toggled presence/pressed-button AT output remains a separate required Core/adapter design, not a completed or permanently exempted feature. --- ## DropdownButton inherited Button refinement audit Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/DROPDOWN_BUTTON_REFINEMENT_AUDIT.md # DropdownButton inherited Button refinement audit Initial design checkpoint, 2026-10-22. CUI base `ef086a41`; frozen v0.7.1 source `87d10ae5e1299d1be18670a37570c5402f952e34`, verified in the local reference checkout. That checkpoint made no production edits, status promotion, generated changes or new dispatch design. All 78 entries remain. Its inspected tests and proposal are preserved below; the separate implementation evidence follows at the end. ## Exact source and coverage | Frozen source | CUI evidence / precise remaining scope | | --- | --- | | `crates/component/src/button/dropdown_button.rs:25-108,148-220` | Optional action/menu, outer variant/size precedence, selected union, action-only disabled/loading, corner anchor and joined borders exist in `include/cui/cui_choice.h:458-485`, `src/components/cui_choice.c:2360-2510`. Tests: `test_dropdown_inheritance_and_ghost_pair`, `test_dropdown_optional_halves`, `test_dropdown_anchor_corners`, `test_dropdown_inner_button_presentation` in `tests/unit/test_choice.c`. | | `dropdown_button.rs:117-120,171-177` | Outer `Styled` refinement belongs to the **container**, not automatically both Buttons. Current container is a fixed row/gap0 with no patch. This is a real bounded box-style gap; arbitrary Styled remains larger than the proposed paint subset. | | `dropdown_button.rs:179-220`; `button/button.rs:599-620,705-733,782-803` | Source retains the action Button's own instance/content refinements while overriding shared size/variant/corners/edges. Current split paint is independent (`cui_dropdown_button_box`, lines2246-2339), and cannot accept `cui_button_styles`. The existing Button facade (`include/cui/cui_button_styles.h`, `cui_components.c:426-474`) already defines a reusable masked paint vocabulary and caller-instance replay. | | `button.rs:505-517,1168-1185,1276-1307` | Source selected/open suppresses pointer layers; trigger menu-open uses selected paint, while ghost action uses held group surface. Current split does not pass `overlay.open` as trigger active/selected paint; selected Ghost can retain hover foreground, and pressed Ghost can retain hover foreground. Dark Ghost hover is full accent rather than half alpha; held/group background should be half of the **resolved hover** background (dark quarter accent), not always half accent. These are concrete source differences, not missing tests alone. | | `button.rs:1316-1359` | Disabled outlined handling has precedence across variants. Current split's special Ghost/Link/Text branch runs before outlined disabled handling. Colored disabled border uses `colors.border` instead of source semantic variant base color. Custom outline disabled background currently uses `.1*custom.color`; source normal outlined background then `.5` must be resolved from the source normal formula. Correction after tracing `theme/color.rs:228-280,1013-1038`: premultiplied mixing against transparent black/white preserves RGB and scales alpha. Current custom .2/.4/disabled .1 formulas are compatible apart from byte rounding; no color conversion is needed. Custom variant shadow (`button.rs:655-656,1089-1096`) is absent. These need source-differential expectations, including transparent-border themes, rather than copying existing assertions. | | `button.rs:371-480,805-818`; `dropdown_button.rs:70-79,179-195` | Action semantic name is already an explicit C call argument (custom content can differ); default visible label and that name cannot independently differ without a custom child. Signed tab index, tab-stop eligibility and toggled semantic metadata exist on current `cui_button_options`, but are not forwarded by DropdownButton options. Selection remains paint-only; current Base explicitly resets trigger checked to false. Source string accessibility identity and arbitrary role override are not equivalent to CUI's integer owner ID or existing Button subset. | | `button.rs:397-435,441-464,742-780,859-870` | Existing split has text leading/trailing/custom body, real caret SVG, stock spinner and delayed text tooltip. `test_dropdown_real_artwork` proves the spinner/caret, **not** general action typed artwork. Source compact/numeric sizing, rounding, font/icon overrides, icon-only action, custom loading icon, typed artwork, content-style, tooltip custom builder/keybinding hint and action hover callback are not fully forwarded. These remain distinct source-functional/content gaps; no catchall “metadata done” claim. | Existing coverage is substantial: `test_dropdown_button`, `test_dropdown_colored_outline`, `test_dropdown_presentation_variants`, `test_dropdown_configurable_palettes`, `test_dropdown_loading_subtree_opacity`, `test_dropdown_loading_keeps_content`, `test_dropdown_reference_metrics`, `test_dropdown_action_tooltip` and shared-size checks in `tests/unit/test_choice.c`. `tests/unit/test_dropdown_events.c` exercises pointer/touch/key/AT action metadata, multiplicity, missing handlers and loading suppression. It establishes an existing typed facade, which a style extension must reuse. It does not establish the missing Button style/metadata cases above. ## Smallest compatible next slice (proposed, not implemented) Use an independent additive record and `_refined`/`_events_refined` entries beside DropdownButton declarations; do not resize `cui_dropdown_button_options`. Include the existing Button styles header, rather than invent a second paint mask or callback signature. Proposed shape: ```c /* Proposed declarations only. */ typedef enum { CUI_DROPDOWN_PAINT_LEGACY, CUI_DROPDOWN_PAINT_BUTTON } cui_dropdown_paint_policy; typedef struct { cui_dropdown_paint_policy paint_policy; cui_button_styles action, trigger; cui_button_paint_patch container; } cui_dropdown_button_refinement; ``` `container` uses the existing paint-only masks: background/border color, foreground, radius/corners and opacity. Because the container has no text, its foreground bit should be **rejected**, not accepted ineffectively. Border width, geometry/gap/padding/clip remain inspection-only and unchanged; this first slice must not pretend to implement the source's arbitrary outer Styled geometry. The outer container still has no semantic/control role. Container paint is not an inherited text cascade into either half. Recommended compatibility policy: zero/NULL takes the exact existing split paint path. Explicit BUTTON selects source-correct built-in layers above even with no callbacks. LEGACY plus nonzero callbacks layers refinements over the legacy palette; it cannot be called complete source state-style parity. This explicit policy avoids silently changing old pixels when a caller adopts only metadata. An alternative is to correct old defaults directly as a separately reviewed bug fix. Root should choose that migration before production; both cannot preserve old pixels and simultaneously change the mismatching source formulas. Action refinements cover retained inner-Button customization. Independent trigger callbacks are an explicit CUI extension: the frozen builder creates that Button internally and does not expose a separate trigger-style setter. For each visible half, reuse `cui_button_styles`' phase vocabulary, pure borrowed callback, patch validity and instance-once captured replay contract. Normal, instance, eligible pointer layer, selected/open layer+instance replay, disabled layer+instance replay, loading fade, then eligible focus follow the documented Component ordering. Press suppresses hover; selected/open suppress both; loading suppresses pointer phases without pretending to be disabled paint. Action effective selected is outer OR inner selected; trigger additionally uses real `overlay.open`. Action menu-open is a ghost group-held surface, not fake selected/checked state. Snapshot ID is each real half ID. Hidden halves invoke no callbacks; old content callback still runs once in its original place. Implementation can remain entirely in DropdownButton's common renderer: retain the existing Base reduction, calculate the local half paint, apply the existing masked value vocabulary through a small Dropdown-specific adapter, then submit the existing layout/content tree. No second control, event loop or generic style dispatcher. Button's resolver is currently private; copying only the bounded patch application/phase adapter is preferable to changing Button internals within this ownership. If later deduplicated, extracting a value-only private helper needs explicit Button ownership and its own equivalence proof. Do **not** call `cui_button_styled_ex`: it would reduce events twice. Simply replacing each half with `cui_button_styled_paint` is also not a proven shortcut: its padding/label/caret/clip tree and ghost group-held behavior differ from the existing split tree. That path would need an independently reviewed layout and content migration, not an assertion that shared callback types imply equivalence. Unknown option policy/container mask rejects before `state->drag_scroll`, input, handlers or paint. Invalid callback output discards that whole paint patch, as Button already specifies; it does not undo an accepted activation. Functions, user and current/info/out records are synchronous borrowed values; callbacks must not call CUI, mutate owner/options, consume input or reenter submission. Descriptors are copied at entry; instance runs once per submitted visible half, its validated value is replayed without rerunning it. No retained attachment. Focus styling must explicitly use existing focus-visible/hide-focus-ring gates under BUTTON; current split colors every focused half, another legacy difference. ## Independently reviewable metadata followup Add an independent masked action/trigger metadata record, not an unrestricted `cui_button_options` pass-through. First useful fields: accessible-name override (valid UTF-8, explicit empty allowed), signed tab index, independent tab-stop eligibility and optional action toggled value. Reuse Core setters/old Button conventions without creating a new role, changing selected to checked, or clearing menu expanded/haspopup/busy/descriptions. Name override is passed to Base for semantics while the original label still paints. Metadata must be preflighted before Base; callbacks/accepted activation evidence remain unchanged. Dynamic focus policy must inherit existing Core timing rather than inventing rerouting. String accessibility-ID aliases and arbitrary source roles remain explicit gaps; CUI integer IDs are not a fabricated string identity facade. Broader input/hover or tooltip-builder lifecycle forwarding needs separate storage/lifetime review. ## Required proof before any coverage promotion - Independent pre-change legacy/zero draw, software-pixel and memberwise semantic oracle across legacy/shared sizes, variants, outlined/selected/disabled/loading, optional halves and custom body; preserve all accepted typed event counts/order. - Source formula matrix for light/dark Ghost hover/group-held/open, selected+ pressed+hover foreground suppression, open trigger versus held action, disabled outline/custom/transparent-border themes, loading fade and focus-visible gates. - Record callback trace and snapshot values: instance exactly once per visible half, press/hover suppression, selected/disabled replay, focus ordering, invalid patch discard, no geometry writes; actual software colors/radii/opacity and existing joined edges/caret/content bounds must match those resolved values. - Real pointer/touch/Enter/Space/AT and menu command queues through legacy and typed `_events_refined` entries: no duplicate dispatch, callback replacement and live disabled/loading mutation preserve current reducer behavior. Distinct handler.user versus style.user; no fabricated origin/count metadata. - Metadata followup: visible versus accessible labels, explicit empty names, signed order/skip eligibility, toggled versus selected/expanded/busy and popup focus restoration. Invalid descriptors do not consume queued events or mutate menu/output. Test borrowed descriptor snapshot and no retained callbacks. - Strict portable C11, C++ declarations/compiled guide, private Release wrapper, WASI and software pixels; browser demonstration follows canonical review. No build or native window was necessary for this read-only checkpoint. ## Final declaration checkpoint The additive contract is now in `include/cui/cui_dropdown_button_styles.h`. It avoids the Choice/Components include cycle. Explicit BUTTON selects source state formulas; two gates select Custom XS shadow; zero stays legacy. Metadata is separate. Source `Colorize::opacity` (`theme/color.rs:156-161`) clamps its multiplier to[0,1], so Secondary disabled .opacity(1.5) preserves alpha rather than increasing it. Tests must cover translucent colors and exact byte rounding. No Theme/Core ABI or new conversion dependency is required. ## Implemented style slice and evidence The declarations are implemented through the existing Dropdown common submission path. Base/events reduce once, descriptors copy before reduction, and legacy callbacks retain their mutation/timing behavior. The metadata proposal above is still unimplemented. At the initial implementation handoff, canonical registration, generated distributions, consumer skill export and browser demonstration remained separate integration work. The canonical followup below adds the build/export coverage; no full-family status is promoted. `tests/fixtures/dropdown_button_styles/legacy_box.h` freezes the pre-change `ef086a41` paint helper and complete submission/paint tree. The new test compares that oracle with NULL/zero descriptors across every variant, all four existing sizes and normal/selected/disabled/loading/outlined/omitted-action cases, using draw values, actual software pixels and memberwise semantic values. Additional tests verify independently calculated source colors (including translucent Secondary and distinct border palettes), instance replay/invalid patch discard, container rejection, real pointer/touch/Enter/Space/accessibility multiplicity, descriptor-copy behavior under legacy event-handler mutation, body-once and trigger-open distinction. Actual software pixels exercise hover/selection and the two shadow gates. Text shaping and source theme-token equality are not claimed by these software tests. Frozen `upstream-pre = 0.3.8` runtime evidence (`src/elements/div.rs:3438-3473,3520-3523`) applies group-hover before own hover/active. Thus an action's own pointer state overrides its group-held background; the trigger does not inherit that group. Verified in the private fixture: strict Release native wrapper 3/3 (new styles, existing Choice and Dropdown events), ASan+UBSan wrapper 1/1, pinned Zig 0.16.0 / wasmtime 49.0.0 WASI 1/1, strict compiled C11 guide and C++ header, and actual `python scripts/format.py --check` with clang-format 23.1.2. All builds live under `/home/matteo/.cache/cui-validation/dropdown-button-styles{,-asan,-wasi}`; no desktop window, dependency install or full-suite rebuild was used. ## Canonical integration followup The independent module delegates its implementation macro to Choice. Choice includes the new declarations before embedding its renderer, so the legacy implementation entry remains self-contained with respect to the new API. Object-definition tests prove both entry points define the two functions before any archive participates. CUI_ALL and both standalone entries run real rendering and accessibility activation assertions. C++ declarations and the exact guide snippet are compiled; guide targets are optional in packaged trees without docs. Canonical Release wrapper checks passed 7/7 (styles, Choice/events, three runtime distribution entries, and standalone/package contract); pinned WASI passed 4/4 (styles plus the same three distribution entries). Usage metadata tests passed 6/6; generated SDK/distribution freshness and pinned formatting passed. Source metadata and its human mirror retain all 78 entries, explicitly omit foreign style facades, and preserve the remaining metadata/style-token limitations. Native artifacts are under `/home/matteo/.cache/cui-validation/dropdown-canonical` and WASI artifacts under the sibling `dropdown-canonical-wasi` directory. Browser/gallery integration is owned separately and not changed by this followup. --- ## Owned element backgrounds: semantic and transport checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/ELEMENT_BACKGROUNDS.md # Owned element backgrounds: semantic and transport checkpoint Design only, 2026-10-31, integration `f724017c`; no API below exists or is approved for production. Preserve all 78 entries and existing box/style/draw ABI. Button's bounded shadow facade and Slider's Aurora thumb gradient motivate a shared Core paint primitive, followed by explicit component/part/theme and binding ownership. This is a semantic-background proposal, not a claim of complete CSS/source parity. ## Evidence and reusable mechanisms Original upstream kit [87d10ae5](https://github.com/longbridge/gpui-kit/tree/87d10ae5e1299d1be18670a37570c5402f952e34) pins `upstream-pre=0.3.8`. Its [color representation](https://docs.rs/crate/gpui-pre/0.3.8/source/src/color.rs) has solid/two-stop-linear plus slash/checkerboard. The exact published [WGPU shader](https://docs.rs/crate/gpui-pre-wgpu/0.3.8/source/src/shaders.wgsl) prepares linear colors from Hsla, interpolates RGB/Lab and alpha independently, and rescales the short axis before dominant-axis projection. Its extracted-source SHA256 is `1d91f2c8a1958a241f1b659a4137c160592c8076b9be09049db4c9fb9a344529`. Pinned `crates/component/src/slider.rs` consumes a Background-valued thumb token; `theme/theme_color.rs` keeps that brush separate from its representative Hsla. `theme/schema.rs:test_aurora_theme_parses_gradient_backgrounds` verifies the `themes/aurora.json` brushes; flattening them to representative colors loses paint. | Existing CUI authority | Actual capability / limitation | | --- | --- | | `include/cui/cui_plot_view.h`, `src/components/cui_plot.c`, `docs/PLOT_MODEL.md` | Source projection, reversed/equal stops, sRGB/Oklab, patterns; separate byte and source-Hsla→linear-premultiplied samplers. Reuse audited equations/tests; Core must not depend on components/Plot types. | | `cui_effect_linear_gradient`, `docs/BACKGROUNDS.md` | Caller RGBA8 raster, pixel-center diagonal, angle 0 right, premultiplied encoded-sRGB interpolation. Not source/CSS geometry or Oklab. | | `cui_text_paint`, `docs/TEXT_GRADIENT.md` | Copied 2..8 stops; explicit endpoints, premultiplied encoded-sRGB glyph paint. Not rectangular background; prepaint text-gradient emission is rejected. | | `cui_paint_bitmap`, bitmap underlay, prepaint | Borrowed pixels through renderer completion; underlay is above background/inset shadows, prepaint above that. Neither replaces the background at its proper paint position. | | `cui_mesh_paint`, `backends/software/cui_mesh.h` | Borrowed coverage vertices, one flat premultiplied linear color. No per-vertex/background gradient. | | Core resources / frame storage | Existing keyed resource size/callback identity, collection and next-begin lifetimes; no gradient cache, device scale or arbitrary retained resource graph may be assumed. | All adapters currently dispatch RECT/IMAGE/MESH, not a semantic rectangle brush: software (`cui_software.c`) rasterizes; SDL_Renderer (`cui_sdl3.c`) has bounded bitmap/shape paths; SDL_GPU (`cui_sdl_gpu.c`) and Sokol (`cui_sokol.c`) use private quad uniforms/textures; Canvas (`web/gallery.js`) reads explicit WASM fields and uses roundRect/image paths. `cui_bitmap.h` caches source pointer/revision/crop/ shape at logical ceil dimensions; `cui_shadow.h` has its OWN 64-slot/32MiB cache. Neither is an approved background cache or a DPI-correct gradient implementation. ## Proposed value contract and API sketch ```c typedef enum { CUI_BACKGROUND_SOLID, CUI_BACKGROUND_LINEAR } cui_background_kind; typedef enum { CUI_BACKGROUND_SRGB, CUI_BACKGROUND_OKLAB } cui_background_space; typedef enum { CUI_BACKGROUND_CSS, CUI_BACKGROUND_GPUI_038 } cui_background_model; typedef struct { float r, g, b, a; } cui_background_color; /* straight LINEAR RGB */ typedef struct { float position; cui_background_color color; } cui_background_stop; typedef struct { cui_background_kind kind; cui_background_space space; cui_background_model model; cui_background_color solid; float angle_degrees; cui_background_stop stops[2]; /* fixed owned values, no count or pointers */ } cui_background; cui_background_color cui_background_color_from_srgba8(cui_color); bool cui_background_color_from_source_hsla(float h, float s, float l, float a, cui_background_color *out); bool cui_background_valid(const cui_background *); bool cui_set_background(cui_context *, const cui_background *); /* open box */ bool cui_element_set_background(cui_context *, cui_id, const cui_background *); /* NEW transport decision; field names and entry points require Core review. */ typedef struct { size_t command_index; cui_background paint; float opacity; } cui_background_binding; typedef struct { cui_draw_list commands; const cui_background_binding *backgrounds; size_t background_count; } cui_background_draw_list; cui_background_draw_list cui_end_frame_backgrounds(cui_context *); ``` Colors are finite straight linear RGB/alpha in [0,1], preserving hidden RGB at alpha zero. The sRGBA8 constructor decodes RGB transfer; source-Hsla explicitly uses the pinned shader conversion, not CSS-HSL/byte reinterpretation. Interpolation space is mandatory policy, not a guessed Tailwind/browser default. No premultiplied `cui_linear_color` stop: it would erase transparent endpoint RGB needed by source. SOLID ignores inactive gradient fields; LINEAR validates both stops, known enums, finite angle [0,360] (360 aliases zero), and finite positions [0,1]. CSS requires ordered stops; upstream preserves reversed order. Equal stops select the second color at/after the boundary: a deterministic extension of source's undefined division. For logical border-box W,H>0 and center C, angle zero points up, 90 right. CSS uses d=(sin A,-cos A), L=abs(W*d.x)+abs(H*d.y), t=.5+dot(P-C,d)/L; upstream scales d.y by H/W when W>H, otherwise d.x by W/H, then uses t=.5+dot(P-C,d)/(length(d)*(abs(d.x)>abs(d.y)?W:H)). Both map t through the two stop positions and clamp; zero-sized boxes paint empty. CSS premultiplies components in the selected interpolation space, mixes with alpha, unpremultiplies (zero alpha gives zero RGB), then returns to linear RGB; upstream mixes straight components and alpha, THEN premultiplies the final fragment. These differences are intentional. CSS geometry/alpha references: [Images 3](https://www.w3.org/TR/2023/CRD-css-images-3-20231218/#linear-gradients), [Color 4](https://www.w3.org/TR/2026/CRD-css-color-4-20261029/#interpolation-alpha). Use standard Oklab matrices; retain computed out-of-gamut float RGB until explicit SDR output clamp/encode/round. That output policy is bounded CUI paint, not a full CSS gamut-mapping/HDR or GPU-f32 bit-identity claim. Quantize straight encoded RGB/alpha to RGBA8 once; apply inherited opacity with existing alpha truncation, then existing shape coverage, with no duplicate image opacity. Old Plot/effects/ text helpers retain their semantics; extract pure math without changing them. ## Composition, ownership and bounded failure Set copies the complete active value now; last successful assignment wins. NULL removes the override and restores the submitted box background; transparent SOLID explicitly suppresses it. No inheritance/list merging/pending-next-widget style. The open setter can address an anonymous current box; named setter uses existing current-frame owned-node/map/config guards, rejecting missing/previous-frame/ layout-only/ambiguous-folded IDs and measurement/prepaint/diagnostic mutation. Validation/capacity preflight publishes no partial replacement; preserve other shadow/outline/mesh/underlay/prepaint owners on reset. No default custom paint is attached to unstyled nodes. Geometry/input/semantics/callback timing remain intact. Replace the original fill exactly between DROP and INSET, retain existing outline/ underlay/content/border order; never paint a gradient over an existing fill. Anchor to full current border-box bounds before clips, not visible/previous bounds. Corners use existing CUI individual clamp to min(W,H)/2, not CSS overlap scaling; ancestor clips/portals/layers and existing opacity apply once after interpolation. Keep each adapter's existing RECT coverage policy; cross-adapter edge AA is not currently byte-identical. No new CSS group-opacity/offscreen compositing claim. Proposed hard ceilings: <=4096 styled boxes and existing max_elements/frame_bytes; no persistent context raster allocation. Raster fallback <=16384 per physical side, <=4M pixels per brush and <=8M total pixels/32MiB CPU per prepared frame; streamed uploads also obey a separate aggregate <=32MiB budget. These are NEW limits for review, not existing resource guarantees. Scale axes finite [1/65536,64], origin within +/-1e6; checked physical covering/inverse sampling preserves logical angle under DPI/nonuniform axis scale. Clip work without changing the anchor. Reject unsupported transforms, overflow, allocation/upload or aggregate budget failure explicitly; no flat-color fallback. Final conversion/preparation failure publishes an empty view and an error. Copied frame descriptors survive renderer completion until next begin_frame; no new in-flight-frame/thread lifetime is implied. ## Transport alternatives and approval gate 1. Caller-owned raster + existing IMAGE is usable today, with explicit size/revision/ lifetime management. It is NOT this owned semantic API: Core lacks device scale, and underlay/prepaint ordering is wrong for inset-shadow backgrounds. 2. Core-owned raster lowered to IMAGE avoids draw ABI changes but requires a NEW pixel owner/budget/DPI contract; logical-resolution raster is a quality compromise. 3. New draw kind/value payload is clean but enlarges public command stride and breaks old ABI/adapters/bindings; do not hide data in bitmap/mesh/text fields. 4. Recommend reviewing the sketched explicit sidecar view: old structs stay exact; Core records a transparent RECT placeholder at the original fill position and owned indexed brush/opacity entries (including originally transparent boxes). Reserve one fill slot per owner; validate unique in-range RECT indexes and clip balance before painting. Replacements reuse storage; old max_commands still bounds conversion. New render entry points replace placeholders. Legacy end_frame rejects outstanding overrides; old render APIs must never silently consume the sidecar's incomplete base list. The sidecar/renderer extension is a NEW ownership/transport protocol requiring approval BEFORE production, not an existing capability. It needs explicit new render entry points/capability negotiation for software, SDL_Renderer, SDL_GPU, Sokol and Canvas/WASM field export. Software reuses rounded-RECT traversal; GPU/Sokol add private brush shader parameters; SDL_Renderer and Canvas may use bounded caller/adapter-owned per-frame rasters. Native Canvas gradients alone cannot implement source straight-alpha/Oklab policy. Specify scratch ownership, release/upload completion and failure before writing those fallbacks; changed raster bytes require a fresh bitmap revision, never an overwritten live upload. Initially use no retained cache. Any later cache needs its own key/eviction/invalidation review (brush, shape, DPI, fractional placement/phase; opacity if baked). Required proof: independent source/CSS sampler goldens (cardinals/obliques, non-square projection, reversed/equal/transparent stops, both spaces, Aurora thumb); old untouched draw-list/pixel oracles; set/replace/reset/collision/open/ closed/portal/current-frame/clip/corners/opacity/order/resize/DPI/suppression; transactional invalid and exact-budget/overflow/upload failures; all five adapter interior samples and their existing edge-coverage tolerances; headless browser and private-Xvfb native tests, no desktop windows. No compiler ran for this audit. Only then map theme brushes and Button/Slider parts, preserve representative accessibility colors, and add owned typed foreign authoring/version checks. Theme brush storage/access must be additive too: do not enlarge `cui_theme` or silently replace its existing scalar palette. Missing brush support stays an explicit importer limitation, not a first-stop color presented as full support. No all-78/complete-Background claim: source patterns, multistop/radial/repeating CSS, arbitrary image backgrounds, font/text/focus and remaining component parts stay explicit follow-on work; no default palette/pixels change is authorized. --- ## Background transport: pre-composition negotiation and complete frames Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/ELEMENT_BACKGROUND_TRANSPORT.md # Background transport: pre-composition negotiation and complete frames Static addendum to [ELEMENT_BACKGROUNDS.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/ELEMENT_BACKGROUNDS.md), baseline `f724017c`; no architecture/API is approved or implemented. This supersedes that checkpoint's recommendation to return an incomplete base list or reject a legacy `end_frame` after composition. Preserve the signed Button/background branches. ## Actual integration constraints `cui_draw_command` is a public struct, not an extensible tagged union. It contains bitmap, mesh, text-paint and shadow fields separately; its size/stride appears in arrays, copies and adapters. Adding an inline brush normally grows stride. Overlaying a new pointer/union onto shadow storage is NOT proven ABI-safe: size, alignment, offsets and old source member access need every supported ABI checked. An added enum tag alone carries no owned brush and is not backward compatibility; enum representation/stride still need ABI checks, and exhaustive switches change. `cui_renderer` currently has capabilities and `render(user,list,clear)`, but no context/payload lookup. `cui_end_frame` is called inside bridge step (`src/bridge/cui_bridge.c`), with SDL rendering in `cui_bridge_sdl.c`, and inside `web/gallery.c`. Gallery exports each command field via `gallery_command` plus separate text/bitmap accessors, enumerated by `scripts/build_web.py`. Canvas `web/gallery.js` does not strictly reject every unknown tag: a new positive tag can fall through to an ordinary fill. Native switches also do not uniformly preflight an entire unknown-tag list before touching output. Neither a new enum nor a capability bit added to an old struct repairs already compiled consumers. ## Alternatives | Choice | ABI / ordinary frame API | Complete-frame and ownership cost | | --- | --- | --- | | A: existing command storage, NEW background tag + context-owned versioned descriptor lookup | Old structs stay byte-for-byte; existing begin/end/render calls can remain. New adapter binding is startup-only. | Background-aware renderer is explicitly bound to this context; tag is never a transparent placeholder. New context/consumer protocol and copy restrictions require approval. | | B: inline command extension or `cui_draw_command_v2`/versioned list | Appending a field breaks old stride. Explicit V2 types preserve V1 but require new producer/consumer/export entry points. | Brush can travel with a command by value; simpler independent copying. Still must negotiate before composition; cannot cast V1/V2 arrays or silently drop the brush. | | C: Core-owned raster lowered to existing IMAGE | V1 list is complete and render APIs unchanged. | Needs a NEW bounded pixel owner and authoritative target scale before composition. Existing bitmap helpers rasterize/crop at logical ceil sizes; merely supplying high-DPI pixels does not preserve physical fidelity. Fixing that globally changes old image pixels; hidden image tags/revision bits are unacceptable. | | Earlier sidecar with transparent RECT base | Preserves physical struct size, introduces a separate per-frame view | Reject: an intermediate consumer can render an apparently valid but incomplete list; late end-frame rejection also occurs after actions ran. | **Recommendation for review:** A minimizes per-frame API proliferation, ONLY if one explicit context-bound consumer and current-frame command views are acceptable. Choose B instead if independently copied/reordered/serialized semantic commands must be a first-class public contract. C is not a shortcut to full five-adapter DPI support; logical-only fallback must not be presented as equivalent semantics. No implementation starts until this choice and the ownership/failure rules below are approved. Storage ABI compatibility in A is not legacy transport compatibility. ## A: explicit opt-in before begin_frame, no new end-frame function Sketch names only; the common value type remains unapproved: ```c /* Versioned record, not an extension to cui_renderer or cui_config. */ typedef struct { uint32_t size, descriptor_abi, model_mask, space_mask; uint32_t shape_policy, output_policy; size_t max_brushes, max_raster_pixels, max_frame_bytes; } cui_background_support; /* Per-adapter bind/unbind outside frames, after preceding render completes. */ bool cui_sdl3_bind_backgrounds(cui_sdl3 *, cui_context *, const cui_background_support *limits); /* Other four consumers need equivalent binding/handshake, not this native type. */ bool cui_background_command_read(cui_context *, const cui_draw_list *, size_t index, uint32_t expected_descriptor_abi, cui_background *out); ``` An UPDATED adapter factory/handshake supplies actual supported policies, format, limits and descriptor ABI; callers cannot infer support from IMAGE, bridge ABI1, or header presence. Bind checks complete model/space/shape/output compatibility and establishes its target/resource policy before any frame. Core copies support values; it does not own the adapter or retain arbitrary callbacks. The adapter borrows the context until explicit unbind/destruction; unbind/change requires no active frame and completed rendering. No global registry, resource graph, new threads or multiple outstanding frames. Destruction order/lifetime is part of this NEW contract, not something the existing renderer interface already ensures. Without this negotiation, setters reject before changing paint/allocating brush storage. An old app follows the exact legacy route: no tag, descriptor or new end-frame failure. Once enabled, setters copy bounded descriptors into Core-owned frame storage and end_frame emits the explicit tag at the actual fill position, with existing bounds/corners and a validated descriptor lookup association. No stop/color pointers are borrowed. No brush is hidden in bitmap/mesh/text fields. The bound updated adapter uses its normal render entry point and verifies the current context/list association, descriptor version and every tag before paint. Manual fabricated background tags/prepaint emits are rejected, not guessed. Lists containing only legacy tags retain their existing render route. Copying a list header while retaining the original frame command view is permitted through renderer completion; a new begin_frame already invalidates borrowed data. Deep-copying/reordering command arrays does NOT automatically copy lookup identity. An owned snapshot/export must copy typed brushes as well as commands and use an explicit validated importer; no address matching, old bounds, raw C memory dumps or magic revision bits. If that restriction is too costly, prefer B now. Accessor checks cannot make an expired borrowed list safe after buffer reuse. ## Simplest coherent full-five-adapter path Start with ONE shared checked CPU sampler/physical-raster preparer for both models and spaces, including the agreed shape/alpha/clip policy. Use it in all five adapters initially rather than implementing three shader/Canvas interpolation variants at once. Existing typed brush values and previous mathematical evidence are reused; extracting math must preserve old Plot/effects/text output exactly. | Consumer | Minimum integration beyond common preparation | | --- | --- | | Software | New-tag preflight, descriptor access, prepared-pixel source-over in command order. | | SDL_Renderer | Bind target scale; upload prepared physical RGBA; draw without logical-size rerasterization or duplicate shape/opacity. | | SDL_GPU | New-tag branch, bounded prepared texture/upload ownership, current textured-quad path; no new gradient shader required initially. | | Sokol | Equivalent bounded texture/view staging and command ordering; prepare before render-pass mutation. | | Canvas/WASM | Version/feature handshake, explicit tag/descriptor field exports, physical raster helper bridge and strict JS dispatch; no native Canvas-gradient approximation. | Thus minimum is 1 Core owned-descriptor/negotiation seam, 1 shared math/preparation module, 4 native adapter integrations, 1 C+JS Canvas wire integration, and bridge binding/error plumbing. This is a structural count, not a line/time estimate. Each adapter needs a descriptor/version/full-tag preflight and actual output tests; IMAGE support does not make any of those integrations free. Existing bitmap logical-ceil cache paths cannot be reused blindly for physical prepared rasters. Agree whether new raster coverage matches existing RECT per adapter or uses one shared mask: old GPU/Canvas AA differs. A new consistent mask is an explicit opt-in edge policy, not exact old-solid/source-GPU pixel parity. Untouched legacy commands keep their existing paths. Shader optimizations/cache reuse come later. Core descriptor count <=min(max_elements,4096), charged to frame_bytes, replacing an owner record in place; no unbounded allocation per repeated setter. Approximate common-ABI descriptor value is72 bytes, but budget by actual sizeof+index metadata, not that estimate. Renderer owns transient CPU rasters and staged uploads, NOT Core. Proposed ceilings remain4M pixels/brush,8M pixels and32MiB CPU/frame plus 32MiB upload/frame,16384 per physical side, checked arithmetic and target transform. Include command-copy/staging overhead separately. No retained raster cache assumed. This requires a NEW whole-frame preparation phase in each adapter, not an existing atomic-render guarantee. Allocate/query/rasterize/stage before clearing; fresh pixel revisions and renderer completion prevent overwritten live texture sources. On validation/capacity failure retain previous style; conversion failure returns an empty erroneous list, never an incomplete successful list. Render preparation/ upload failure before target mutation returns false and preserves the previous surface; clean staging and reuse the context next frame. Device loss/failed submit after mutation cannot promise GPU rollback. Existing action callbacks may already have run: no event replay or implicit recomposition/rollback on failure. ## CPU preparation lowered to IMAGE: simplest first rendering option A shared bounded sampler can lower each semantic fill to an owned per-render RGBA IMAGE at explicit physical scale; all five then reuse their image compositing and texture paths, without five shaders or a retained cache. This is the preferred first rendering implementation to investigate, independently of transport A/B. It is not currently a drop-in Core IMAGE substitution: bitmap helpers regenerate logical-ceil rasters and radius masks. Add an explicit prepared-image path/private adapter staging so physical pixels survive, shape coverage/opacity apply exactly once, and clip/geometry/order remain those of the original fill. Do not reinterpret legacy IMAGE fields or alter old image output. Canvas needs equivalent owned bytes and explicit scale/wire lifetime, not a native-gradient approximation. Existing SDL_GPU bitmap upload copies raster bytes into a transfer buffer, records an upload and releases that buffer; Sokol uploads through its image path. That does not establish a universal borrowed-CPU-buffer completion contract. Each adapter must prove when CPU bytes may be released and who retains textures/transfer storage until queued GPU work completes. Public IMAGE currently borrows pixels through render completion; asynchronous staging cannot borrow the next frame's scratch. Use per-render owned staging and explicit completion/driver-safe release, or bound in-flight work to one and wait; do not assume render-return means GPU completion. With 8M pixels the proposed 32MiB CPU +32MiB texture budget can additionally need 32MiB transfer staging: budget96MiB for simultaneous whole-frame copies, before command arrays, shadows, surfaces, driver alignment and previous in-flight frames. Incremental release may lower peak only with a proven lifetime ledger. Charge costs or lower the cap; blocking completion avoids unbounded frame multiplication but has latency cost. Upload/allocation failure fails the frame, never flat-color approximation. Performance evidence can justify shaders/cache later. ## Bridge, exports, failure recovery and review gate Bridge must bind the actual SDL consumer after context creation and before step's first begin_frame. Headless/no-consumer mode cannot advertise renderer support; pure palette/value construction remains available independently. Check support at attachment/update before retaining an unsupported requested brush. Future Python/JS/TS/Go/Rust authoring must negotiate new symbols/capability versions, not assume that their existing ABI1 library supports this feature. Gallery/WASM must negotiate the host wire version BEFORE its first composed frame, export full typed brush fields, and reject unknown tags/versions in JS. Other end-frame forwarders, captures and serializers must join that negotiation or remain legacy-only. A missing/old consumer never enables semantic backgrounds. Updated adapters must reject unsupported whole lists before target mutation; a caller deliberately bypassing the negotiated consumer cannot be made safe by an enum alone. B provides stronger type separation if that must be prevented. Recovery changes limits/target/binding between frames; it does not silently flatten to a representative color or rerun accepted actions in the failed frame. Slider coordination: signed resolver design `185ee042` uses private owned `cui_slider_palette_color`/brush, straight linear float RGBA, fixed2stops, explicit sRGB/Oklab and GPUI038 projection only. Keep it pure and renderer-independent; source-Hsla conversion preserves hidden RGB without byte quantization, while custom cui_theme bytes explicitly decode sRGBA8. Convert privately to an approved shared type later; no duplicate universal brush ABI is being implemented. Review must select A/B/C, version/lease/copy rules, shape/output policy and the resource/failure protocol before production. Require all-five adapter output, legacy ABI/pixel, old-consumer refusal, copy/version/resize/clip/budget recovery and headless browser/private-Xvfb tests. All78 coverage, theme brush ownership, source patterns, focus/text and foreign authoring remain separate pending slices. ## Root decision: versioned commands, values first Review selected **B: explicit versioned draw/list contracts**. Preserve all V1 structs and routes. A's context-bound lookup/copy restrictions and incomplete-list risk are rejected. No V2 record is approved yet: review its complete owned brush, serialization, capability and five-adapter contracts before implementation. The next independent slice is Core-owned fixed-two-stop background values and a pure allocation-free sampler only. It does not attach paint, emit commands, own targets or enable rendering. Common CPU preparation and all five adapters remain required follow-on work; this decision does not narrow the full background goal. --- ## Element shadow ownership coverage: 78-family source audit Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/ELEMENT_SHADOW_COVERAGE.md # Element shadow ownership coverage: 78-family source audit Audit baseline: `b553c8bb`; catalog authority [component manifest](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/gpui-parity.json). This is a read-only ownership checkpoint, not 78-component acceptance evidence. Subsequent candidate slices add [six typed builder roots](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_SHADOWS.md) and [opt-in C selection indicators](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NAMED_SELECTION_INDICATORS.md); the matrix below deliberately preserves its stated baseline rather than counting those later slices as acceptance of every family. All 78 catalog families remain open for complete shadow coverage. Source references identify current paint sites; the linked public header on each family is the catalog authority. Additional additive headers are noted below. The first C slice styles an already submitted, current-frame, non-layout-only **named box**, including portals, through `cui_element_set_box_shadows` and `cui_element_set_shadow_preset` ([contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui.h#L679), [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/core/cui.c#L2155)). It does not manufacture a component root, address anonymous nodes, retain styles across frames, or shadow glyph/mesh silhouettes. Apply after the actual box submission and before `end_frame`, never from measurement/prepaint/diagnostics. Callbacks may submit different owners; absence, virtualization, collapsed views and layout-only measurement reject. Styling a transparent layout row is technically possible but is not equivalent to styling its inner painted surface. Codes in the C column describe **source-level eligibility**, not tests of that family: **R** = caller-supplied named root/box; **P** = public named parts or conditionally emitted portal; **I** = internally named owners without supported public paint-ID mapping; **E** = justified host/data/no-paint exception. Private XOR/hash IDs are recorded as private: copying their constants is not a public API. For each R/P entry the first C seam is implemented, while the listed remaining parts are not delivered by that seam. There is **no retained bridge/Python/JS/TS/ Go/Rust element-shadow authoring facade at this baseline** for any row. The six-kind binding worker and opt-in Checkbox/Radio indicator worker are in flight; their future work is not counted here. Existing built-in default shadows and style callbacks are not general element-shadow coverage. | Catalog family / authoritative header | Actual paint owners and public identity | First C seam now / remaining work | Exact painter evidence | | --- | --- | --- | --- | | [Accordion](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_disclosure.h) | Container ID and supplied item trigger IDs; revealed panels use private derived IDs, omitted/measurement-only while collapsed. | R on container/triggers; panel accessor and per-part proof remain. | [src/components/cui_disclosure.c:143](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_disclosure.c#L143), [src/components/cui_disclosure.c:49](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_disclosure.c#L49) | | [AlertDialog](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_surface.h) | Shared Surface portal uses state.overlay.id; footer/action buttons have derived surface-part IDs. | P when open; backdrop, arrow and action mapping are separate owners. | [src/components/cui_surface.c:160](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_surface.c#L160), [src/components/cui_surface.c:263](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_surface.c#L263) | | [Alert](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) | Caller ID owns alert card; detail/content containers use private content-child IDs. | R; title/description/icon/close mapping needs explicit part contract. | [src/components/cui_content.c:40](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_content.c#L40), [src/components/cui_content.c:55](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_content.c#L55) | | [Attachment](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_media.h) | Caller ID is card; typed part getter exposes media/overlay, metadata, actions, remove/media retry; indexed child getter exposes row/text retry. | R/P current-frame parts only; conditional/custom namespaces may have no box. C-only; builder targets pending. | [Getter source](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_media.c#L22), [Typed getter contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMPOUND_SHADOW_PARTS.md), [focused tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_compound_shadow_parts.c) | | [Avatar](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) | Caller ID owns round frame/ring; photo bitmap has private child ID; stack is separate composition. | R frame; photo/ring separation and stack-part targeting pending. | [src/components/cui_content.c:265](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_content.c#L265), [src/components/cui_content.c:288](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_content.c#L288) | | [Badge](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) | Legacy caller ID is pill; ex caller ID wraps custom content, public cui_badge_indicator_id owns positioned indicator. | R/P indicator if submitted; content callback owns its descendants. | [src/components/cui_components.c:1913](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_components.c#L1913), [src/components/cui_components.c:1940](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_components.c#L1940), [src/components/cui_components.c:1981](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_components.c#L1981) | | [Bubble](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) | begin_bubble caller ID is surface; composed caller ID is row; typed getter exposes actual surface/reactions. | R/P current-frame composed parts; reactions conditional. C-only; builder targets pending. | [Getter source](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_content.c#L26), [Typed getter contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMPOUND_SHADOW_PARTS.md), [focused tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_compound_shadow_parts.c) | | [Button](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) | Caller ID is painted button box; loading/content/icon wrappers mostly anonymous. | R; independent content/loading part styling not supplied by first slice. | [src/components/cui_components.c:609](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_components.c#L609), [src/components/cui_components.c:615](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_components.c#L615) | | [Checkbox](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) | Caller ID is label/indicator row; indicator and its layout wrappers are anonymous. | R row only; painted indicator gap is assigned to another worker, not closed here. | [src/components/cui_components.c:1323](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_components.c#L1323), [src/components/cui_components.c:1329](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_components.c#L1329) | | [Clipboard](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_sdl3.h) | SDL clipboard interface is a host service, not a UI painter or node. | E host-only; style the app's copy button, not this service. | [include/cui/cui_sdl3.h:71](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_sdl3.h#L71) | | [Collapsible](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_disclosure.h) | Caller ID belongs to trigger; outer wrapper and revealed panel use private derived IDs. | R trigger; no public outer/panel getter, collapsed panel may be absent/layout-only. | [src/components/cui_disclosure.c:94](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_disclosure.c#L94), [src/components/cui_disclosure.c:49](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_disclosure.c#L49) | | [DropdownButton](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h) | Supplied container/action/trigger IDs are separate boxes; popup uses menu state overlay ID. | R/P supplied halves and open popup; internal separator/content ownership remains separate. | [src/components/cui_choice.c:2766](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_choice.c#L2766), [src/components/cui_choice.c:2780](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_choice.c#L2780), [src/components/cui_choice.c:2836](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_choice.c#L2836) | | [Empty](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) | Caller ID is root; header/media/title/description/actions are private children or caller render callbacks. | R; meaningful subpart getters/ownership contract pending. | [src/components/cui_content.c:766](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_content.c#L766), [src/components/cui_content.c:776](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_content.c#L776) | | [Focus Trap](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_overlay.h) | Overlay focus scope only; header explicitly leaves layout/paint to application. | E no-paint scope; decorate caller-owned panel/portal instead. | [include/cui/cui_overlay.h:8](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_overlay.h#L8) | | [GroupBox](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) | Caller ID is outer framed box; title is text within it, content is caller submitted. | R frame; no separate title paint box contract. | [src/components/cui_content.c:826](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_content.c#L826) | | [HoverCard](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) | Caller ID owns conditionally submitted portal; inner width-constraining content box is private child17. | P when painted; no new part getter in this baseline; six-kind binding worker owns facade. | [src/components/cui_content.c:1100](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_content.c#L1100), [src/components/cui_content.c:1147](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_content.c#L1147) | | [Icon](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_icon.h) | Caller ID owns rectangular box; SVG is rasterized into a bitmap under private derived paint boxes, not named icon-path boxes. | R rectangle only; glyph silhouette/path shadows are outside this setter. | [src/components/cui_icon.c:85](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_icon.c#L85) | | [Image](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_media.h) | Caller ID owns image frame; placeholder/checker/content children use private media IDs and bitmap commands. | R frame; image content/placeholder part contract pending. | [src/components/cui_media.c:44](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_media.c#L44), [src/components/cui_media.c:52](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_media.c#L52) | | [Kbd](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) | Legacy and ex use caller ID for rounded keycap; stroke/icon/text are inner content. | R keycap; no independent stroke-part getter. | [src/components/cui_content.c:844](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_content.c#L844), [src/components/cui_kbd.c:44](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_kbd.c#L44) | | [Label](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) | Legacy cui_label emits text with no box; cui_label_source optionally creates box at nonzero semantic_id. | R only optional source-label box; legacy requires caller wrapper; not glyph shadow. | [src/components/cui_components.c:1910](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_components.c#L1910), [src/components/cui_label.c:925](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_label.c#L925) | | [Marker](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_status.h) | Caller ID wraps text/marker; highlight pieces use private status-child IDs/paint content. | R wrapper; marker highlight subparts need stable contract. | [src/components/cui_status.c:387](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_status.c#L387), [src/components/cui_status.c:392](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_status.c#L392) | | [Message](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_message.h) | Caller ID is message stack; typed getters expose avatar/header/footer and indexed body surface/slot row. | R/P current-frame parts; optional/custom slots may omit boxes. C-only; builder targets pending. | [Getter source](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_message.c#L15), [Typed getter contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMPOUND_SHADOW_PARTS.md), [focused tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_compound_shadow_parts.c) | | [MessageScroller](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_message.h) | Caller ID owns clipped scroller; typed getter exposes viewport/jump and state/index getter resolves retained row key. | R/P submitted rows only; offscreen identities have no box. C-only; builder targets pending. | [Getter source](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_message.c#L112), [Typed getter contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMPOUND_SHADOW_PARTS.md), [focused tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_compound_shadow_parts.c) | | [Notification](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_status.h) | Supplied scope is not a submitted root; typed getter combines scope/logical ID into actual card/content/action/close identities. | P only when painted; system-only/removed/layout-only omitted, custom action namespace may have no box. C-only; builder targets pending. | [Getter source](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_status.c#L480), [Typed getter contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMPOUND_SHADOW_PARTS.md), [focused tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_compound_shadow_parts.c) | | [Pagination](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_numeric.h) | Caller ID is row; public numeric_part_id identifies navigation buttons/page window items. | R/P present page buttons; ellipsis/text are not independent boxes. | [src/components/cui_numeric.c:194](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_numeric.c#L194), [src/components/cui_numeric.c:224](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_numeric.c#L224) | | [Progress](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) | Caller ID is track/root; fill and label wrappers use private XOR IDs; circle variant has own caller-ID root and mesh. | R track/circle rectangle; named fill/ring subpart contract pending. | [src/components/cui_components.c:2041](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_components.c#L2041), [src/components/cui_components.c:2053](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_components.c#L2053), [src/components/cui_components.c:3045](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_components.c#L3045) | | [Radio](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) | Caller ID is label/indicator row; grouped variant adds supplied group/item IDs; painted circular indicators remain anonymous. | R row/group only; indicator naming assigned to another worker, not covered here. | [src/components/cui_components.c:1875](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_components.c#L1875), [src/components/cui_components.c:1881](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_components.c#L1881) | | [Rating](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_numeric.h) | Caller ID owns star group; public numeric_part_id addresses star wrappers/clear; star artwork nested anonymous. | R/P star wrapper; exact star mesh/anonymous visual ownership remains gap. | [src/components/cui_numeric.c:295](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_numeric.c#L295), [src/components/cui_numeric.c:307](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_numeric.c#L307), [src/components/cui_numeric.c:312](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_numeric.c#L312) | | [Shimmer](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_status.h) | Caller ID owns clipped text root; effect stripe portals use private derived IDs. | R rectangular text extent; stripe/glyph-specific shadows not exposed. | [src/components/cui_status.c:298](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_status.c#L298), [src/components/cui_status.c:339](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_status.c#L339) | | [Skeleton](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) | Caller ID owns rounded skeleton box; ex delegates same visual; shimmer highlight is effect content. | R shape rectangle; no separately exposed highlight owner. | [src/components/cui_content.c:899](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_content.c#L899), [src/components/cui_content.c:998](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_content.c#L998) | | [Spinner](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) | Legacy caller ID owns dot layout and private dot IDs; ex default delegates Icon at caller ID; custom paint callback can own/omit boxes. | R for built-in box paths only; glyph/dots/custom callback not universal parts. | [src/components/cui_content.c:862](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_content.c#L862), [src/components/cui_content.c:948](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_content.c#L948) | | [Stepper](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_numeric.h) | Caller ID root; public numeric_part_id items in visual navigation; its circles/connectors anonymous; presentation circles use undocumented numeric1000+ IDs. | R root, conditional item wrappers; circle/connector contracts vary across painters; no facade claim here. | [src/components/cui_numeric.c:365](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_numeric.c#L365), [src/components/cui_stepper_visual.c:36](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_stepper_visual.c#L36), [src/components/cui_stepper_visual.c:42](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_stepper_visual.c#L42), [src/components/cui_stepper_presentation.c:98](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_stepper_presentation.c#L98) | | [Switch](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) | Caller ID row; public switch_track_id and switch_thumb_id own painted track/thumb; optional focus portal separate. | R/P track/thumb when submitted; focus/icon content remains separate. | [src/components/cui_components.c:1544](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_components.c#L1544), [src/components/cui_components.c:1557](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_components.c#L1557), [src/components/cui_components.c:1568](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_components.c#L1568) | | [Tag](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_status.h) | Caller ID owns tag shell; start/end/text wrappers and close content use private XOR IDs. | R shell; private content/action part access pending. | [src/components/cui_status.c:241](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_status.c#L241), [src/components/cui_status.c:249](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_status.c#L249) | | [Toggle](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) | Caller ID owns toggle painted box; icon/spacers/content wrappers anonymous. | R; child content/indicator separation not exposed. | [src/components/cui_components.c:1693](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_components.c#L1693), [src/components/cui_components.c:1699](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_components.c#L1699) | | [Tooltip](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h) | Caller ID owns conditionally submitted tooltip portal; text is local content. | P only while emitted; absent hover target must reject, not retain prior frame style. | [src/components/cui_content.c:1100](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_content.c#L1100), [src/components/cui_content.c:1128](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_content.c#L1128) | | [Calendar](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_picker.h) | Caller ID owns calendar frame; public day/year/month/navigation getters map emitted interactive boxes; layout rows/private cells separate. | R/P current-view cells/navigation only; omitted views have no target. | [src/components/cui_picker.c:117](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_picker.c#L117), [src/components/cui_picker.c:173](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_picker.c#L173), [src/components/cui_picker.c:280](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_picker.c#L280) | | [ColorPicker](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_picker.h) | Caller ID frame; public color_part_id maps hue/plane/alpha/swatches; small color raster boxes private style IDs. | R/P coarse controls; raster cells/handles need precise part contract. | [src/components/cui_picker.c:470](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_picker.c#L470), [src/components/cui_picker.c:474](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_picker.c#L474), [src/components/cui_picker.c:522](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_picker.c#L522) | | [Combobox](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h) | Caller input ID paints Input; state.overlay.id owns popup; results use supplied item IDs through List. | R input/P open popup/results; viewport/details follow constituent gaps. | [src/components/cui_choice.c:1476](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_choice.c#L1476), [src/components/cui_choice.c:1503](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_choice.c#L1503) | | [DatePicker](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_picker.h) | Caller ID paints trigger button; calendar popup is state.overlay.id, inner calendar ID derived internally. | R trigger/P open popup; calendar part-root mapping and compound date-time variants need contract. | [src/components/cui_picker.c:370](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_picker.c#L370), [src/components/cui_picker.c:402](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_picker.c#L402), [src/components/cui_date_time_picker.c:75](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_date_time_picker.c#L75) | | [Editor](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_editor.h) | Caller ID frame; textarea_viewport_id public; completion item getter public; gutter/row/find-bar wrappers private. | R/P viewport/completion when emitted; gutter/code/selection/find parts not complete. | [src/components/cui_editor.c:280](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_editor.c#L280), [src/components/cui_editor.c:358](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_editor.c#L358), [src/components/cui_editor.c:119](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_editor.c#L119) | | [Form](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_form.h) | Caller ID form layout; supplied field IDs own field boxes; public form_label_id/description_id; controls submitted by callbacks. | R/P supplied fields/labels/descriptions; row/error/control ownership not universal. | [src/components/cui_form.c:38](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_form.c#L38), [src/components/cui_form.c:50](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_form.c#L50), [src/components/cui_form.c:101](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_form.c#L101) | | [Input](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) | Caller ID frame; input_viewport_id is public clipped content box; caret/selection/text are commands/private children. | R/P viewport rectangle; glyph/caret/selection ownership not separate shadow targets. | [src/components/cui_components.c:2585](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_components.c#L2585), [src/components/cui_components.c:2700](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_components.c#L2700) | | [Input Group](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_form.h) | Caller group ID frame, caller input ID embedded Input, supplied addon IDs own addon boxes; side wrappers private. | R/P group/input/addons; internal side/container pieces need explicit mapping. | [src/components/cui_form.c:161](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_form.c#L161), [src/components/cui_form.c:353](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_form.c#L353), [src/components/cui_form.c:398](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_form.c#L398) | | [NumberInput](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_numeric.h) | numeric_part_id(id,0) owns outer number frame, id owns embedded Input; +/- use public parts1/2. | R/P frame/input/buttons; part0 paint use verified in source, not documented numeric header's listed parts. | [src/components/cui_numeric.c:116](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_numeric.c#L116), [src/components/cui_numeric.c:143](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_numeric.c#L143) | | [OtpInput](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_otp.h) | Caller ID root; public otp_cell_id each emitted cell; grouping/separator boxes derived privately. | R/P cells; separators/group frame contract pending. | [src/components/cui_otp.c:56](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_otp.c#L56), [src/components/cui_otp.c:66](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_otp.c#L66), [src/components/cui_otp.c:105](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_otp.c#L105) | | [Questionnaire](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_questionnaire.h) | Caller IDs explicitly name root/item/choices/actions/heading/choice cards; indicator/title/shortcut internals anonymous/private. | R on explicitly supplied controls; nested indicator/shortcut contract incomplete. | [src/components/cui_questionnaire.c:776](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_questionnaire.c#L776), [src/components/cui_questionnaire.c:860](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_questionnaire.c#L860), [src/components/cui_questionnaire.c:1130](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_questionnaire.c#L1130) | | [Select](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h) | Caller trigger ID painted button; state.overlay.id popup; supplied list item IDs own result rows. | R/P trigger/open popup/items; menu contents follow List parts gap. | [src/components/cui_choice.c:1302](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_choice.c#L1302), [src/components/cui_choice.c:1329](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_choice.c#L1329) | | [Slider](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_components.h) | Legacy track ID unchanged; optional typed Base ROOT/TRACK/FILL/START_THUMB/END_THUMB use cui_base_slider_model_part_id_v1. Single omits START; pure getters do not certify presence. | R/P basic track; new C-only typed Base named boxes accept existing element setter after facade; legacy/styled fill/thumb/marks and all five typed builders remain pending. | [legacy track/fill](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_components.c#L2085), [legacy styled events](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_styled_slider_events.c#L72), [typed Base painter](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_base_slider_model.c#L109), [typed part getter](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_base_slider_model.c#L8), [typed Base guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BASE_SLIDER_MODEL.md) | | [Speech](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_speech.h) | speech_button delegates caller-ID Button; waveform uses caller-ID clipped box with generated visual bars. | R button/waveform frame; provider/recognizer services have no visual root. | [src/components/cui_speech.c:9](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_speech.c#L9), [src/components/cui_speech.c:74](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_speech.c#L74) | | [Textarea](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_textarea.h) | Caller ID frame; public textarea_viewport_id; text rows/padding/selection/caret are private/command owners. | R/P viewport; per-line/caret/selection shadows not independently exposed. | [src/components/cui_textarea.c:106](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_textarea.c#L106), [src/components/cui_textarea.c:124](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_textarea.c#L124), [src/components/cui_textarea.c:172](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_textarea.c#L172) | | [TimeField](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_picker.h) | Caller ID owns field group; public time_segment_id names emitted segment controls; separators are text. | R/P segments; separator glyph shadow outside box seam. | [src/components/cui_picker.c:417](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_picker.c#L417), [src/components/cui_picker.c:438](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_picker.c#L438) | | [Carousel](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_carousel.h) | Caller ID root; internal clipped frame derived privately; caller control/pagination IDs accepted; slide render callback owns slide content. | R and supplied controls; frame/slide getters and callback ownership contract pending. | [src/components/cui_carousel.c:239](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_carousel.c#L239), [src/components/cui_carousel.c:247](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_carousel.c#L247), [src/components/cui_carousel.c:347](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_carousel.c#L347) | | [DescriptionList](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_description.h) | Caller ID root; supplied item IDs own value cells; row/label/body grouping privately derived. | R/P item cells; label and row getters pending. | [src/components/cui_description.c:81](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_description.c#L81), [src/components/cui_description.c:95](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_description.c#L95), [src/components/cui_description.c:111](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_description.c#L111) | | [Dialog](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_surface.h) | Shared Surface portal at state.overlay.id; content supplied by caller; public surface_part_id for selected controls. | P when open; backdrop/arrow/resize handles have distinct owners, not whole-dialog silhouette. | [src/components/cui_surface.c:149](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_surface.c#L149), [src/components/cui_surface.c:160](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_surface.c#L160), [src/components/cui_surface.c:197](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_surface.c#L197) | | [Dock](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_dock.h) | Caller view/workspace ID root; public group/tab/close/resize/menu/zoom/region getters; panel body/title wrappers derived privately. | R/P emitted public part boxes; model keys alone are not paint IDs; hidden panels absent. | [src/components/cui_dock.c:723](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_dock.c#L723), [src/components/cui_dock.c:1317](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_dock.c#L1317), [src/components/cui_dock.c:2393](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_dock.c#L2393) | | [List](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h) | Caller container ID root; caller item IDs own visible rows; icon/text/selection wrappers private/anonymous. | R/P rendered items; virtual/filtered-out rows not targetable, subparts incomplete. | [src/components/cui_choice.c:1078](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_choice.c#L1078), [src/components/cui_choice.c:1124](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_choice.c#L1124) | | [Menu](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h) | Trigger caller ID and open state.overlay.id portal; tree/submenu scopes internally derived, item IDs supplied. | R/P trigger/popup/item rows; submenu/checkbox/arrow visual parts lack complete public map. | [src/components/cui_choice.c:1302](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_choice.c#L1302), [src/components/cui_choice.c:1928](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_choice.c#L1928), [src/components/cui_choice.c:2015](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_choice.c#L2015) | | [Popover](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_surface.h) | state.overlay.id is actual portal frame; public surface_part_id includes selected header/arrow/resize owners; footer anonymous. | P frame and known emitted named parts; placement/measurement/closed cases conditional. | [src/components/cui_surface.c:160](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_surface.c#L160), [src/components/cui_surface.c:172](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_surface.c#L172), [src/components/cui_surface.c:246](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_surface.c#L246) | | [Resizable](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_resizable.h) | Caller group ID root; supplied panel IDs; public resizable_handle_id owns absolute hit-band box; visible handle line anonymous. | R/P group/panel/handle band; shadowing band is not independently shadowing visible line. | [src/components/cui_resizable.c:169](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_resizable.c#L169), [src/components/cui_resizable.c:206](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_resizable.c#L206), [src/components/cui_resizable.c:228](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_resizable.c#L228) | | [Root View](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_root.h) | Caller ID is real painted base-root box; facilities are separately submitted surfaces/notifications, plugins own decorators/overlay content. | R root; cannot shadow facilities by assuming they share root ID. | [src/base/cui_root.c:173](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_root.c#L173), [src/components/cui_root.c:62](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_root.c#L62) | | [Scrollable](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_scroll.h) | Caller ID is surface; viewport privately derived; public scrollbar_id names track/bar box, thumb anonymous in legacy painter. | R/P root/bar when emitted; viewport/thumb mapping incomplete; overlay variant separate paint policy. | [src/components/cui_scroll.c:34](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_scroll.c#L34), [src/components/cui_scroll.c:39](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_scroll.c#L39), [src/components/cui_scroll.c:88](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_scroll.c#L88) | | [Settings](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_settings.h) | Caller ID owns outer frame; public settings_part_id accepts page/group/item role numbers without documenting their meanings; custom field render owns its controls. | R root; internal parts technically named, but role-number contract needs documentation before public targeting. | [src/components/cui_settings.c:836](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_settings.c#L836), [src/components/cui_settings.c:575](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_settings.c#L575), [src/components/cui_settings.c:604](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_settings.c#L604) | | [Sheet](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_surface.h) | Shared Surface portal at state.overlay.id, with shared part getters; edge placement does not create a distinct catalog root. | P when open; backdrop/footer/caller content remain separate owners. | [src/components/cui_surface.c:160](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_surface.c#L160), [src/components/cui_surface.c:214](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_surface.c#L214) | | [Sidebar](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_sidebar.h) | Caller ID wrapper; menu/header/footer IDs supplied; public sidebar_part_id exists but role numbers are undocumented; body/selected parts are internally named; spacers/content anonymous. | R/P explicit sections/items; derived body parts need documented role mapping. | [src/components/cui_sidebar.c:458](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_sidebar.c#L458), [src/components/cui_sidebar.c:502](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_sidebar.c#L502), [src/components/cui_sidebar.c:131](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_sidebar.c#L131) | | [StatusBar](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_chrome.h) | Caller ID frame; supplied region item IDs own boxes; region/spacer IDs private chrome_part. | R/P explicit items; region/inner layout getters pending. | [src/components/cui_chrome.c:62](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_chrome.c#L62), [src/components/cui_chrome.c:34](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_chrome.c#L34) | | [Tabs](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h) | Caller container ID layout; supplied tab item IDs own triggers; bar/content/underline/overflow portals privately derived. | R/P visible trigger wrappers; actual underline/panel/background part mapping incomplete. | [src/components/cui_choice.c:561](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_choice.c#L561), [src/components/cui_choice.c:595](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_choice.c#L595), [src/components/cui_choice.c:750](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_choice.c#L750) | | [Theme](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_theme.h) | Shared style data/provider, no submitted UI box merely by choosing theme. | E data-only; style the actual consuming owner rather than inventing Theme root. | [include/cui/cui_theme.h:25](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_theme.h#L25) | | [TitleBar](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_chrome.h) | Caller ID frame; supplied item IDs own boxes; drag/title/control region wrappers private chrome_part; OS actions host-owned. | R/P explicit items; native OS chrome has no Core paint ID. | [src/components/cui_chrome.c:182](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_chrome.c#L182), [src/components/cui_chrome.c:196](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_chrome.c#L196) | | [Toolbar](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_toolbar.h) | Base toolbar/group begins caller-ID box; optional sized-item IDs and command IDs own boxes; custom callback owns inner descendants. | R/P explicit item/command boxes; anonymous icon/content pieces not separate targets. | [src/base/cui_toolbar.c:36](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_toolbar.c#L36), [src/components/cui_toolbar.c:52](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_toolbar.c#L52), [src/components/cui_toolbar.c:171](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_toolbar.c#L171) | | [Tree](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_tree.h) | Caller ID root; public tree_row_id/tree_toggle_id emitted visible row/toggle boxes; indentation/icon wrappers private. | R/P current visible rows/toggles; collapsed descendants absent; labels are text. | [src/components/cui_tree.c:39](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_tree.c#L39), [src/components/cui_tree.c:56](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_tree.c#L56), [src/components/cui_tree.c:71](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_tree.c#L71) | | [VirtualList](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_virtual_scroll.h) | Caller ID frame; viewport/window IDs derived privately; render callback owns row boxes, no automatic universal per-item paint root. | R frame; row targeting needs callback-supplied IDs; viewport/window getter absent. | [src/components/cui_virtual.c:50](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_virtual.c#L50), [src/components/cui_virtual.c:52](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_virtual.c#L52), [src/components/cui_virtual.c:58](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_virtual.c#L58) | | [Chart](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_chart.h) | Caller ID clipped bitmap/prepaint frame; bars/axes/paths are raster/prepaint commands; legacy tooltip portals private, current tooltip is prepaint content. | R rectangle; no per-mark box targets or public tooltip-owner mapping. | [src/components/cui_chart.c:2016](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_chart.c#L2016), [src/components/cui_chart.c:2676](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_chart.c#L2676) | | [Command](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_command.h) | Caller ID root; public command_input_id/list_id/row_id; icon/shortcut/group/detail wrappers private. | R/P current input/list/rows; result subparts and filtered rows incomplete/absent. | [src/components/cui_command.c:145](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_command.c#L145), [src/components/cui_command.c:230](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_command.c#L230), [src/components/cui_command.c:295](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_command.c#L295) | | [DataTable](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_table.h) | Caller ID root; public body/header/row/cell/group-header/resize/trailing/row-header IDs; frozen panes/spacers private. | R/P rendered public boxes; virtual omissions and renderer-owned cell content remain conditional. | [src/components/cui_table.c:436](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_table.c#L436), [src/components/cui_table.c:490](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_table.c#L490), [src/components/cui_table.c:532](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_table.c#L532) | | [Plot](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_plot_view.h) | Caller ID per view/element/grid/dots/bars/labels box; plot geometry is bitmap/mesh/prepaint; legacy tooltip portal private, current tooltip prepaint-owned. | R per explicit plot layer rectangle; no per-point/path silhouette or tooltip getter. | [src/components/cui_plot.c:842](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_plot.c#L842), [src/components/cui_plot.c:935](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_plot.c#L935), [src/components/cui_plot.c:993](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_plot.c#L993) | | [Table](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_table.h) | Caller ID table frame; row/cell/section/caption IDs explicitly supplied by caller. | R/P all submitted explicit boxes; cell-content callback/glyphs stay separate owners. | [src/components/cui_table.c:32](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_table.c#L32), [src/components/cui_table.c:109](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_table.c#L109), [src/components/cui_table.c:134](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_table.c#L134) | | [TextView](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_text_view.h) | Caller ID clipped document frame; optional scroller/block-action boxes derived privately; glyph/code/table/selection paint mainly prepaint commands. | R document rectangle; no complete block/link/code-action paint-ID contract. | [src/components/cui_text_view.c:1025](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_text_view.c#L1025), [src/components/cui_text_view.c:771](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_text_view.c#L771) | ## Public-part authority and important boundaries The getters above are declared in the family's linked header, except source Label [`cui_label.h`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_label.h), source Stepper [`cui_stepper_visual.h`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_stepper_visual.h), and textarea viewport reused by Editor [`cui_textarea.h`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_textarea.h). Numeric part meanings are explicitly listed at [`cui_numeric.h:52`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_numeric.h#L52); NumberInput part0 is used by the painter but omitted from that listed-part contract and needs documentation before promoting it as a consumer promise. Surface parts are documented at [`cui_surface.h:164`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_surface.h#L164); Settings exposes a generic helper at [`cui_settings.h:148`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_settings.h#L148) but does not document its role-number meanings; Sidebar has the same generic-helper limitation. A public helper returning an interaction ID is not proof that every mode submits a box there; verify the particular painter/mode in the evidence column. A bounds getter alone also does not establish a current-frame owned paint box. Notification now has a C typed paint-ID getter. Its logical key/type is distinct from both scope and paint identity; no box is submitted at the scope, and fully hidden cards remain layout-only. Compound builder targets remain pending. Root View, in contrast, really creates a named root through Base; its facilities are separately owned. Clipboard, Focus Trap and Theme justify no invented visual roots; applications can decorate their real enclosing controls. Chart/Plot/Icon/Image expose rectangular owners; this is box shadow ownership, not vector-path/raster alpha silhouette shadowing. ## Next independent slices 1. **Already public identities:** Switch track/thumb, Badge indicator, OTP cells, Input/Textarea viewport, Calendar/Time/Color controls, and explicit Table rows/cells. Add focused current-frame ownership, mixed DROP/INSET ordering, clipping and clear/invalid-transaction tests, then add narrowly scoped builder part targeting. Do not duplicate the six-kind facade worker's owned roots. 2. **Compound painted surfaces:** Bubble's actual surface/reactions, Message and MessageScroller cards, Attachment media/treatments, Notification card/actions. C typed getters now expose these identities with conditional/custom/layout-only contracts. Binding targets and broader renderer proof remain pending; do not substitute outer rows. 3. **Anonymous painted indicators:** legacy/Styled Slider thumb/fill, Progress fill, Rating star artwork, visual-navigation Stepper circles/connectors, scroll thumb and Resizable visible handle line. Design opt-in names preserving legacy command streams; Checkbox/Radio indicators are already assigned elsewhere and excluded from this slice. 4. **Structured collections:** List/Menu/Select/Combobox parts, Tabs bar/panel/ underline, Accordion/Collapsible panels, Tree/Sidebar/Settings/Dock sections. Publish only stable emitted-part mappings, with collapsed/virtual/portal tests. 5. **Document and raster owners:** Editor gutter/completion/find controls, TextView block/action surfaces, Chart/Plot tooltip frames. Separate meaningful rectangular controls from command-only marks/glyphs; a per-primitive API would be a separate design, not implied completion of this box seam. Completion needs all-family ownership decisions plus headless behavior/painter proof and matching consumer/binding documentation. This audit changes no public API, painter, manifest, generated resource or test; no compile or native window was run. It deliberately leaves the complete-coverage item unchecked. --- ## Unified element shadows: proposed architecture Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/ELEMENT_SHADOW_STYLING.md # Unified element shadows: proposed architecture Status: named-box addressing and CSS factory implemented as the first slice; component-part and binding rollout remains a proposal. Audit base: fb3be922. This proposal covers the 78 catalog families as an implementation plan, not a claim that all roots or nested parts already expose shadow styling. ## Evidence and gap `include/cui/cui.h:375–416,670–673` already defines copied, bounded eight-layer DROP/INSET lists, named presets and open-box setters. `src/core/cui.c:2111` validates a whole list before replacing the current open node. The renderer pipeline and budgets are documented in DROP_SHADOW.md and INSET_SHADOW.md. No new renderer is needed for ordinary rectangular element shadows. The missing seam is addressing component-owned geometry consistently. Most one-call widgets close their root before returning. Applying the existing setter after that call styles the caller's open parent. A wrapper adds layout geometry and cannot reach a detached popup. `cui_bounds` (`src/core/cui.c:3046`) may return previous-frame bounds, so it cannot implement correct move/resize decoration. Core records current-frame nodes, anonymous synthetic layout IDs and portal paint roots (`src/core/cui.c:1825–1858`); these are private implementation details. `src/components/cui_components.c:1323–1329` illustrates named outer and anonymous indicator nodes. `src/components/cui_surface.c:149–189` has separate resize, backdrop and surface portals; only the surface receives its existing style list. `cui_picker.c:370`, `cui_content.c:1100`, `cui_editor.c:119` and `cui_dock.c:253` provide further independently owned portal examples. ## Recommended decision Review an additive current-frame by-ID setter in Core, plus explicit public component part resolution. Do not add a global pending style that silently applies to whichever internal box happens to be emitted next. Do not change existing public structure layouts, defaults, preset tuples or sigma meanings. A by-ID setter alone does not cover anonymous parts or conceptual components. First-slice signatures (see authoritative `include/cui/cui.h` contracts): ```c bool cui_element_set_box_shadows(cui_context *, cui_id, const cui_box_shadow *, size_t count, cui_corner_radii); bool cui_element_set_shadow_preset(cui_context *, cui_id, cui_shadow_preset, cui_corner_radii); bool cui_box_shadow_from_css(float x, float y, float blur_radius, float spread, cui_color, cui_box_shadow_kind, cui_box_shadow *out); ``` The element setter accepts only an already submitted, named current-frame box, including a closed box or portal, before end_frame. ID zero, missing/previous-frame ID, layout-only nodes, collision, invalid list or prohibited mutation phase reject atomically with documented diagnostics. Open-node setters retain their contract. No deferred target registration: application order is component submission, then styling. Replace all DROP/INSET layers, last successful call wins; count zero and NONE clear. Existing component defaults survive absent explicit opt-in; an explicit setter after submission replaces them. A later component-owned setter would replace that explicit list, so begin/end consumers apply styling after end. No retained cross-frame style or automatic state inheritance is introduced. Reuse the node's copied eight-layer storage and existing paint emission. Decoration must mark the target's layout custom data even after closure; review that Core operation explicitly. Store no Clay pointer in a public value. Linear lookup is a bounded initial implementation; optimize only with measured evidence. No new layout pass, input target, semantic node, bounds expansion or capture is added. Opacity, ancestor masks, local overflow clipping, portal ordering and resource failure boundaries remain the existing renderer contracts. DROP remains before background, INSET after background before local content; supplied order is retained within each phase. This is CUI paint order, not a promise of complete CSS stacking. CSS convenience converts blur_radius to sigma=blur_radius/2 explicitly; existing sigma-based APIs and named source presets never change. Validate finite radius in [0,512], offsets/spread in [-4096,4096], kind and output before writing, preserving existing supported-domain checks. CSS defines blur using half-radius Gaussian standard deviation: https://www.w3.org/TR/css-backgrounds-3/#shadow-blur . CUI's bounded kernel, spread/radius handling, source mask culling and RGBA8 quantization remain different from full browser box-shadow. This factory promises a useful CSS-inspired parameterization, not browser pixel identity. Custom sigma lists remain available without conversion. ## Component-owned parts Each family must publish which ID denotes its rectangular paint root and which parts need explicit stable IDs or checked part getters. Do not expose private numeric XOR salts. Preserve semantic ownership; an indicator paint ID must not become an input target. For currently anonymous nodes, assigning an ID can affect capacity/collision behavior and needs owner-specific tests. Indexed parts require stable keys, bounds checks and absence reporting. Popup surface, trigger, backdrop, arrow and resize handles are separate targets; root styling must never silently style all five. Nonrectangular/vector/glyph masks remain outside box-shadow. The matrix below is a complete catalog inventory and proposed acceptance route. R = rectangular owner/root audit and test; P = additional detached surface audit; N = nested/repeated/anonymous parts require explicit mapping; H = host/behavior family, no independent rectangular caster promised. Every R/P/N row is pending per-API ID verification. Header links are canonical catalog authority, not proof that each entry point has a suitable root today. | Family | Route | Header | | --- | --- | --- | | Accordion | R/N | `include/cui/cui_disclosure.h` | | AlertDialog | R/P/N | `include/cui/cui_surface.h` | | Alert | R | `include/cui/cui_content.h` | | Attachment | R/N | `include/cui/cui_media.h` | | Avatar | R | `include/cui/cui_content.h` | | Badge | R | `include/cui/cui_components.h` | | Bubble | R | `include/cui/cui_content.h` | | Button | R | `include/cui/cui_components.h` | | Checkbox | R/N | `include/cui/cui_components.h` | | Clipboard | H | `include/cui/cui_sdl3.h` | | Collapsible | R/N | `include/cui/cui_disclosure.h` | | DropdownButton | R/N | `include/cui/cui_choice.h` | | Empty | R | `include/cui/cui_content.h` | | Focus Trap | H | `include/cui/cui_overlay.h` | | GroupBox | R | `include/cui/cui_content.h` | | HoverCard | R/P/N | `include/cui/cui_content.h` | | Icon | R | `include/cui/cui_icon.h` | | Image | R/N | `include/cui/cui_media.h` | | Kbd | R | `include/cui/cui_content.h` | | Label | R | `include/cui/cui_components.h` | | Marker | R | `include/cui/cui_status.h` | | Message | R/N | `include/cui/cui_message.h` | | MessageScroller | R/N | `include/cui/cui_message.h` | | Notification | R/P/N | `include/cui/cui_status.h` | | Pagination | R | `include/cui/cui_numeric.h` | | Progress | R | `include/cui/cui_components.h` | | Radio | R/N | `include/cui/cui_components.h` | | Rating | R/N | `include/cui/cui_numeric.h` | | Shimmer | R | `include/cui/cui_status.h` | | Skeleton | R | `include/cui/cui_content.h` | | Spinner | R | `include/cui/cui_content.h` | | Stepper | R/N | `include/cui/cui_numeric.h` | | Switch | R/N | `include/cui/cui_components.h` | | Tag | R | `include/cui/cui_status.h` | | Toggle | R/N | `include/cui/cui_components.h` | | Tooltip | R/P/N | `include/cui/cui_content.h` | | Calendar | R/N | `include/cui/cui_picker.h` | | ColorPicker | R/P/N | `include/cui/cui_picker.h` | | Combobox | R/P/N | `include/cui/cui_choice.h` | | DatePicker | R/P/N | `include/cui/cui_picker.h` | | Editor | R/P/N | `include/cui/cui_editor.h` | | Form | R/N | `include/cui/cui_form.h` | | Input | R | `include/cui/cui_components.h` | | Input Group | R/N | `include/cui/cui_form.h` | | NumberInput | R/N | `include/cui/cui_numeric.h` | | OtpInput | R/N | `include/cui/cui_otp.h` | | Questionnaire | R/N | `include/cui/cui_questionnaire.h` | | Select | R/P/N | `include/cui/cui_choice.h` | | Slider | R/N | `include/cui/cui_components.h` | | Speech | H | `include/cui/cui_speech.h` | | Textarea | R | `include/cui/cui_textarea.h` | | TimeField | R | `include/cui/cui_picker.h` | | Carousel | R/N | `include/cui/cui_carousel.h` | | DescriptionList | R/N | `include/cui/cui_description.h` | | Dialog | R/P/N | `include/cui/cui_surface.h` | | Dock | R/P/N | `include/cui/cui_dock.h` | | List | R/N | `include/cui/cui_choice.h` | | Menu | R/P/N | `include/cui/cui_choice.h` | | Popover | R/P/N | `include/cui/cui_surface.h` | | Resizable | R/N | `include/cui/cui_resizable.h` | | Root View | R/N | `include/cui/cui_root.h` | | Scrollable | R/N | `include/cui/cui_scroll.h` | | Settings | R/N | `include/cui/cui_settings.h` | | Sheet | R/P/N | `include/cui/cui_surface.h` | | Sidebar | R/N | `include/cui/cui_sidebar.h` | | StatusBar | R | `include/cui/cui_chrome.h` | | Tabs | R/N | `include/cui/cui_choice.h` | | Theme | H | `include/cui/cui_theme.h` | | TitleBar | R | `include/cui/cui_chrome.h` | | Toolbar | R/N | `include/cui/cui_toolbar.h` | | Tree | R/N | `include/cui/cui_tree.h` | | VirtualList | R/N | `include/cui/cui_virtual_scroll.h` | | Chart | R/N | `include/cui/cui_chart.h` | | Command | R/P/N | `include/cui/cui_command.h` | | DataTable | R/N | `include/cui/cui_table.h` | | Plot | R/N | `include/cui/cui_plot_view.h` | | Table | R/N | `include/cui/cui_table.h` | | TextView | R/N | `include/cui/cui_text_view.h` | ## Bindings and rollout The shared bridge is `include/cui/cui_bridge.h`; no box-shadow authoring operation is declared there today. Source SDK availability is not language-builder support. Python, Node/TypeScript, Go and Rust must all expose the same copied style value, preset and CSS factory semantics. Prefer a versioned additive bridge operation with bounded explicit layer records and count validation, then typed facade methods in each builder. Do not expose pointers into host arrays or depend on C structure layout across the wire. Builders must apply style after actual native submission, not when retained authoring objects are merely constructed. Detached popup styling must run only when its current-frame surface exists. Go/Rust bundled C source is regenerated separately from their typed facade implementation. First review Core addressing, anonymous-part policy and replacement precedence. Then implement pure CSS factory and named-root seam with focused tests. Migrate representative Button, Input, anonymous Checkbox indicator, compound Stepper, clipped Scrollable and portal Popover before expanding family-by-family. Reuse existing presets; add an optional explicitly chosen visual recipe/gallery page with light/dark surfaces, subtle/raised/floating examples, mixed inset and custom layers. No new implicit shadows on older components. Only update completion metadata for rows with actual root/part and binding evidence. ## Acceptance tests and maintenance Headless tests must prove submitted/closed/current-frame resolution, same-frame move/resize, missing/zero/duplicate IDs, omission next frame, copied stack lists, all eight layers, transactional ninth/NaN rejection, NONE/clear, preset/custom replacement, CSS conversion endpoints and unchanged output on rejection. Compare no-opt-in legacy command streams and software pixels. Exercise ancestor clip, local overflow, opacity once, translucent backgrounds, nested parts, independent popup/trigger/backdrop targeting, modal layering and unchanged semantics/input. Test resource exhaustion and recovery using the existing emission boundaries. The 78-row matrix becomes an acceptance tracker with per-entry-point test evidence, not one generic test presented as all-component coverage. Binding tests assert the same layer records, ownership, clear/error behavior and live popup lifecycle for all five language facades. Reuse renderer regressions; no redundant raster suite. Browser probes run headless at DPR1/2; native checks use test_local.py/Xvfb. GPU checks unavailable in virtual display stay deferred. Keep one focused build, -j1, nice19, and avoid package tests that silently build unrelated targets. When implementing public contracts, update canonical header/docs, binding coverage, source manifests, SDK/amalgamation generators and consumer skill resources. Run generate_agent_skill.py and test_agent_skill.py under the agreed resource budget. The original design commits changed no consumer contract, generated data or manifest entry and ran no compilation. First-slice evidence is recorded below. ## Core seam checkpoint before implementation Closed-node decoration can reuse an existing private mechanism without creating custom paint on every element. `cui_set_scroll_offset` in `src/core/cui.c:1937` already resolves a node submitted in the current `ui->nodes[0..node_count)` and mutates its Clay hash-map element after closure. Clay's element retains its `config` through EndLayout: `third_party/clay/clay.h:3061` tests `config.custom.customData` while generating CUSTOM paint. There is no separate closed-element custom-data registration required. The proposed setter first matches the full public ID in the current node array (not merely its folded hash), rejects layout-only nodes, selects the context, then obtains `Clay__GetHashMapItem(node->clay_id)`. Before mutation it checks the returned element exists, its id matches, it is not text/exiting, and its `config.userData == node`. The node array is allocated to max_elements at context creation, not resized during a frame; existing configuration already stores these same node pointers as userData/customData. These checks reuse that explicit ownership contract rather than expose or save a new Clay pointer. No pointer is retained across frames. `appearedThisFrame` must NOT be used as a current-frame flag: Clay uses it for newly appearing/transition behavior, not submission age. Current-frame membership comes from the CUI node array reset by begin_frame. Only a successful explicit style call attaches `config.custom.customData=node`. Invalid calls leave both element config and copied style untouched. All list and geometry validation precedes attachment. Zero-count on an otherwise untouched node is a no-op so a clear does not insert needless CUSTOM commands. Clearing an already customized node preserves other underlay/outline/mesh/prepaint owners; its pre-existing custom pointer is retained. This does not attach custom paint to unmodified nodes and preserves their old Clay/CUI command paths byte for byte. A clear following actual opt-in can use the existing customized empty-list paint path; tests must compare its visible output and background ordering as well. Duplicate public/folded IDs already fail at begin_box before node registration. The setter must reject a frame reporting DUPLICATE_ID rather than styling the first submitted node under an ambiguous application request. Unknown, zero, previous-frame and layout-only targets reject with documented invalid-action errors. Mutation guard rejects prepaint, measurement and diagnostic reentrancy. This seam needs no public struct growth, node-wide preattachment, previous-frame bounds query, changed renderer or input-dispatch path. It does rely on the pinned private Clay hash-map/config mechanism already used by scroll-offset mutation; focused closed/open/portal tests must lock down that dependency. If those checks cannot find the current owned element, reject rather than guess or scan stale arena memory. Component part IDs and language authoring remain separate work. ## First implementation slice and evidence The three additive APIs above now implement only current-frame named rectangular box styling and explicit CSS blur conversion. No component-part getter, retained builder integration or renderer change is included. The private duplicate-box flag is reset per frame and catches ambiguous identity even when an earlier unrelated diagnostic is sticky. Failed begin/layout-only scopes cannot style another node. Old entry points and unstyled element configuration are unchanged. Strict portable Release compilation used GCC16 with -Wall/-Wextra/-Wpedantic/ -Werror, nice19, CPU0 affinity and -j1 in one focused build directory. CTest through private Xvfb passed6/6: element_shadows, legacy drop_shadow/inset_shadow/ shadow_presets, and standalone/umbrella distribution fixtures. The umbrella fixture includes cui_all.h declarations with only the Core implementation, deliberately avoiding unrelated full-umbrella implementations. No new browser/GPU/sanitizer or binding evidence is claimed. The unit fixture covers open/closed/portal current-layout move/resize, omission, full-ID/folded collision rejection (including a preceding different diagnostic), layout-only and failed submission scopes, copied eight-layer records, invalid transactions, preset replacement and clear, preserved underlay/outline, legacy commands/software pixels, DROP/background/INSET/local-content order, ancestor clip/opacity, ordinary pointer activation, measurement/prepaint/diagnostic guards, command-capacity rollback and explicit-error-clear recovery. CSS constructor bounds and unchanged-output rejection are independent assertions. Required SDK, amalgamation and skill resources are generated from canonical sources. Offline installed-skill tests passed17/17; SDK checksums, distribution and skill freshness checks passed. --- ## Go/Rust controlled Slider bridge checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/GO_RUST_SLIDER_MODEL_V1.md # Go/Rust controlled Slider bridge checkpoint Source audit at integrated `02240266`; proposal only, no implementation or runtime claim. C authority is [BRIDGE_SLIDER_MODEL_V1.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/BRIDGE_SLIDER_MODEL_V1.md). Python and Node/TypeScript already expose the separate bridge-owned route. These two remaining languages must preserve legacy scalar Slider timing/autoacceptance. ## Actual integration constraints | Area | Go | Rust | |---|---|---| | Authoring | `native.go` owns retained `Node`, `App.Mount` preflight and native creation; `Slider(key)` remains kind9. | `src/lib.rs` owns imperative `App::root/child/create` and app-borrowed `Builder`; `Kind` currently ends at80. | | Loading | `native.go` C preamble owns `bridge_lib`, mandatory `API` table and optional notification/window resolvers. `New` permits only one loaded-library identity per process. | Dynamic `notification_symbol_v1` uses Unix lookup or Windows module-by-existing-symbol; `cui_bridge_static` directly pairs with bundled sources. | | Thread | `New` locks the goroutine OS thread before create; `App.check` validates the saved pthread/Windows token. `Close` destroys, nulls and unlocks (native runner defers unlock until return). | `App` has `PhantomData>`, making it !Send/!Sync. `Node` contains a private app ID. Owner thread stays alive through Drop. | | Dispatch | `Step` only steps; `Dispatch` drains legacy FIFO, counts entries and stops on Close. Native `goBridgeAfterFrame` captures panic/error before returning to C. | `step` only steps; `frame` steps then dispatches. Legacy callbacks take only `&ChangeEvent`; `run_with` catches panic/error and resumes outside C. | | Teardown | `RequestClose` requests shutdown; `Close` destroys. Existing `Node.Remove` is explicit. | `App::close` only requests shutdown; Drop destroys. `remove` clears legacy registrations after successful C removal. | Do not add new functions to Go's mandatory `API` table. Its optional C helpers must live beside the existing TU-local `bridge_lib` (or an included private header at that exact seam), not introduce another loader/global registry. Keep new public records in a focused Go file; thin Go crossing functions in native.go can bridge them without exposing cgo types publicly. Rust needs a focused `slider_model` module with private repr(C) wire records and existing dynamic/static linkage conventions. Dynamic mode resolves the complete 16-symbol group before any use, validates V1 plus all five sizes, and imports no new required symbol. Static mode may name matching bundled symbols directly; this is not compatibility with arbitrary older static archives. No dependency, loader, Core, dispatcher or native host change is needed. ## Owned records and exact values Both languages expose tagged Single(end)/Range(start,end), domain, complete config, receipt, request/evidence, presentation and typed part selection. Use float64/f64 for every value/domain/numeric payload, uint64/u64 for EVERY C uint64 (including event index and its UINT64_MAX absence sentinel), uint32/u32 handle pairs/enums/masks, and checked float32/f32 only for actual geometry. Never use int/usize, float, JSON numbers or scalar storage for identities/ranges. Private wire layouts match C value24/domain32/config72/receipt56/input72/request296/ presentation32/queue16 bytes; test sizes and offsets against C on actual supported targets. Validate schema/reserved/tag/mask/finite/active fields before publishing. Authored parent length is ignored/canonicalized; a nonzero inactive native parent length rejects. Copy all nested records before returning from FFI; no slices, references to C memory, borrowed native buffers or callback-held C stack values. Go/Rust records are owned value copies, not a promise that application-local variables cannot be mutated. Such mutation cannot alter the C submission snapshot or manufacture authority. Receipt fields are private, with read-only snapshot accessors; ordinary assignment/Clone preserves an issued receipt. A private per-App namespace token contains no App/native pointer. Go's token must have nonzero storage (distinct empty-struct pointers are not guaranteed distinct). Rust may use Rc identity for authority, deliberately keeping receipts local; explicit numeric snapshots can be transferred as inert data. Neither scheme is a security or cross-loaded-image uniqueness mechanism. Defaults initialize one complete config; reject active nonfinite/invalid values atomically. Preserve explicit whole-pair acceptance, current/gesture-domain distinctions, immutable C entry current and ordered evolving requested intent. No automatic owner write, retry, scalar CHANGE or receipt retagging. ## Proposed Go surface - `DefaultSliderConfig() SliderConfig`, `NewSliderSingle(end float64)` and `NewSliderRange(start,end float64)` return validated values/errors. - `SliderModel(key string, config SliderConfig, confirmed SliderValue) *Node` follows existing builder error accumulation; Mount rejects bad records and non-Row/Column ancestry before creating nodes/enabling the FIFO. - `App.SupportsSliderModel`, `EnableSliderRequests(capacity uint32)`, `PollSliderRequest() (SliderRequest,bool,error)`, `AcceptSliderRequest(SliderReceipt,SliderValue) error`, `DispatchSliderRequests() (int,error)`. - New typed node methods `ConfigureSlider`, `SetSliderValue`, `SliderValue`, `SliderConfig`, `SliderPartBounds`, `SliderPresentation`, `OnSliderRequest(func(SliderRequest) error)`; existing `Disabled/Text/Remove` policy/retained ownership remains. Do not overload scalar Value/OnChange. After legacy Dispatch reaches EMPTY, drain the typed FIFO only when enabled. Pop/copy once, capture handler, invoke after C returns; guard only the new typed callback phase against Step/Run/Dispatch recursion. defer clears the guard on error/panic; manual dispatch propagates panic normally, native trampoline resumes it only after leaving C. Callback may capture App, mutate external owner state, accept, configure, remove, queue later input, RequestClose or Close. Clear only new typed handlers on successful removal/Close, stop before another C call when closed, preserve OS-thread lock/unlock and all old callback behavior. ## Rust callback decision required before production Proposed base surface: `SliderValue::{Single{end},Range{start,end}}`, `SliderConfig::default`, `App::slider_model(parent:Node,key:&str,config,value)` returns Result; explicit parent required, C validates existing ancestry atomically. Add supports/enable/poll/accept/config/value/part/presentation methods with Result and owned Option results. Existing imperative authoring has no whole unmounted tree to preflight; rejection must not remove previously authored nodes. Registered typed callbacks need acceptance and label/policy updates, but existing legacy `FnMut(&ChangeEvent)` cannot access the mutably dispatched App. Do not silently expand every old callback or use application raw pointers/RefCell tricks. Recommended new signature: ```text on_slider_request(node, impl for<'a> FnMut(&mut SliderRequestContext<'a>, SliderRequest) -> Result<()> + 'static) ``` The new context privately borrows App and forwards explicit accept(receipt,pair), configure/set-value, text, remove, queued pointer/key/text input and close-request operations. It has no Deref/as_app/owned App escape. This permits external owner mutation and enqueueing without handing a callback `&mut App` that could replace or drop protected live App storage. Context does not dispatch input or own extra state. Pop/copy first; clone the callback registration, release map borrows, invoke with the context, and release it before the next poll. A private guard resets on panic; existing native catch_unwind boundary remains authoritative. Handler replacement/removal is allowed without borrowing the map across user code. Rust close remains request-only; destruction remains Drop after the caller's App borrow ends. Do not invent Python-style destroy-within-borrow semantics. Manual poll+explicit accept remains available without registered callbacks. Root review must approve the narrow context and its exact forwarding methods/signature before Rust production; unrestricted new `FnMut(&mut App,...)` is an alternative requiring an explicit protected-storage/replacement policy, not an unnoticed convenience. ## Independently reviewable implementation/proof slices 1. Go complete optional group, owned records, kind81 authoring/dispatch and full authored windowless UI. Reuse cached current/old bridge with `-tags cui_dynamic`, GOMAXPROCS=1, `go test -p1`; later one matching static/source closure check. 2. Rust records/FFI plus approved context and full authored windowless UI. Reuse cached bridge through CUI_BRIDGE_LIB_DIR, Cargo offline/locked/jobs1; later one matching bundled-static closure check without rebuilding an engine unnecessarily. 3. Coalesced human/LLM metadata/guides, canonical export and exact installed-source examples; all78 remain. No all-five claim until both actual runtimes pass. Each language needs actual Single/Range × both axes, explicit accepted/rejected full pairs, double extremes and 64-bit identities, ordering/legacy autoaccept, capacity/error atomicity, expiry/config/readonly/disabled/omission, copied lifetime, handler removal/replacement, callback error/panic/close and recursion tests. Prove Go wrong-thread rejection and Rust !Send/!Sync compile rejection. Use synthetic wire faults only as protocol evidence. Old-library fallback and all16 missing symbols must run in distinct processes against an actual old module, with missing historical-fixture omissions explicit. Native automated tests use private Xvfb; no desktop, dependencies, registry publishing or physical AT inference. Native numeric delivery, typed SET/touch injection, V2 gradients, arbitrary direct C Styled styles/motion and vertical registered-scroll admission remain separate open requirements after these wrappers; this does not close the whole family. ## Go implementation evidence (unreleased, pending integration) Go source implements the proposed independent optional group, owned copies and new typed callback phase. Actual dynamic typed UI tests passed; the first broad legacy wrapper run failed only native lifecycle/visibility fixtures because no FontPath had been supplied. That failure log is retained. Repeating with absolute bundled Inter passed, including those native fixtures; nine unrelated historical notification/shadow/visibility methods retained their explicit fixture skip gates. The next dynamic batch passed42/42 private-wrapper cases: font-correct legacy, actual old-module fallback, all16 missing symbols, support/size failures and synthetic malformed receipt/input/canonical absence evidence. The matching default Go source build passed TestSliderStaticClosure with no dynamic library override, actually resolving all optional entries and producing nested typed thumb geometry. It compiled required embedded SDK objects rather than assuming weak presence. Final metadata/skill gates and remaining example modes are still separate gates. Rust context production remains the next independent slice. --- ## HoverCard dismissal and accessible relationship audit Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/HOVERCARD_RELATIONSHIP_AUDIT.md # HoverCard dismissal and accessible relationship audit Historical design checkpoint. The bounded implementation has since landed in the integration branch; use [the current API guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/HOVER_CARD_EXTENDED.md) for implemented names, behavior and remaining limitations. The proposal below records its review scope. Design checkpoint only. No production change or parity-status promotion is authorized by this document. CUI baseline: `876c654e`; frozen reference checkout: `87d10ae5e1299d1be18670a37570c5402f952e34` (`/tmp/cui-upstream-reference`). ## Source findings The manifest item combines several independent promises. Existing behavior is not absent merely because the combined item remains `not_started`. | Concern | Frozen upstream | CUI baseline | Remaining scope | | --- | --- | --- | --- | | Desktop dismissal | Base HoverCard schedules close after leaving trigger/content; epoch cancellation prevents stale delayed work | Caller-owned reducer advances explicit dt; trigger focus, panel hover and contained child focus can hold open | Different scheduling contracts; preserve CUI ownership | | Escape | No explicit Escape handler in base HoverCard or its Popup host | Shared Tooltip/HoverCard scanner treats every Escape key-down as dismissal, including consumed, repeated, modified and composing input | Consumption-aware policy would be a CUI improvement, not demonstrated upstream parity | | Mobile dismissal | Mobile trigger click toggles; content installs left mouse-up-out dismissal | No equivalent mobile-specific toggle/outside-dismiss policy in this helper | Explicitly deferred | | Open notification | Base set_open changes state, notifies render, then synchronously calls current cloned on_open_change; same-value calls do nothing | Existing pure/styled lifecycle observers report aggregate model changes | Already supported, with different lifetime/timing guarantees | | Accessible relationship | No explicit controls/expanded/labelled-by relation in base/component HoverCard or Popup source | Open panel is GROUP with accessible name and parent=trigger; trigger is not patched with controls/expanded; Tooltip instead patches trigger description | Add a bounded CUI semantic relationship; upstream source does not establish this requirement as implemented | Reference authorities: `crates/base/src/hover_card.rs` (HoverCardState::set_open, schedule_open/schedule_close, RenderOnce), `crates/component/src/hover_card.rs` (wrapper), `crates/base/src/popup.rs` (placement/deferred occluding host), and `crates/component-shell/src/shell/overlays/hover_card.rs` (typed on_open_change forwarding). The reference tests exercise delayed pointer open/close, notification sequence, mobile toggle, content click retention and outside dismissal. These sources do not prove an upstream native accessibility mapping or Escape contract. CUI authorities: `src/base/cui_content.c` (`cui_hover_update` and pure event adapter); `src/components/cui_content.c` (`cui_content_hover_panel`, begin/end and styled event adapter); `include/cui/cui_content.h`; `include/cui/cui_hover_events.h`. Invalid viewport/anchor closes the model after reduction. Resource failure may reject composition while leaving the model open. Thus open, begin admission and completed visibility are distinct facts. Focus-inside retention uses previous rectangular containment, not semantic ancestry; do not strengthen that claim. ## Compatibility and input ownership `tests/unit/test_hover_styled_events.c` explicitly freezes the old behavior: its step 4 consumes a repeated Ctrl+Escape before submission and still expects the same close/suppression in legacy and observer paths. Changing the shared scan to ignore consumed Escape would break a tested contract and also change Tooltip. The pure reducer takes policy booleans; it cannot infer event acceptance. Core exposes `cui_event_consumed` and `cui_consume_event`. Core also associates Escape with a previous focus scope when one exists, but the current hover helper never checks that target. A consumption check alone is not focus ownership, topmost-popup arbitration or prevention of multiple open cards closing. A later submitted consumer cannot undo an earlier HoverCard decision. Consumption is sampled at the helper call, not retrospectively. Do not introduce a dispatcher, focus trap or a fabricated accepted-activation event to solve this slice. Initial relationship-only alternative (superseded as the recommended first slice by the mobile amendment below): an additive, typed HoverCard-only extended entry point with an explicitly enabled relationship policy. Existing entry points, Tooltip, options layout and all-zero/absent policy retain their exact behavior. This can reuse the private panel helper with default-preserving internal policy parameters; no Core architecture or retained state ownership changes are needed. A separate opt-in `ignore_consumed_escape` policy can be included only with its own documented semantics and tests: filter consumed indices before the existing Escape predicate, leave repeat/modifier/IME/global scope behavior unchanged, and do not consume Escape on behalf of the card. This policy is not exclusive input ownership. It must not silently become the legacy default. If strict no-behavior- change scope is preferred, ship relationship only and defer this policy. ## Proposed semantic contract The trigger must already be submitted in the current frame, as the current API requires. Patch its copied semantic details, preserving description, required, readonly, focus-target, release-key policy and all unrelated fields. Never create an invented trigger node or edit the previous frame as a fallback. The explicit opt-in grants this card ownership of trigger controls/expanded for this call; one relation field cannot represent several cards sharing one trigger. After the final begin decision, write controls=card_id and expanded=true only when the panel was actually admitted. Otherwise clear this owned controls relation and write expanded=false, including disabled, Escape, pending close/open, invalid-anchor/viewport and resource-failure paths. A pending close whose panel remains admitted stays expanded. Do not derive expanded solely from state.open. When no current trigger semantic exists, leave semantics untouched and report relationship application failure separately from begin admission; children/end balancing must continue to depend only on admission. Tests must pin this result. Omitted calls apply no patch and cannot replay a transition or clear caller data; ordinary immediate-mode trigger resubmission supplies fresh details. Retain the panel GROUP role, accessible name and existing parent=trigger. Do not add labelled_by=trigger automatically: the card may have its own explicit name, and this slice supplies no name-merging contract. Do not turn the card into a modal dialog, assert focus movement, or expose a dismiss accessibility action. Do not add a public field just to label a callback as dismissal. ## Existing notification timing Reuse `cui_begin_hover_card_events` semantics through an additive extended sibling if observation and the opt-in policy need to be combined. Snapshot handler and frame at entry. Observe the final legacy-equivalent model after begin/relationship work and before arbitrary admitted children; end is still required exactly once on true admission. A close observation happens after reducer/fallback mutation, not after portal removal has been rendered or after `cui_end_hover_card`. Do not add a second dismissal callback or silently change the existing result: `changed` is independent of handler; `change_count` counts callbacks, not inputs. Payload remains UNKNOWN source, genuine eligible frame only, no input index, activation evidence, cause or completed-visibility claim. Multiple Escape inputs can produce one close. Protected/frame-zero work keeps legacy maintenance and suppresses callbacks. Keep existing restrictions on callback mutation/reentry; no post-callback second state write or veto protocol is proposed. ## Accessibility proof boundary `cui_semantic_details` already contains controls, expanded and parent. Core setter replaces the full details record, so preserving unrelated data is necessary. `backends/accesskit/cui_accessibility.c` translates controls only when the target exists and emits expanded only when true or the node is TREEITEM. Consequently, setting expanded=false on an ordinary button does not currently prove an explicit collapsed property reaches AccessKit. A controls target absent while closed is also filtered. Core semantic tests alone cannot establish collapsed AT behavior. The bounded first implementation may honestly prove the CUI semantic snapshot and admitted-panel controls mapping, while recording collapsed platform state as unsupported. Full expanded/collapsed AT proof needs a separately reviewed adapter presence policy (the present boolean cannot distinguish unspecified from false), adapter snapshot assertions, and relevant native integration verification. Do not infer live screen-reader announcements, speech, navigation or mobile AT behavior from headless semantic snapshots. No adapter or public Core schema change is approved in this checkpoint. ## Required production proof before status changes - Preserve existing content, pure hover and styled hover event tests, including consumed/repeated global Escape on all legacy entry points and Tooltip. - Add focused headless extended-API cases: closed/pending/open/pending-close, Escape suppression/rearm, disabled close, invalid geometry, resource rejection, missing trigger, omission and two independent cards. Assert controls/expanded, parent, names, preserved unrelated details and exact begin/end balance. - If consumption opt-in ships, compare consumed and unconsumed Escape, repeated and modified input, preexisting suppression, and call-order boundary; assert no new consumption or claimed exclusive ownership. Keep legacy fixtures intact. - Compare absent-policy legacy and extended draw commands, bounds and model; test contained-child focus retention and intrinsic content placement unchanged. - Exercise observer before children, after final semantic patch, no-handler result, copied payload lifetime, frame-zero/inert/layout-only callback suppression and final-model fallback close. Never assert completed visibility from notification. - Use strict portable C11/C++ header checks and the repository Xvfb test wrapper; no desktop windows. Adapter proof is additional scope, not implied by these tests. Bridge currently renders HoverCard using legacy begin/end and separately reports its before/after model state. This checkpoint adds no bridge options, foreign callbacks, owned-content lifetime changes or Python/Node/TypeScript/Go/Rust API. Document those omissions if the C slice ships. Mobile tap/outside dismissal, exclusive Escape routing, live AT announcements and explicit collapsed adapter state remain separate work. The combined manifest item cannot be called fully complete from relationship snapshots alone. Root/integrator owns any approved metadata, generated SDK/distribution and consumer skill updates after review. ## Review amendment: mobile toggle and bounded outside release The first implementation proposal must cover genuine frozen mobile behavior as well as the manifest relationship requirement. Relationship snapshots alone do not close the source gap. This amendment supersedes the relationship-only first- slice recommendation; all legacy compatibility and AT limitations above remain. No production work is authorized by this amendment until separately reviewed. ### Accepted trigger input and explicit mode Propose one additive extended HoverCard API with a typed policy containing DESKTOP_HOVER (zero/default) and TAP_TOGGLE modes, relationship opt-in, explicit accepted-trigger input and optional bounded outside-release tracking. Retain the existing caller-owned hover state; add a separate caller-owned mobile workspace rather than appending fields to the public existing state/options. No automatic platform detection: the application selects touch/mobile policy. TAP_TOGGLE can be selected on desktop for headless tests and mouse/pen accessibility consistency. The old functions and an absent extended policy use the exact old helper path. The application submits its trigger first and passes whether that trigger actually accepted activation in this frame, using its Button bool/event result. The API must name this input accepted_trigger_activation, not raw pressed/tapped. False means no toggle; it must never be inferred from pointer-up coordinates, focus or cui_interaction_state alone. This is an explicit application assertion, not a claim that a public boolean is cryptographically validated. The implementation can prove its documented integration using real Button acceptance and cancelled- activation tests; arbitrary callers can still supply an incorrect assertion. An optional copied activation snapshot may accompany the assertion only when obtained at the trigger acceptance point. Validate target and current frame if used; never turn absent evidence into an invented source/index/press. If detailed snapshots add unnecessary scope, omit them entirely and keep UNKNOWN lifecycle metadata. In particular do not rescan events after Button consumption to decide whether its already accepted activation happened: accessibility acceptance can be cancelled by later consumption, while ordinary accepted activation has different rules. No change to either Core contract is proposed. Snapshot entry open before applying outside dismissal or the accepted toggle. A true trigger assertion sets open=!entry_open once, coalescing the aggregate Button result; it does not toggle once per raw event. This matches the frozen mobile trigger listener's captured rendered-open value and its explicit comment about outside dismissal handling the same release first. If several transitions must be represented within one frame in the future, a bool is insufficient; that requires a separately specified ordered accepted-input API. TAP_TOGGLE ignores hover/focus and open/close delays. It cancels pending elapsed policy work, and keeps the open card until accepted trigger toggle, permitted outside release, disabled close, legacy-global Escape or geometry fallback. Retain the old Escape predicate, including consumed/repeated/modified input; Escape wins over a toggle in the same aggregate call, with suppression preserved. Do not ship ignore_consumed_escape as an accidental new default. The desktop mode keeps its old reducer/containment rules. Closed or disabled mode, omission resumption and explicit mode changes reset the outside workspace, preventing a stale contact from closing a later card. On resume after a skipped frame, reset pending contact instead of assuming omitted input did not cancel it. ### Outside release support that current Core can prove Core authorities: cui_event_target resolves against previous-frame regions and may identify captured content even after the pointer leaves it. The scope-hit helpers require active focus scopes; current HoverCard creates none. Final cui_pressed is current capture state, not per-release history. Core touch handling tracks contacts, drag threshold, generated cancellation and scroll suppression, but no public universal accepted blank-space release snapshot exists. A blank outside tap therefore cannot honestly be described as an accepted widget activation. Existing overlay/surface outside policies dismiss on pointer-down; they cannot be reused unchanged to claim the frozen mouse-up-out contract. Propose an explicitly bounded outside-tap policy with one caller-owned pending contact: record primary down outside both previous valid panel and trigger bounds, its type/device/contact, starting point and frame. Accept a matching unconsumed primary up outside both regions only if no cancellation or drag invalidated that contact and ordinary submission/modal admission still permits the card. Reject nonfinite/unknown bounds, missing down, unmatched up, secondary button, mode or context reset, and ambiguous simultaneous contacts. Observe matching cancel even if consumed, so cancelled state cannot survive until a later release. Consumed matching down/move/up, scroll/gesture takeover, or movement reaching an explicit 8-logical-pixel radial threshold invalidates the pending tap; do not rearm within that contact. Include final up displacement. This threshold is the new policy's bounded rule, not a promise of universal host gesture equivalence. Movement must be processed in input order even when the final pointer returns near its start. Do not consume input or capture the outside target on behalf of this card. A down inside card/trigger never arms outside dismissal. Thus child clicks stay open, trigger release is owned by the accepted trigger assertion, and a drag from card to outside does not dismiss. A blank outside down/up does dismiss, including across adjacent frames. Touch cancellation, scrolling and pinch must retain the card. Multiple contacts fail closed for dismissal rather than guessing the primary finger. The tracker must see relevant events every submitted frame; it is not a second global dispatcher and does not establish topmost-popup ownership. Modal checks use existing cui_pointer_scope_allowed; unrelated overlays without a shared ownership protocol remain outside this guarantee. This strict outside-tap contract intentionally narrows frozen mouse-up-out, which does not itself require an outside press origin or a movement threshold. Preserve that distinction in status/consumer guidance: required frozen happy paths can be covered while drag/cancel safety receives its own explicit rule. If exact arbitrary mouse-up-out semantics are also required, expose a separately named raw-release policy and document its drag behavior; never claim the strict tap mode is exact full parity. Prefer the strict policy first for the user's touch requirement. ### Composition, observation and proof Apply the final mobile open decision before normal shared placement/admission. Reuse the existing observer contract after final model and relation patch, before children, without retaining handlers or changing payload/result meaning. A toggle plus outside close coalesces into the final model transition; no fabricated input multiplicity or completed dismissal event. Lifecycle metadata stays UNKNOWN/frame- only even when the application has supplied a real trigger snapshot: this aggregate can also include Escape, disabled or placement fallback. Relationship reflects actual admission, and collapsed AccessKit limitations remain explicit. Before production approval, required focused tests must additionally use actual Button accepted activation (mouse, touch, keyboard and accessibility as policy permits), cancelled trigger release and accessibility consumption timing; mobile hover/delay no-op; open, trigger retoggle, content click retention and blank outside release; same-frame trigger/outside ordering; cross-frame down/up; cancel before up; drag across threshold and back; consumed release; card-child drag out; contact/ device mismatch; second contact/pinch/scroll; mode switch, omitted frame, disabled, Escape and invalid-geometry reset; modal blocking; no-handler results and callback ordering. Keep the frozen upstream test scenarios traceable separately from new safety cases. Tests run through the repository headless wrapper with assertions and strict warnings. No new source, bridge/binding coverage, adapter promise or full touch/full parity status is implied by this design-only checkpoint. --- ## HoverCard dismissal and relationship checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/HOVER_CARD_DISMISSAL_RELATIONSHIP_AUDIT.md # HoverCard dismissal and relationship checkpoint Audit base: `ab8fddbb`; frozen source: `87d10ae5e1299d1be18670a37570c5402f952e34` (0.7.1). Proposal only; no production or ledger change. ## Source contract and existing coverage | Contract | Exact source | Current evidence / remaining scope | | --- | --- | --- | | Desktop delayed hover, retention while hovering content; cancel pending close on return | `crates/base/src/hover_card.rs:145-209,243-280` | `src/base/cui_content.c:cui_hover_update`, `src/components/cui_content.c:cui_content_hover_panel`; `test_content.c` and `test_hover_card_extended.c:desktop_parity` already cover desktop retention/delay and zero-extension equivalence. Focus retention and global Escape are CUI additions, not requirements found in this source. | | Mobile accepted trigger click toggles frozen rendered open value; cancel timers | `crates/base/src/hover_card.rs:233-246` | Extended tap policy already implemented. `test_hover_card_extended.c:mobile,acceptance_and_escape,routed_input_and_validation` cover accepted pointer/key/AT activation, rejection and callbacks. Platform choice remains explicit host policy. | | Mobile primary mouse-up outside content dismisses, irrespective of where down occurred or movement | `crates/base/src/hover_card.rs:269-280` | Genuine remaining difference: existing outside-tap policy requires matching outside down/up, movement below8px, no consumption/cancellation/gesture takeover. Tests explicitly preserve inside-down/outside-up and dragged releases. Do not rename that conservative policy source-equivalent. | | Relationships and keyboard accessibility | No relationship/expanded/role setup in frozen `hover_card.rs` or `crates/base/src/popup.rs:130-204`; `website/component/hover-card.md:244` calls it visual-only and recommends Popover for keyboard access | CUI opt-in relationships are an accessibility extension. Existing extended API patches submitted trigger controls/expanded after actual panel admission, preserves other details, and retains named GROUP parent=trigger. `relationships_and_protection` covers invalid geometry, resource rejection, missing trigger and protected work; callback inspects final relationship. The broad not_started row is stale, but native adapter completeness is genuinely open. | | Panel placement/appearance/content fit | `crates/component/src/hover_card.rs:151-187`, base Popup deferred positioner | Existing placement/intrinsic measurement must remain unchanged. `tests/web/test_example_polish.py` exercises actual-WASM intrinsic content fit; `test_touch_components.py` and broad browser fixture cover legacy gallery opening. These do not prove extended raw release or collapsed native AT state. | The source `on_open_change` clones the retained callback at state transition (`base/hover_card.rs:184-194`), including timer-driven transitions. CUI callbacks remain synchronous borrowed submission observers, with documented mutation restrictions and UNKNOWN origin. This audit does not assert equivalent retained ownership. ## Smallest compatible dismissal slice proposed Add an independent sibling submission descriptor/API rather than resizing `cui_hover_card_policy` or changing conservative outside_tap. A typed release policy chooses LEGACY/strict-tap/raw-primary-release; zero/NULL delegates exactly to the current extension. Raw release is meaningful only with explicit TAP_TOGGLE. It examines eligible unconsumed primary POINTER_UP outside previous valid panel bounds, without requiring matching down or a movement threshold; consumption/modal permission are explicit CUI routing rules, not a claim about undocumented upstream listener dispatch. Trigger accepted activation retains frozen entry-open precedence; disabled/global Escape and placement rejection retain current ordering. No event consumption, capture, modal ownership, dispatcher change or new retained resource is proposed. Invalid policy fails before mutation. Existing contact workspace is used only for strict taps. Before implementation, freeze names and whether raw release excludes the trigger region: source mouse-up-out is relative to content alone; accepted trigger activation must win using entry-open, including an outside release in the same submission. Do not silently substitute the existing both-regions test. Snapshot previous grid/bounds once; evaluate queued releases in order, preserving one final legacy callback, not a new per-input event stream. Tests: legacy/NULL/zero draw and semantic oracle; strict policy unchanged; raw inside-down/outside-up, unmatched release, above-threshold drag, outside-to-inside release, trigger release with accepted and rejected activation, secondary button, consumed release, cancellation/gesture characterization, missing/invalid bounds, modal denial, disabled, Escape, multiple queued releases and independent cards. Real pointer/key/AT trigger activation and exact final callback timing remain required. Native private wrapper + existing WASI extended suite; gallery opt-in and actual-WASM mouse/touch proof only after API review. No automatic mobile detection. ## Accessibility architecture decision required separately Core `cui_semantic_details.expanded` is a bool (`include/cui/cui.h:310`): false cannot distinguish absent from explicit collapsed. AccessKit (`backends/accesskit/cui_accessibility.c:190-191`) emits expanded only when true or TREEITEM; controls is separately emitted when its target resolves (`:228-230`). Thus the existing Core snapshot relationship is implemented, but ordinary closed trigger cannot reliably announce explicit collapsed state through native AccessKit. Do not fix this by setting expanded=false on every Button or by inventing a HoverCard role. A complete optional-state contract needs an explicitly reviewed Core presence representation and corresponding adapter/equality/serialization/bridge handling. Prefer a generic presence mask with an EXPANDED bit and bool value over a component-specific adapter exception; zero must preserve all old semantic behavior. This changes public semantic layout and requires matching-header/library rebuild and binding review. It is outside this component-only checkpoint. Required tests include absent/false/true, removal and omission, closed initial node, open-close, resource rejection, adapter tree updates and browser serialization; live screen-reader proof remains distinct from snapshot tests. ## Ledger reconciliation recommendation Replace the stale combined not_started feature with bounded tested evidence for existing dismissal and Core relationship plus explicit remaining raw-release and optional collapsed native-state work. Keep all78 entries and tested_partial platforms. Do not promote full HoverCard parity: inherited styling/content ownership, native AT, foreign bindings and exact host routing remain outside this audit. No source/API changes or new test run are claimed by this read-only checkpoint. ## Approved final component contract The additive declaration is in the existing extended header: `cui_hover_card_release_policy` with `CUI_HOVER_CARD_RELEASE_LEGACY=0` and `CUI_HOVER_CARD_RELEASE_RAW_PRIMARY`, and `cui_begin_hover_card_with_release` (same original arguments plus release policy before handler). No old struct changes. LEGACY delegates the original path exactly, including validation of conservative outside_tap/contact. RAW requires TAP_TOGGLE, overrides outside_tap, needs no contact, and clears any supplied contact. Invalid enum/mode fails before mutation. Content-only prior bounds are authoritative, not trigger bounds or enclosing clip. Finite unconsumed primary release and existing pointer-scope permission are required; no raw down bookkeeping. Cancel/scroll/gesture alone do not dismiss or veto a later raw release (host must consume/cancel that release); this is intentionally not a new gesture dispatcher. Multiple releases aggregate one final transition callback. Accepted trigger assertion is applied after release against entry-open, followed by existing disabled/Escape/placement rules. Callback and relationship timing stay unchanged. Optional collapsed semantic presence remains deferred. ## Implemented component slice and local evidence The approved additive release API is implemented with legacy delegation, raw content-only prior bounds, trigger entry-open precedence and unchanged observer ordering. No old descriptor layout, Core semantic layout or native AT adapter changed. The catalog retains all 78 entries and separates the remaining optional collapsed native accessibility feature from tested component dismissal. Fresh local validation on 2026-10-31 used one portable Release build tree, `CUI_BUILD_NATIVE=OFF`, strict warnings, and the final focused build at nice 19 with one job. Eight selected CTest checks passed via ```sh python scripts/test_local.py --build-dir /home/matteo/.cache/cui-hover-raw-build \ -R '^(hover_card_extended|example_hover_card_extended|hover_card_extended_header|content|hover_events|hover_styled_events|manifest|agent_skill_freshness)$' ``` The wrapper uses private Xvfb; no desktop windows were opened. The 17-test `tests/test_agent_skill.py` suite, generated distribution check, Go/Rust SDK freshness check and both gallery C snippets compiled with strict C11 warnings also passed. Generated skill resources and SDK/distribution copies were refreshed through their generators. `tests/web/test_hover_card_release.py` is ready for the integrator's single combined actual-WASM build. It drives browser mouse, keyboard and real CDP touch input, including the conservative/raw inside-down/far-outside-up distinction. It has only been syntax-checked in this worker; no fresh browser/WASI execution or GPU/native accessibility proof is claimed here. Run it headlessly with `uv run tests/web/test_hover_card_release.py --directory COMBINED_WEB_OUTPUT`. Native GPU hardware and live screen-reader observations remain deferred. --- ## Owned Icon resources and configured Badge: proposed bridge V1 Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/ICON_BRIDGE_CHECKPOINT.md # Owned Icon resources and configured Badge: proposed bridge V1 Design only after `956a853c` / `NODE_CONFIGURED_BADGE.md`. No symbols, structs or new node kinds below are implemented. Exact C authority remains `cui_icon.h` and `cui_components.h:470–515`. All 78 manifest families stay intact; this adds an internal bridge IR kind, not a component family. Root review precedes production. Existing kind11 Badge/kind50 Icon and their default routes are frozen. ## Records: native C layout, never a network wire Below U32/U64/F32 denote uint32_t/uint64_t/float; RGBA is U32 with R in bits0–7, G8–15, B16–23, A24–31. Native scalar endianness applies; foreign LE encodings must convert every scalar individually. No struct contains pointers, size_t, C enums or bool. All records start exact `struct_size,schema_version=1`; getters require those initialized headers. INPUT records reject unknown flags/reserved words. OUTPUT records require only exact size/version; other incoming bytes are ignored and successful output is canonical, including zero reserved fields. Proposed sizes/offsets are derived, **not measured**; strict native/WASM32 assertions and old-header ABI probes are required before approval to publish declarations. ```c typedef struct { U32 slot, generation; } cui_bridge_icon_handle_v1; //8,align4 // style:128,align4; every cui_box field has a representation struct cui_bridge_icon_style_v1 { U32 struct_size,schema_version,flags,reserved; //0..15 F32 width,height,padding,gap,radius; //16..35 U32 background_rgba,border_rgba; F32 border_width; //36,40,44 U32 align_x,align_y; F32 offset_x,offset_y; //48..63 F32 corners[4],border_edges[4]; //64..95 F32 max_width,max_height,opacity,padding_edges[4]; //96..123 U32 reserved_tail; //124 }; // flags bits0..11: row,clip,custom_corners,custom_border_edges,fixed_width, // fixed_height,layout_only,inert,custom_opacity,width_percent,height_percent, // custom_padding. Corners TL,TR,BL,BR; edges L,R,T,B. Align START0/CENTER1/END2. struct cui_bridge_icon_constraints_v1 { //32,align4 U32 struct_size,schema_version,flags,reserved; F32 min_width,min_height,max_width,max_height; }; //flags bits0..3: explicit minW,minH,maxW,maxH, including maximum0 struct cui_bridge_icon_options_v1 { //256,align4 U32 struct_size,schema_version,flags,size,design_size,reserved[3]; //0..31 F32 custom_size,inherited_text_size,width,height,opacity,rem_size;//32..55 U32 color_rgba,inherited_color_rgba; //56,60 F32 transform[6]; //64..87 struct cui_bridge_icon_style_v1 style; //88..215 struct cui_bridge_icon_constraints_v1 constraints; //216..247 U32 reserved_tail[2]; //248..255 }; //flags bits0..9: customWidth,customHeight,customColor,customInheritedColor, //customOpacity,customTransform,decorative,hasStyle,hasConstraints,debugPlaceholder struct cui_bridge_icon_limits_v1 { //48,align8 U32 struct_size,schema_version,reserved[2]; U64 max_svg_bytes,max_pixels,max_cache_bytes,max_versions; }; struct cui_bridge_icon_info_v1 { //80,align8 U32 struct_size,schema_version,icon_error,reference_count; U64 parse_count,raster_count,cache_bytes,cache_versions,source_revision; U32 source_kind,flags; struct cui_bridge_icon_handle_v1 handle; U64 reserved; }; //source_kind EMPTY0/NAME1/PATH2/DATA3; flags0; revision nonzero struct cui_bridge_icon_bitmap_v1 { //64,align8; pixels copied separately U32 struct_size,schema_version,format,reserved; //format RGBA8=0 U32 width,height,stride,reserved2; U64 required_bytes,revision; F32 paint_x,paint_y,paint_width,paint_height; }; struct cui_bridge_badge_config_v1 { //64,align8 U32 struct_size,schema_version,reserved[2]; U32 variant,size,design_size,flags; U64 count,maximum; U32 color_rgba,reserved2; struct cui_bridge_icon_handle_v1 artwork; }; //flags customColor bit0; artwork{0,0}=named legacy artwork, otherwise owned struct cui_bridge_badge_result_v1 { //40,align8 U32 struct_size,schema_version,submitted,icon_error; cui_bridge_node node; U64 frame_sequence; U32 frame_status,reserved; }; ``` Options cover every `cui_icon_options` scalar and both pointed descriptors; accessible_name is a separately copied string. Style includes all cui_box fields, even those Icon overrides; no second layout implementation. Size vocabulary is INHERITED0/XSMALL1/SMALL2/MEDIUM3/LARGE4/CUSTOM5; errors are the explicit six Icon values0..5, availability UNKNOWN0/CATALOG_NOT_EMBEDDED1/EMBEDDED2. Control/design sizes use separately documented existing C vocabularies, not these Icon numbers. ## Exact proposed function family All names in this section have prefix `cui_bridge_`; A=app*, H=icon_handle_v1, N=existing cui_bridge_node. Except the U32 queries, functions return existing cui_bridge_status. Pointer arguments are synchronous borrowed call arguments, not wire members; all mutable source/config bytes are copied before returning. - `icon_versions(void)->U32` bit0 means the complete owned-resource/utilities group only. Separate future `badge_versions(void)->U32` bit0 means the complete configured-Badge group; its foreign facade requires both. No stubs advertise later Badge functions. `icon_record_size_v1(U32 record_kind)->U32` kinds STYLE0/CONSTRAINTS1/OPTIONS2/LIMITS3/INFO4/BITMAP5/BADGE_CONFIG6/BADGE_RESULT7, unknown=>0. Resource-only implementation exposes only LIMITS3/INFO4/BITMAP5; STYLE0/CONSTRAINTS1/OPTIONS2/BADGE_CONFIG6/BADGE_RESULT7 return0 until their real parser/render consumers are implemented. Their declarations likewise wait, rather than publishing inert records. Each advertised optional group is complete. - `icon_create_v1(A,const limits*,H*)`; `icon_destroy_v1(A,H)`; `icon_get_info_v1(A,H,info*)`; `icon_set_limits_v1(A,H,const limits*)`; `icon_get_limits_v1(A,H,limits*)`; `icon_default_limits_v1(limits*)`. - `icon_set_source_v1(A,H,U32 kind,const char*,U32 byte_length)`; `icon_get_source_v1(A,H,U32* kind,char*,U32 capacity,U32* required)`; `icon_reload_v1(A,H)`; `icon_collect_v1(A,H)`. - `icon_asset_put_v1(A,H,const char* path,U32 path_bytes,const char* svg,U32 svg_bytes)`; `icon_asset_remove_v1(A,H,const char* path,U32 path_bytes)`; `icon_asset_clear_v1(A,H)`. These update a resource-local C-owned copied path map. - `icon_catalog_count_v1(void)->U32`; `icon_catalog_entry_v1(U32 index,U32* is_default, char* name,U32 name_capacity,U32* name_required,char* path,U32 path_capacity, U32* path_required)`; `icon_query_v1(const char*,U32,U32* availability)`; `icon_asset_copy_v1(const char*,U32,char*,U32 capacity,U32* required)`. - `icon_prepare_v1(A,H,F32 width,F32 height,const F32 transform[6],U32* icon_error)`; `icon_bitmap_copy_v1(A,H,bitmap*,unsigned char*,U32 capacity,U32* required)`. Prepare is outside frames only; bitmap is straight RGBA8, packed copied rows, no native pointer/stride borrow. Empty bitmap canonical width/height/stride/bytes0. - `badge_configured_create_v1(A,N parent,const char* key,N*)`; `badge_configure_v1(A,N,const badge_config*,const options*,const char* name,U32, const char* named_icon,U32,const char* artwork_accessible_name,U32)`; `badge_get_config_v1(A,N,badge_config*,options*)`; `badge_copy_text_v1(A,N,U32 field,char*,U32,U32*)` (NAME0/NAMED_ICON1/ART_NAME2); `badge_get_result_v1(A,N,badge_result*)`. Full Badge setter is atomic across records/strings/handle refcounts; config getter returns native values, text getter copies. Count/maximum U64 reject >SIZE_MAX on 32-bit targets, never narrow. Existing make/remove hierarchy, generic child APIs, design enum, node identity, ordinary event FIFO and poststep callback dispatch are reused. Generic node text/visual setters reject this new kind when ambiguous; explicit text setters above avoid accidentally changing the old scalar pill. No new input routing or component manifest entry. New parent admission permits ordinary children and nested configured Badges, preserving each child's rules. ## Validation, bounded owners and error semantics New resource APIs serialize on owner thread and reject during step/render/provider or teardown; existing void app destruction retains its serialized-caller precondition. The resource APIs validate handle generation within the supplied app before state access. The proposed8-byte handle is app-scoped: native C callers must retain the matching app; equal slot/generation pairs from different apps are indistinguishable in C. Foreign opaque resource wrappers retain their owner app and reject cross-app use before C. A C-level guarantee against coincident foreign pairs would require an additional owner nonce/registry and changed record sizes; that is not claimed or smuggled into this proposal. Root may choose that alternative before freezing ABI. Config floats/presence follow actual Icon active-field rules and native conversion bounds, including opacity normalization and explicit maximum0; no NaN-as-presence. Inactive descriptors are canonical all-zero except initialized descriptor headers; inactive transforms/colors/scalars canonical zero. Strings use strict UTF8/no NUL: name/path/accessible/key <=4096 bytes, SVG <=configured max_svg_bytes. `icon_set_source_v1` dispatches exactly to the four C setters: EMPTY requires byte_length0 and calls set_empty; NAME calls set_name (catalog names, paths and aliases accepted exactly by C lookup); PATH calls set_path with the C-owned map loader; DATA calls set_data. No guessed extension, name-to-path rewriting, file lookup or automatic fallback from unknown NAME to PATH. NAME uses C's canonical catalog path for loader lookup; PATH passes its supplied path unchanged to that loader. Empty NAME fails NOT_FOUND; empty PATH/DATA preserve their C empty-source behavior, rather than parsing empty SVG or looking up an empty path. Successful get_source copies the submitted kind/bytes; canonical internal path selection is not a change to the owner's source request. Unknown NAME reports bridge EMPTY, retains old source, and records exact Icon NOT_FOUND for get_info. Other native setter errors map as below. Explicit EMPTY detaches its loader as set_empty does; subsequent PATH/NAME installs the resource-local map loader again. No new status enum: malformed/layout/overflow=>INVALID_ARGUMENT, invalid UTF8=> INVALID_UTF8, stale=>STALE_HANDLE, phase/refcount=>INVALID_STATE, allocation=>OUT_OF_MEMORY, resource budget=>CAPACITY, closed=>CLOSED. Catalog out-of-range=>INVALID_ARGUMENT; unembedded/unknown asset copy=>EMPTY. Operational prepare returns OK plus exact Icon error (including NOT_FOUND/PARSE/LIMIT/ALLOCATION); BADGE likewise exposes icon_error separately. Set-source native failure uses the same status mapping but retains old source; get-info preserves exact last error. Output records remain byte-unchanged on failure. Copy CAPACITY changes only required sizes (both required sizes for catalog); no partial destination writes. Required string size includes terminating NUL; bitmap required is pixels only. Preflight all output/input aliases and capacity arithmetic before copying or native mutation. App-local Icon slots: default8,max128; lazily allocated only after explicit create. Each resource uses C default limits (256KiB SVG/1M pixels/8MiB cache/16 versions), C ceilings1MiB/16M/64MiB/128. Reserve sum configured cache quotas <=64MiB per app, and max_svg quotas plus actual path-map bytes <=8MiB; max128 map entries/resource, max1MiB SVG/entry. Reject overflow/cap before copying; replacement checks peak old+ new source/map copies, not just final bytes. This bounds owned source/mask payloads, not total parser/document/allocator/dependency memory; no joint-process cap claim. Limits/set-source/map replacement leave previous ownership intact on failure. A resource map loader runs only C lookup: copied override first, false falls back to embedded. Put/remove/clear increments source_revision and calls reload. No JS callback or implicit file/network access. Arbitrary deferred C loader callbacks remain unsupported; pre-frame service is a future separately reviewed extension. Each configured node retains one handle ref, source/state reusable across nodes within its app. Foreign cross-app wrappers reject before native calls. Successful config replacement transfers refs once; node removal drops once; destroy rejects reference_count>0 without invalidating handle. App closes release nodes then resources after renderer consumption; a destroyed slot increments its nonzero generation and retires permanently on wrap (never stale-handle reuse). Masks survive all in-flight lists. Auto-collect only after synchronous renderer returns; explicit collect/prepare/destroy rejects any bridge frame in progress. Preparation failure does not authorize early collection. This assumes current synchronous bridge render completion, not arbitrary external async list consumers. Configured render calls cui_badge_ex or cui_badge_with_icon exactly once; the C content callback recurses children once, no foreign call. Structural invalidity has submitted=false and no content; artwork errors preserve submitted shell/content. Store latest frame/result on invocation and finalize frame_status after submission; getter requires invocation in the last attempted frame and unchanged config, otherwise INVALID_STATE. submitted never promises a successful Core frame. No result FIFO or accept/replay operation. Configured artwork stays decorative even if its copied accessible name is nonempty; sole STATUS name is the Badge's name. ## Scope and gates before implementation acceptance This family covers Badge full options plus reusable Icon resources/utilities; standalone configured Icon node and animated spinner presentation remain future facades, explicitly not satisfied by old kind50's name/visual_size. Identity and rotation helpers can be pure host math, validated against C. All five language facades remain individually pending; no source-family completion claim. Required gates: native/WASM record offsets/size/alignment, strict C11/C++ and old header consumers; immutable old Badge/Icon bridge outputs/allocation counts; complete/each-missing optional symbols; full native size_t/UTF8/alias/reserved bounds; resource limits/copy failure/collect/reload/reference/stale/close tests and foreign wrapper cross-app refusal (including coincident numerical handles); old-mask render after source replacement; exact EMPTY/NAME/PATH/DATA setter routing, empty NAME rejection versus empty PATH/DATA, catalog aliases/canonical loader path, unchanged custom path keys, embedded fallback and reload timing; independent ordinary Icon tree RGBA for all Badge variants/sizes/styles/constraints/transforms/alpha; debugPlaceholder bit9 inactive/active on missing PATH and known-unembedded NAME, with preserved NOT_FOUND, no placeholder for PARSE, exact inherited/explicit tint+opacity and unchanged layout/decorative or named semantics (Badge always decorative); count0/max0/overflow, nested interactive content once, resize/omission and separate artwork/frame errors; actual Node/TS app and strict declarations later. Headless private wrapper only. No compile, tests, generation, public declarations or production ran for this doc. --- ## Input Group event checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/INPUT_GROUP_EVENTS_SLICE.md # Input Group event checkpoint Design only, audited at `be4820a6`. No declarations below are implemented. Preserve all 78 families, old entrypoints/options/state/results and their timing. ## Existing state and reduction [Form declarations](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_form.h) expose caller-owned edit model, input behavior/scroll/viewport state and at most 64 borrowed addon descriptors. Base [implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_form.c) validates IDs, labels, geometry and enum values before registering the group and every addon in source order. Button addons call Base Button; other addon kinds register a group. The last activated addon in descriptor order becomes `result.activated_addon`; it is not a chronological action log or a callback. Loading/disabled addons are disabled; input readonly does not independently disable a button addon. After addons, Base calls `cui_base_input_ex` once using the existing hit-test fallback, then attaches input semantics to the group. Input owns actual editing and validation, composition, history, secure redaction and Enter behavior. [Styled](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_form.c) resolves sizes/theme and bounded addon geometry, calls Base once, and paints input/addons. Addon render callbacks are presentation hooks, not built-in addon action callbacks. A custom renderer may compose its own controls; those controls retain their own events. Base Input already has an optional common path in [`cui_base.c`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_base.c) that delivers per-event committed CHANGE and eligible SUBMIT through `cui_base_input_events`, preserving the legacy aggregate. Reuse that exact path instead of inventing a second text reducer or wrapping the entire group with a final-text comparison that loses its ordering. ## Proposed additive API and ordering New `cui_form_events.h` may include Form, shared metadata and Text Input events: ```c typedef struct { cui_component_text_fn on_text; void (*on_addon)(void *, const cui_component_event_metadata *); void *user; } cui_input_group_handler; typedef struct { cui_input_group_result control; size_t addon_count, change_count, submit_count; bool count_overflow; } cui_input_group_event_result; ``` Propose `cui_base_input_group_events` and `cui_input_group_events`, mirroring the old arguments plus handler and returning this new result. A narrow private common Base/Styled path must preserve every validation, hit-test, semantic and paint step. Legacy entrypoints pass no observer. New Base invokes the existing observed Input once when text observation is requested, retaining its exact control/errors and actual counts; missing text handler retains old work and zero text counts. New Styled calls observed Base once and paints once; it must not wrap another observed Styled Input or replay any addon/input reduction. At each existing Button addon interaction, preserve its aggregate boolean and last-addon result write. If its new observer is present, deliver each actual accepted routed activation belonging to that addon, in input order for that addon. Use the same accepted-activation lookup, not queued-event type guessing. Different addons retain descriptor traversal order; all addon notifications precede the nested Input's event-ordered text notifications. Do not sort callbacks across those phases or move them after paint. Missing addon handler ignores user and preserves all legacy flags and child semantics. Custom/text addons have no intrinsic new action; custom child Buttons retain their own API. Text payloads reuse `cui_component_text_event` unchanged: metadata target is the actual nested input ID, CHANGE/SUBMIT and redacted secure text rules match Input. Addon ACTIVATE metadata target is the actual addon ID; caller knows the group from the call/userdata. Preserve genuine accepted snapshot and input facts when available, using honest absent evidence otherwise. No fabricated group activation, old text, request rejection, COMMIT or generic form submit is implied. Observers see the current reducer state before later group semantics and Styled paint. Text count can exceed one; legacy input changed/submitted flags remain aggregates and last-addon remains last in descriptor order. Reading results never replays callbacks or mutations. Applications choose one side-effect path per action. No new handler is retained, no workspace/allocation, no generic routing, network stack or Core change is required. ## Lifetime, suppression and compatibility Input's existing edit acceptance and value-owner model remain authoritative. Notifications cannot reject an already applied edit, consume an input by return, stop propagation or prevent a platform default. Preserve the old treatment of consumed/cancelled activations at each existing interaction seam. Disabled/loading addons and disabled/readonly input retain their distinct existing rules; readonly input is not a blanket addon disable. Passive/inert/layout-only/omitted submission must emit no new callback while preserving old maintenance. Text bytes are borrowed through the callback only; scalar edit snapshots and activation metadata copy by value. Secure payloads remain redacted. Bounded UTF-8 copying uses the shared copy helper. Handlers/users/descriptors/state/model and frame resources must stay live; no active model/state/descriptor/input mutation, recursive submission or context destruction during observers. Unrelated flags and deferred removal after outer call plus renderer consumption are supported. Legacy validation/render hooks keep their old timing and mutation rules; arbitrary host edits in a later custom renderer are not replayed as nested Input events. ## Independent implementation and evidence Before production, review exact accepted-activation and observed-Input forwarding seams. Worker scope: new public header, Base/Styled Form common paths, focused new test, new guide and this checkpoint status. Root owns test/build/WASI/docs registration, metadata and generated distributions/SDK/resources. No Core, old Input reducer or foreign notification schema changes. Tests need paired old/new owner/state/result/focus/semantics/paint checks; multiple addon activations with descriptor-order versus event-index distinction; repeated text CHANGE/SUBMIT and rejected edits; addon-before-input timing; readonly input with enabled addon; loading/disabled addon suppression; custom child action isolation; missing handlers; invalid admission without work; secure redaction; partial edit failure after earlier callback; passive/inert/omitted frames; copied payload and supported deferred removal. Keep existing Form/Input regressions and strict C11/C++ headers, private-wrapper native tests and portable WASI checks. The bridge's existing InputGroup generic text producer and opt-in owning TEXT poll are separate post-step queue contracts. They do not expose these proposed synchronous per-event/addon handlers, rejection or native multiplicity. Binding omissions must remain explicit until independently implemented and tested. ## Approved implementation refinement Use private Base and Styled common functions. Legacy entrypoints pass no observer. After each existing Button addon interaction, preserve its old aggregate flag and last-addon result write, then its existing semantic details. Only then enumerate actual accepted activations for that addon in input order. Copy genuine snapshot when available; if accepted ID is proven but snapshot unavailable, use only actual frame/index/type-source facts, never fabricate activation. No accepted entry means no synthetic callback merely because an aggregate button boolean was true. Addon descriptor traversal still precedes exactly one nested Input operation. When on_text is supplied, call existing `cui_base_input_events` and forward the same handler user, preserving actual per-event counts/control/errors. Otherwise use the old Input entrypoint. Styled calls this observed Base once at its old seam, then performs its unchanged paint/custom rendering once. No hidden workspace, allocation, second reduction, aggregate text wrapper or Core change. Compatibility boundary: current Styled InputGroup does not forward masked or content_type from behavior options into its Input paint options. The event slice must preserve this old paint path for paired equivalence, while secure event payloads inherit the existing observed Base Input redaction. Do not claim secure paint parity. A separate review/fix must audit actual secure paint fields and prove no secret text leaks through draw commands, semantics or selection paths. ## Event compatibility implementation checkpoint Implemented the private Base/Styled common paths and new public event facade, without changing legacy layouts or secure paint forwarding. Tests compare old/new state/results/focus/redraw/semantics/paint, addon traversal versus input order, per-event text/submit counts, rejection/partial failure, IME/undo, masked/password payload redaction, disabled/loading/readonly distinctions, actual inert/layout scopes, custom child isolation, missing handlers, invalid input and deferred omission. Secure Styled paint remains the separate reviewed follow-up; event redaction does not imply visual masking. No binding or full parity promotion. ## Secure Styled InputGroup fix checkpoint (review required) Source audit after compatibility commit `52c6d3d5`. No production implementation of this section exists. The approved event reducer and callback timing remain the baseline; this is a separate correction to existing Styled secure rendering. ### Actual gap and purpose distinction `src/components/cui_form.c` builds `cui_input_options paint_options` without `o.input.masked` or `content_type`, reduces through Base Input, then calls `cui_input_paint`. Base already sets secret/password semantics, configures host text-input purpose and redacts events using the real behavior options. But paint reads actual committed/composition text unless its own `options.masked` is true. Merely forwarding masked is insufficient: `cui_input_paint` consumes a private prepared mask cache and otherwise paints blank. `cui_input_common` in `src/components/cui_components.c` currently owns mask binding, staged checked presentation, masked caret/hit conversion, visual geometry, cache completion and paint. Reuse that path; do not implement a second bullet string builder, fake edit model, post-edit allocation, second reducer or paint raw text as a failure fallback. `masked` alone controls visual hiding. PASSWORD/NEW_PASSWORD with masked=false is intentionally PASSWORD_VISIBLE: actual text remains visible, while semantic value and event text remain redacted. Preserve that public distinction, including secure lifecycle/history/clipboard policy; do not automatically turn purpose into masking. ### Exact private layering and shared seam Recommend two small private headers so Base never depends on components types: 1. `src/base/cui_form_private.h`: declare the existing common Base group operation with an optional synchronous nested-input delegate/user. Delegate signature uses only Base types: context/input ID/name/edit/behavior/options/text handler and returns `cui_input_event_result`. Legacy Base entrypoints use NULL delegate. Delegate runs exactly at the existing nested Input seam, **after** addon traversal/notifications and hit-test fallback construction, before input-parent association. It does not dispatch addon work or paint. No retained registration. 2. `src/components/cui_input_private.h`: declare a shared Styled preparation/reduce helper using existing components options/state types, plus explicit output for final paint options and whether paint is valid/required. It accepts optional full Base behavior overrides, the same text handler, and an observation flag. It returns the exact nested input control/count/error result. Its local mask/hit scratch lives through the one synchronous Base Input reduction; retained mask buffers/geometry continue using the existing resource ownership, not new owners. Factor the existing `cui_input_common` preparation/reduction into this helper, keeping standard Input's order and behavior. Standard Input then paints once when its existing path would paint. Specifically preserve its existing early-invalid no-paint returns versus masked-preparation-error disabled/secret invalid paint. No early `cui_input_paint` may remain in a helper used by InputGroup, or Group would paint twice. No new public API or mask allocator/storage option on InputGroup. Styled Group uses a stack delegate descriptor with its resolved frameless input paint options/theme and temporary `cui_input_state`. Its common Base call selects this delegate only for masked Styled input. Unmasked and purpose-only controls retain the exact event-compatibility path, apart from forwarding explicit paint masked/content_type fields. At the delegate seam call shared Styled preparation and exactly one Base Input operation, then copy result/counts normally. After Base returns, perform the unchanged group/addon layout and one `cui_input_paint` using prepared masked cache and the finalized invalid/placeholder paint options. No symbol from Base invokes components directly; only the optional synchronous function pointer supplied by Styled crosses that seam. Base-only builds have no components link dependency. Core, unrelated public APIs and generated sources stay untouched. If factoring cannot preserve standard Input failure branches exactly, stop for review rather than hiding behavior changes in the helper. ### Behavior override and custom policy The helper must start from the complete supplied `cui_base_input_options`, not silently rebuild a subset. Preserve disabled/readonly/required/invalid, clipboard, validate/user, normalization, delegate_up_down/delegate_home_end, format/workspace, matcher and secure purpose. Use the Group's resolved font, input viewport and scroll for default masked geometry. Forward masked/content_type/format/workspace and relevant validation fields into the shared Styled configuration. Preserve all existing theme/size/design/frameless padding/height resolution; no new public paint configuration is invented. **Explicit custom hit_test:** preserve it and hit_test_user unchanged; its existing contract returns actual model UTF-8 byte offsets, so the caller owns the mapping policy. Distinguish a caller-provided hit test from Group's internally synthesized plain-text fallback: when no caller hit test was supplied, replace that internal fallback with the shared masked visual hit test. Never use real-text width for masked default pointer positioning. Document this responsibility and test custom callback/user forwarding and multibyte returned offsets. **Explicit custom presentation:** recommend rejecting masked Styled Group when `presentation.prepare` or `presentation_complete` is configured, with CUI_EDIT_INVALID_ARGUMENT at the nested-input seam. A mask stage and arbitrary external transactional presentation cannot safely share the existing single presentation slot without a separately designed composition/rollback contract. Do not silently replace the caller's prepare/complete/user/workspaces or call both without engine rollback support. Malformed descriptors retain normal validation; unused user-only fields must not be dereferenced. This is an explicit correction for a previously unmasked visual path, not a new ownership transfer. Base Group, unmasked Styled Group and purpose-only PASSWORD_VISIBLE keep custom presentation unchanged. If compatibility requires composing these policies rather than this narrow rejection, obtain that decision before implementation. ### State, atomic failure and timing Initialize temporary `cui_input_state` from Group's exact behavior and scroll_x. Use the Group's existing tracked input viewport and resolved metrics, not a second persistent state or a new owner ID. Shared preparation/reduction owns temporary hit scratch until it returns; no stack pointer may remain in retained mask state. Copy behavior back immediately after nested reduction, including error paths so focus/composition/secure lifecycle cleanup is not lost. Copy scroll back after existing paint updates it; track the same viewport ID as before. Do not reset scroll each frame. Preserve error/control/count delivery and addon-before-text ordering. Text observers still run inside the existing Base Input reducer before outer Group semantics/paint; no deferred notification or extra reduction. Initial mask preparation or custom-policy rejection must perform no text-event mutation, acceptance callback or text notification. Register a disabled, readonly, secret/invalid textbox using the existing masked Input failure policy and paint fail-closed (empty display if no ready mask); never disclose source text. Preserve the owner's text/revision/selection/history, except documented lifecycle state cleanup already done by the shared path. Do not claim whole-group rollback: earlier addon callbacks already happened and remain counted. During editing, mask staging remains a hard checked presentation gate before acceptance/commit. A failed growth/geometry/format stage leaves the rejected edit's model/revision/selection/history and last good displayed mask intact; no CHANGE for it. Earlier successful events and callbacks remain, first error wins as in Input. Distinguish initial preparation error from later per-event failure. Do not retry or replay events, overwrite errors, or turn failures into raw-text paint. Composition preedit must use the same staged provisional mask and cancellation policy; no secret preedit in draw commands. Security-mode changes retain existing Input lifecycle cancellation and history policy. ### Evidence and test plan Existing references to preserve and reuse: - `tests/unit/test_password_input.c`: masked text, selection/caret, clipboard/history, mask allocation/storage and failure behavior, semantic secret/password state. - `tests/unit/test_password_present.c` and `test_password_engine.c`: checked prepare, borrowed candidate and atomic presentation failure/rollback engine contracts. - `tests/unit/test_input_number_control.c` and `test_input_format_control.c`: masked formatted display, caller storage capacity rejection before acceptance, retained model/selection/paint on error. - `tests/unit/test_input_pointer_selection.c`: actual pointer selection policy and custom hit-test offsets, including masked mode transitions. - `tests/unit/test_input_group_events.c`, `test_form.c`/Base-only and `test_text_input_events.c`: exact one-pass reduction, inherited redaction, callbacks/multiplicity, bounded geometry and baseline aggregate behavior. Add dedicated secure Group cases to the owned focused test (or a new focused test with root registration if approved): prepopulated multibyte secret displays the right bullet count, never raw secret or secret preedit in any text draw command; secret/password semantics expose zero value, correct host HIDDEN versus VISIBLE purpose; actual selection/caret/scroll and pointer hit-test use masked geometry; composition commit/cancel, undo/redo, mode changes and repeated frames stay coherent. Prove purpose-only password stays visibly unchanged while events remain redacted. Compare legacy and observed Styled entrypoints under the **fixed** path, preserving all event counts/order and result fields; retain original unmasked equivalence. Test custom hit_test/user untouched, custom presentation rejected only for masked Styled (no prepare/complete calls, no mutation/text callbacks, fail-closed paint), and unchanged Base/purpose-only custom presentation behavior. Exercise failure before first edit and failure after accepted progress; use existing shared Input caller-storage/allocator fault fixtures for helper staging regressions rather than pretend Group exposes an allocator it does not. Include nonfinite/invalid metrics and missing mask resources without assuming atomic rollback of unrelated addon actions. Verify no double semantics/paint/reduction or stale temporary state. Strict C11/private-wrapper tests: Group events, Form/Base-only, Input events, password_input/present/engine, secure_focus/generation, format/number controls and pointer selection, plus C/C++ headers. Root owns CMake/WASI/docs registration and dist/SDK regeneration. Scope extension requested: `cui_components.c`, the two private headers above, existing owned Form source/tests/guide/checkpoint only. No production changes before checkpoint review; tests described here are planned, not claimed passing coverage of the proposed fix. ### Secure paint implementation checkpoint Implemented shared standard Input preparation/reduction behind two private headers, with the actual Group behavior owner passed through callbacks and one later Group paint. Existing standard Input failure branches retain their paint/return behavior. The Styled common function uses the amalgamation-safe name `cui_form_private_styled_group`; private Base delegation is `cui_form_private_input_group`. Masked custom presentation is explicitly rejected; caller model-offset hit testing is retained. Focused old/facade equivalence covers secret draw/preedit/semantics, purpose-only visibility, custom hit offsets, custom presentation rejection, and one accepted change before format capacity failure. No broader family or renderer parity promotion is implied. --- ## Input grow-width containment: bounded correction Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/INPUT_GROW_WIDTH.md # Input grow-width containment: bounded correction Base `41429b9d72037834af31352cde6113475f317b59`. No Editor changes. The pre-change headless regression confirmed the documented bug: a 255-character value measured 2550px; in a fixed 400px parent the Input frame was 400px but its viewport was 2550px instead of 378px. This is actual geometry overflow, not an unsupported assumption about fitting an unwrapped value. Core `cui_core_axis` maps negative width to Clay GROW, with zero minimum. In the pinned Clay main-axis sizing pass (`third_party/clay/clay.h`, "If the parent clips content ... don't compress children"), a clipped row skips compression. Input's outer clipped row therefore retained its content-sized growing viewport. The component-only correction inserts one anonymous percentage-width row for negative-width single-line Input. That row takes the resolved frame width independently of text; its unclipped flex layout constrains the existing viewport between the existing exact float insets. The frame and viewport both retain their clips, and the text wrapper remains unwrapped. There is no previous-width cap, extra reduction, Core change or public API. Fixed/default-width and multiline composition are unchanged. The extra row costs one layout element per growing single-line field. Frozen upstream `87d10ae5e1299d1be18670a37570c5402f952e34`: `crates/component/src/input/input.rs::render_editor` uses a full-size flex wrapper; `crates/base/src/input/base/element.rs::request_layout` requests relative width 1.0. Its prepaint computes scroll size against current bounds. Do not infer CUI's current-frame scroll behavior from that source behavior. The new passing fixture covers first-frame long text and 400→220→500→180 resizing, column and flex-row/dashboard composition, all three alignments, fractional padding, border/no-border/no-appearance/invalid variants, preserved outer and viewport clip streams, fixed/default widths, and settled scrolled pointer hit / Shift+Home selection. Existing Styled InputGroup with long text retains prefix 40px/suffix56px at widths400/220/500; actual input widths are304/124/404 and its tracked viewport stays within that input. Existing Input and InputGroup event suites remain passing, including their acceptance/history/reduction coverage. No acceptance, IME composition, history or callback implementation changed. ## Remaining same-frame caret limitation Width containment is **not** complete responsive caret/scroll correctness. The opt-in `--probe-caret` requirement fails after this correction: | Frame width | Current viewport | End caret X | Viewport right | Stored scroll | Needed scroll | | --- | --- | --- | --- | --- | --- | | 400 | 378 | 388 | 389 | 2173 | 2173 | | 220 | 198 | 388 | 209 | 2173 | 2353 | | 500 | 478 | 208 | 489 | 2353 | 2073 | | 500 again | 478 | 488 | 489 | 2073 | 2073 | `cui_input_paint` reads `cui_bounds(viewport)` before layout to clamp scroll; Core explicitly returns previous-frame bounds. Merely fixing viewport sizing cannot make that calculation current. Shrink can hide the end caret for a frame; grow can leave excess scroll until the next frame. Selection paint and host IME caret geometry share that stale projection. This probe is intentionally opt-in and failing, not a test that enshrines the defect as success. Any follow-up must be reviewed separately before Core/API work. Existing prepaint supplies current bounds but forbids layout/input mutation; updating scroll state alone does not reposition already-laid-out text/caret or its tracked IME geometry. In particular, `cui_input_paint` receives a stack-local temporary state inside Styled InputGroup: a deferred callback must not retain that state pointer. An architecture proposal must resolve that lifetime and geometry ownership, not silently add an end-frame borrowing requirement to existing APIs. Reproduction is in `tests/fixtures/input_grow_width/README.md`. Canonical registration, source metadata and consumer guidance include the containment test and retain the narrower current-frame grow-caret/scroll limitation above. No full Input parity, browser acceptance or general text-engine completion claimed. Verified on this slice: strict-warning Release and ASan/UBSan builds each pass `input_grow_width`, `input`, and `input_group_events` (3/3) through the private Xvfb wrapper. Formatting and whitespace checks pass. --- ## Frozen Kbd source audit and bounded slice Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/KBD_SOURCE_AUDIT.md # Frozen Kbd source audit and bounded slice Design checkpoint, 2026-10-20; CUI baseline `9d491483`. Frozen upstream kit 0.7.1 checkout `/tmp/cui-upstream-reference` was verified at `87d10ae5e1299d1be18670a37570c5402f952e34`. [Component source](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/crates/component/src/kbd.rs) stores exactly one `Keystroke` (lines 12–17). Constructors accept one stroke. `from_binding` explicitly selects `binding.keystrokes().first()` (105–108). There is no grouped/multi-step shortcut rendering method in this component. The [story](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/crates/story/src/stories/kbd_story.rs) composes independent hints in an ordinary horizontal flex container with gap and wrap. The [frozen guide](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/website/component/kbd.md) also shows ordinary parent composition, one chord per Kbd. The existing manifest already records that “grouped shortcut rendering” has no mapped frozen multi-shortcut API. Modifier formatting tests cannot establish such a contract. This checkpoint does not promote, rename or delete that row; root owns its reconciliation. An invented grouping API would not close a source-backed gap. Actual remaining source features: | Source contract | CUI at this checkpoint | Proposed slice | | --- | --- | --- | | Platform modifier order and special key display (`format`, 111–225) | Existing `cui_kbd_format` orders modifiers and safely truncates UTF-8, but leaves key spelling/case untouched | Add typed one-stroke formatter for common ASCII/special names; preserve old helper | | Appearance enabled by default | Legacy `cui_kbd` always draws an outline | Add `cui_kbd_ex` with normal muted pill default | | `appearance(false)` returns plain formatted text (234–236) | No option | Opt-in `plain`, overriding outline | | `outline()` adds border and changes fill (245–249) | Only outlined legacy presentation | Explicit outline option alongside normal/plain | | Padding X4/Y2, min width20, half theme radius, text12/lineheight1, no shrink (250–259) | Uniform padding4, text0.8*theme font, no minimum | Source-shaped geometry using theme font-size/16 rem scaling | | Host Action/context/focus/global binding lookup (58–108) | CUI command bindings belong to host-owned command model, not upstream Window/Action registry | Remains host responsibility; no simulated lookup or dispatcher | | Unicode first-character uppercase and arbitrary Styled | Existing helper preserves key text | Non-ASCII casing and arbitrary styles remain explicit limits | Proposed additive header `cui/cui_kbd.h`: ```c typedef struct { unsigned modifiers; cui_str key; } cui_kbd_stroke; typedef struct { bool plain, outline, mac_symbols; cui_str accessible_name; } cui_kbd_options; size_t cui_kbd_format_stroke(cui_kbd_stroke, bool mac_symbols, char *output, size_t capacity); bool cui_kbd_ex(cui_context *, cui_id, const cui_theme *, cui_kbd_stroke, cui_kbd_options); ``` The typed key is a strict UTF-8 single line of at most128 bytes. Modifier bits are the existing CTRL/ALT/SHIFT/META constants; parser aliases such as secondary must be mapped by the host. Required-size formatter returns SIZE_MAX on invalid input, supports null/zero-capacity queries, and truncates only complete UTF-8 scalars. Formatting preserves non-ASCII casing rather than pretending to ship a Unicode case database. Rendering submits one noninteractive label with an optional explicit accessible name; it never handles input. No new global architecture, allocations or retained state are required. New base/component `cui_kbd.c` files avoid edits to shared content/components sources and preserve the legacy function and formatter byte behavior. Root must register those sources and the new header/test in canonical metadata/build lists. A standalone worker fixture can compile the new sources against the unchanged portable library. Proposed tests cover source key-name matrix, scalar-safe capacities, validation, normal/outline/plain draw geometry and software pixels, semantics/no activation, theme scaling, ordinary row-group composition, and source-owned lifetimes. A guide example must compile as C11. No claim of complete Kbd parity or runtime validation is made by this audit. --- ## Lifecycle and result observer checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/LIFECYCLE_RESULT_EVENTS_SLICE.md # Lifecycle and result observer checkpoint Original design audit at `ea5a3e40`; the Base and Styled hover observers are now implemented, as recorded at the end. Other proposals remain unimplemented; no metadata promotion or new manifest family. Read with the [remaining audit](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_REMAINING.md), [contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_CONTRACT.md) and [scroll checkpoint](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SCROLL_EVENTS_SLICE.md). Existing headers remain authoritative. No build/test was run for this document; linked assertions are existing source evidence, not fresh verification. ## Disposition without erasing gaps | Family | Current useful contract | Remaining absence and recommendation | | --- | --- | --- | | Focus Trap | Caller-owned overlay open state plus Core focus-scope bracketing and input-close bool. | No typed overlay open/close observer. Scope begin/end itself is a justified primitive exception, not a retained lifecycle. Optional operation observers would be real additive work; do not call existing bool an event facade. | | HoverCard | Caller `cui_hover_state`, delayed open policy, paired begin/end when composed; child controls own their events. | Genuine gap: no typed model-open observer. Propose separate Base then Styled observation, explicitly not visibility/render completion. | | Tooltip | Same delayed state but no interactive content hold; complete-call text composition and trigger description. | Genuine gap: no typed model-open observer; share typed payload with HoverCard while preserving distinct timing/children. | | VirtualList | Typed error/view/scroll_changed/window_pending results and visible-row callback. | No final-offset observer for the whole virtual operation, but no demonstrated missing asynchronous completion lifecycle. Keep window completion result-only; a future offset adapter is separate, not implemented by the Scrollable facade automatically. | | MessageScroller | Typed double-precision view, changed/jumped/opacity/wake results and explicit model operations. | No precise final-offset/tail-transition observer. This remains an optional real gap; current result is sufficient for immediate inspection, but is not equivalent to a notification. No message-delivered/read or render-complete lifecycle exists. | The user objective does not require identical event categories on every family. These distinctions justify preserving useful result APIs; they do not relabel missing callbacks as implemented. No generic queue, scheduler or Core lifecycle registry is proposed. ## Recommended decision for the original event objective **Implement bounded HoverCard/Tooltip model-open observers next** if closing the remaining interactive lifecycle gap is part of this batch. Their delay, suppression and placement policy changes state inside the component; a caller should not need to reconstruct that transition from composition bool. This is a real missing API, not a render-only exception. Base then Styled can be independently reviewed; no visibility, animation-completion or foreign callback claim is required. **Accept Focus Trap scope bracketing and virtual-window completion as explicit exceptions**, subject to root review. Scope begin/end already express caller-owned composition, and virtual result pending describes this call's rendered window; neither owns a lifecycle request to complete. Do not manufacture callbacks merely for symmetry. Overlay operation metadata is a reasonable later enhancement, outlined below, but is not required to make the trap primitive usable or to cover the original Button/Input/control/menu/dialog objective. Accepting this exception must not be described as an implemented typed overlay facade. **Keep MessageScroller result-only for this batch**, explicitly recording the missing exact offset/tail observer as deferred, not implemented. Its broader `changed` result cannot substitute for that observer. A separately requested scroll notification objective would require the double-precision slice below; it does not require a fictional message/render completion lifecycle. Virtual final-offset observation is likewise a separate deferred scroll feature, not closed by the Scrollable pair. These are documented scope decisions, not parity promotion or a claim that all lifecycle categories now exist across 78 families. ## Focus Trap: explicit overlay operations versus scope lifetime [`cui_overlay.h`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_overlay.h) is the public Focus Trap surface. [`cui_overlay.c`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_overlay.c) implements these exact seams: - `open`: nonnull context/state, nonzero overlay ID, currently closed; remembers explicit trigger or current focus, sets open, clears previous bounds, invalidates. Already-open calls do nothing. It does not begin a scope or paint anything. - `close`: currently open; clears open, restores eligible trigger focus or clears focus, invalidates. It does not end an active scope, destroy UI or prove that a panel was painted. No retained listener exists. - `update`: caller runs after frame begin, innermost overlay first, before controls. It skips consumed events, scans in order and closes on the first eligible nonrepeat Escape targeted at the overlay, or eligible outside pointer down against previous panel bounds. Modal outside requires owner target; nonmodal outside does not. Returns true only for that input-driven close. It does not explicitly consume the closing event; preserve Core modal routing and focus restoration rather than adding consumption through an observer. - `begin`: open flag plus successful Core focus-scope begin, with no layout; `end` pops that scope. Pair only if begin succeeded. Omitted begin cannot create a new trap, but does not clear application `open`. Frame omission is not close. [Core scope implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/core/cui.c) can register an inactive inert scope while still requiring a matching end; focus behavior is separate from box layout/paint. Do not globally promise inert/layout-only operations never mutate application overlay state. `update`/`open`/`close` are explicit operations, and policy/focus eligibility remains the existing Core contract. Zero frame evidence cannot identify a unique passive frame or an OS focus event. [`test_overlay.c`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_overlay.c) meaningfully asserts nested Tab/Shift-Tab and disabled-child skipping, inner-first Escape, consumed Escape / outside suppression, modal opener isolation, nonmodal behavior, and restoration to missing/disabled trigger fallback. First open has no previous panel bounds to outside-dismiss. It does not prove every passive/protected phase or retained lifecycle because no retained listener exists. A narrowly reviewable **optional overlay-operation slice** could add `cui_overlay_open_events`, `cui_overlay_close_events`, `cui_overlay_update_events` with typed `{event, previous_open, open, reason}` and one borrowed handler argument. Reasons would distinguish EXPLICIT_OPEN, EXPLICIT_CLOSE, ESCAPE and OUTSIDE, not invent acceptance/veto/destruction. Each observes an actual transition after existing focus restoration/invalidation. Preserve update's exact legacy bool as a separate `control_result`; missing handler still mutates, repeated no-op stays silent. A private update seam can freeze the matched event index/type before closing; do not rescan after observer mutation or infer activation snapshots from pointer down. Explicit operations have PROGRAMMATIC origin without invented input; input update uses only genuine index/frame/source when available. Frame-zero observation should report maintenance result but suppress callback, consistent with the approved scroll policy. Out-of-frame explicit-operation policy must be reviewed separately: preserve old allowed operations and diagnostics rather than pretend zero means a known passive frame. Do not add callbacks to scope begin/end: those calls bracket composition, do not own the panel, and repeat every submitted open frame. An OPEN callback on each successful begin would be false multiplicity; end is not CLOSE. Surface's retained completed-close observer is a different API, not a second overlay notification to chain automatically. No new Styled Focus Trap layer is necessary. ## HoverCard and Tooltip: model-open is not actual visibility The [public hover contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h), [pure Base policy](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_content.c) and [Styled panel helper](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_content.c) establish: - State is caller-owned `{open,pending,target,suppressed,elapsed}`. Pure update returns only old-versus-final `open`; pending/elapsed-only changes return false. Positive finite dt advances delay; invalid/nonpositive dt does not. Invalid or negative delay becomes zero. Repeated calls advance according to supplied dt; there is no automatic once-per-frame time accounting. - Disabled or Escape resets state immediately; Escape suppresses reopening until trigger, focus and content inputs are all absent. Otherwise target is trigger hover or focus, plus content hover only while already open. Pending reversal restarts elapsed. This is delayed state policy, not animated exit completion. - Styled helper scans all frame key events for Escape without checking consumed, repeat, target or modifiers. Preserve this observable difference from Overlay update; an observer must not silently “fix” input filtering. Trigger focus opens; HoverCard also holds open for panel hover or focused descendant whose preceding bounds are contained by the previous card bounds. Tooltip does not use that hold. - The trigger must already be submitted; placement uses preceding-frame anchor bounds. Invalid viewport or missing/empty anchor can force `state.open=false` after pure update. Measurement resource allocation can fail with `open=true` while helper returns false. Thus legacy false is not simply “closed”, and true means panel composition/pair admission, not completed presentation. - Tooltip composes text and closes its own portal, adding trigger description semantics. HoverCard begin opens portal plus inner content box and returns true before arbitrary children; end only closes them. No modal focus trap is added. Intrinsic measurement is context-owned, tracks child bounds and schedules a collision-placement redraw; no caller content callback is retained. Omission freezes caller hover state: it does not advance delay, close, dispatch or retain a synthetic late callback. A stale `open=true` after omission is model state, not proof of a visible panel. Inert/layout-only work can still run policy maintenance; do not infer user visibility from it or add observers in protected measurement/paint phases. Existing public frame-zero limitations still apply. [`test_content.c`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_content.c) tests pure delay/suppression/ invalid dt; Styled pointer timing, card-versus-tooltip content hold, Escape, trigger-focus opening, disable close, trigger description/parent/tab semantics, explicit and intrinsic geometry, wrap/viewport collision, bounded height and measurement redraw settling. Its closed/omitted-content assertions demonstrate missing bounds/resource lifetime, not an automatic omission-close callback. No current tests establish typed observer order, passive suppression, allocation failure events, callback mutation or every consumed-Escape variant. Recommend two independent slices, with no new shared Core mechanism: 1. **Pure Base hover observation:** `cui_hover_update_events(target, state, ..., handler)` preserving all current parameters and reducer bool in a typed result. Payload `{event, previous_open, open}` is pointer-free, kind LIFECYCLE, source UNKNOWN, without context/frame/index evidence: input booleans are caller facts, not physical events. One aggregate callback only for actual `open` transition; pending/elapsed changes remain result/state inspection. This is notification, not controlled rejection. Optional handler/user are borrowed only through call. 2. **Styled final-model observation:** `cui_tooltip_events(...)` observes after the whole old call; `cui_begin_hover_card_events(...)` observes after the old begin decision and before returning to arbitrary children. Result separates `control_result` (legacy pair admission) from actual open change and callback count. Caller ends only on true admission, even if no callback occurred. Capture entry state, invoke legacy once, then compare final model after placement/error fallbacks; never call a Base observer internally and notify twice. Suppress callbacks for zero-frame/protected work while preserving old maintenance. Do not name payload “visible” or promise pixels/geometry settled. Closed→opened→ forced-closed in one call is aggregate net-zero, not a displayed open/close pair. Already-open→composition-failure can be no model change despite false return. A reason enum would require narrow internal policy instrumentation; omit reasons initially rather than infer Escape/disable/geometry from final bool. Genuine frame only, UNKNOWN source and no index/HAS_ACTIVATION for Styled aggregation. End has no new lifecycle event. Content remains arbitrary child composition, not notification. Callbacks may update unrelated app state only; active hover state/options/trigger/ input mutation, recursive submission or context teardown is unsupported. Handlers are not retained across pending delay or omission. Pointer-free payload copies outlive callback; borrowed text/children retain their existing frame obligations. This adds no “will open” veto, confirmed close animation, disposal or OS event. ## VirtualList: result-only window state is a justified exception [Public result](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_virtual_scroll.h), [Base](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_virtual_scroll.c) and [Styled](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_virtual.c) distinguish reduction from callbacks. Base resolves extents, reduces scroll/owner keys and computes view. Styled renders that window/overscan, then processes child-deferred scroll and translates current viewport. Main-axis deferred movement sets `window_pending` and invalidates for next-frame row composition; returned view still describes the rows just rendered. Cross-axis change can set `scroll_changed` without main-axis pending. [`test_virtual_styled.c`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_virtual_styled.c) asserts precise wheel/key/scrollbar behavior, disabled behavior, visible-row semantics/geometry, software rendering and the pending-then-stable deferred sequence. Empty-model normalization is also asserted. These do not establish async data or presentation completion. Rows and measurement users are borrowed during composition; keys/ heights cannot change in row callbacks. Model state outlives use, not a retained completion listener. Omitted widget produces no new result/callback and cannot “finish” a previously retained request that does not exist. Keep `window_pending` result-only: false is no new pending deferred change in this call, not a completed generation or finished GPU frame. A retained completion hook would require new request/ownership architecture. Repeating row composition in finish would change callback multiplicity. A later useful final-offset observer must wrap the whole virtual Base or Styled operation and retain the existing view/ error/pending result separately; generic Scrollable events miss virtual owner keys or duplicate internal finish if naively composed. This observer remains absent; no claim that result-only covers all application notification needs is made. ## MessageScroller: retain exact results; precise observation is separate work [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_message.h), [Base](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_message.c), [Styled](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_message.c), and [tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_message.c) establish double offsets/totals, explicit append/prepend/splice/measurement, anchoring and following-tail. Application owns message records; opaque state retains only bookkeeping. Row renderers run for visible rows plus overdraw; collection/state must remain stable through end_frame. Base learns prior rendered row bounds, lays out/anchors/clamps, then captures its local old scroll; input/bar/jump actions and opacity transitions follow. `changed` includes row measurements and jump/fade animation, so it is not a scroll event. Styled width can remeasure before Base and tracked bounds feed later calls. There is no virtual-style deferred finish/window_pending or data-delivery generation. Tests assert prepend/measurement anchor behavior, tail following, bounded row work, precise wheel, edge consumption, Home, jump action, reduced-motion/opacity/wake and invalid options. They do not assert a missing offset observer or completed render. An optional later slice could expose a separate double `{previous,value}` offset observer around the whole model operation, plus a distinct `{previous,value}` following-tail transition if applications need it. Snapshot must precede layout reconciliation; never float-cast `view.scroll` or use `result.changed` as its condition. Preserve existing result exactly. Programmatic append/tail/remeasure changes, passive work and between-frame calls need an explicit notification policy before implementation; handlers must not be invoked by retained row-bound writes. No message-received/read, network, render-complete or paint lifecycle is implied. ## Review/test gates before production Each proposed slice needs separate ownership approval and a signed, strict C11/ C++ header/test commit, with native CTest through the private-display wrapper. For Overlay: repeated explicit operations, inner-first input, consumed/repeat/ outside/first-bounds rules, focus restore ordering, omitted/passive operations and old/new behavior comparisons. For hover: timer/reversal/suppression, repeat calls, consumed/global Escape preservation, focus/child hold, fallback final-state/net-zero, allocation failure, no callback from omission or frame-zero work, callback ordering before arbitrary HoverCard children, correct begin/end balancing, copied payload and no retained user pointer. For any future virtual/message observer: exact final state versus rendered view, deferred window and double precision/anchor/tail proofs. Do not change Core input policy or retime callbacks to satisfy a generic vocabulary. Bindings expose none of these proposed immediate handlers; existing queued bridge allowlists stay unchanged. A new C payload alone does not add owning foreign views, synchronous request hooks or async completion. Browser checks stay headless and private Xvfb proof does not establish hardware/native-session behavior. ## Proposed ownership for the next reviewed work Base hover slice: new `include/cui/cui_hover_events.h`, narrow `src/base/cui_content.c` additive entrypoint, new `tests/unit/test_hover_events.c`, new `docs/HOVER_EVENTS.md` and this checkpoint status only. Prefer new-header discovery over modifying legacy public layouts. Pure Base arguments remain exactly the existing `cui_hover_update` input values plus explicit target and handler; no context or retained callback is added. Styled follow-up after separate review: additive declarations in that new events header, narrow `src/components/cui_content.c` entrypoints/common seam, new `tests/unit/test_hover_styled_events.c`, guide/checkpoint status. Existing `cui_content.h` discovery can be considered explicitly; no layout additions. Preserve helper failure/begin-end behavior, measurement storage, trigger semantics and old functions. Root owns CMake/source manifests/generated distributions and bindings for both slices. Core/overlay/virtual/message code is outside ownership. Base tests should prove exact legacy state/bool sequence equivalence across opening/closing/reversal/suppression/disabled/invalid timing, actual callback counts, missing handler, repeated same-state calls and copied metadata with no fake frame. Styled tests add pointer/focus/inside-card behavior, global consumed/repeat Escape legacy equivalence, placement/anchor failure and net-zero fallback, allocation failure where deterministically injectable, passive suppression, composition admission separate from open change, old/new paint/semantics/geometry, callback order and borrowed lifetime. No platform desktop is needed for these tests. ## Implemented Base hover slice `cui_hover_events.h` now exposes `cui_hover_update_events`, `cui_hover_lifecycle_event` (`event, previous_open, open`), borrowed `cui_hover_handler` and `cui_hover_event_result` (`valid, control_result, count_overflow, change_count, changed`). It preserves the pure reducer once, validates nonzero target/state before work and reports actual open transitions only. UNKNOWN metadata has no context/frame/index/source-presence/activation/reason. Disabled pure close is eligible notification. Read [HOVER_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/HOVER_EVENTS.md) for examples, timing, copies and unsupported mutation. Styled names in this checkpoint remain proposals; no Core/overlay/virtual/message behavior changed. The unreleased Base result now has explicit `changed = previous_open != open`, independent of handler/count. Base `control_result` is the same legacy transition bool; future Styled `control_result` remains composition admission. Tests assert that absence of a handler does not erase the applied transition. Consumers rebuild for this additive unreleased layout change. ## Implemented Styled hover slice `cui_tooltip_events` and `cui_begin_hover_card_events` now wrap each legacy call once and observe final open model after placement/resource decisions, before arbitrary HoverCard children. `changed` is independent of `control_result` admission and handler/count. Metadata is UNKNOWN with genuine nonzero frame only; frame-zero/protected maintenance remains observable in results with no callback. No Base observer is invoked internally. The guide and focused old/new geometry, semantics, failure, omission, input-policy and protected-phase tests document the implemented limits. Original Focus Trap and virtual/message dispositions remain unchanged; no visibility, allocation rollback or completion promise was added. --- ## List and ToggleGroup typed transition slice Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/LIST_EVENTS_SLICE.md # List and ToggleGroup typed transition slice Design only, audited at `dccb02f2`. Choice sources are currently owned by the Dropdown worker; implementation requires their completed changes and root review. Keep Tabs, popup policy, input dispatch and bridge schemas outside this slice. ## Evidence and current behavior - [Public choice types](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h#L120): ToggleGroup borrows a bool array, List single borrows a stable `cui_id` owner, List multi borrows bools. `cui_list_state.active` is the independent navigation cursor; it is not selection. - [ToggleGroup reducer](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_choice.c#L490) registers BUTTON items, processes unconsumed events in order, toggles the cursor item on activation, applies `allow_empty`/`multiple`, navigates/focuses, then updates semantics. In single mode selecting a new item clears all bools before setting that item. Caller arrays can initially contain several true values; do not silently add normalization. Its bool means some accepted mutation occurred, including toggling back to entry, not final-array inequality. It has no legacy callbacks. - [Private List loop](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_choice.c#L614) handles scrolling, scope, disabled/consumed events, secondary highlighting and Escape. Activation writes selected ID and active cursor, then calls `on_activate`, then `on_confirm`. `on_confirm` receives the configured secondary-modifier interpretation. Same-ID confirmation still invokes both callbacks and returns activated=true, although it need not change selection. `on_cancel` handles nonrepeat Escape independently of activation/selection, including an empty scoped list. Navigation/typeahead changes active/focus/window without writing selected ID. Scroll-window changes discard stale pointer-up activation. Final semantics follow the whole loop. - [Existing selection forwarding](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_choice.c#L690) snapshots the prior owner, captures available input metadata, performs activation and the old callbacks, then reads the final owner and emits typed CHANGE only if different. [Select](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_choice.c#L1279) and [Combobox](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_choice.c#L1444) use this seam; typed delivery precedes their existing close/paint policies. Combo's ordered editor/reducer path has its own forwarding, and must not be rerouted through a second List pass. [Simple Menu tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_simple_menu_events.c) exercise the sibling per-command ACTIVATE seam, including repeated same-ID activation; command activation is not selection CHANGE. - [List multi](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_choice.c#L1095) installs a synchronous activation adapter that flips the matched bool **before** the user's old `on_activate`; it forwards confirm/cancel with original userdata. Final multi semantics are patched after the List pass. Its return is activation, even two flips net zero. Do not observe the temporary internal single action ID as multi selection. - [Styled List](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_choice.c#L1137), [multi](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_choice.c#L1459) and [ToggleGroup](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_choice.c#L898) reduce once before paint. List resolves scroll receiving geometry and design metrics first. Rendering callbacks borrow item/index; indices are relative to the displayed array. Existing tests establish these contracts: [multi selection and two same-item flips](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_choice.c#L340), [confirmation/secondary/cancel ordering](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_choice.c#L3086), [Select per-transition net-zero and missing activation snapshot](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_select_events.c), and [ordered Combo events](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_combobox_events.c). Preserve them. ## Smallest independent API A separate `cui_list_events.h` includes `cui_choice.h` and existing shared selection types; no edits to old options/state layouts. Single List reuses `cui_selection_change`/`cui_selection_handler` and its existing per-transition private seam, rather than wrapping a whole-frame bool. Add explicit compound ID to the new Base signature because the old Base List has no container parameter. ```c typedef struct { cui_selection_event_result events; bool legacy_activated; /* Original bool, not final owner inequality. */ } cui_list_event_result; cui_list_event_result cui_base_list_events(cui_context *, cui_id control, const cui_choice_item *, size_t count, cui_id *selected, cui_list_state *, cui_list_options, cui_selection_handler); cui_list_event_result cui_list_events(cui_context *, cui_id container, const cui_theme *, const cui_choice_item *, size_t count, cui_id *selected, cui_list_state *, cui_list_options, cui_selection_handler); typedef struct { cui_component_event_metadata event; cui_id item; /* Item whose bool changed. */ cui_id trigger_item; /* Activated item causing this operation. */ bool previous, value; } cui_choice_item_change; typedef void (*cui_choice_item_change_fn)(void *user, const cui_choice_item_change *event); typedef struct { cui_choice_item_change_fn on_change; void *user; } cui_choice_item_handler; typedef struct { bool valid, submitted, legacy_result, count_overflow; size_t change_count; /* Actual typed calls; can exceed activation count. */ } cui_choice_items_event_result; cui_choice_items_event_result cui_base_list_multi_events(cui_context *, cui_id control, const cui_choice_item *, size_t count, bool *selected, cui_list_state *, cui_list_options, cui_choice_item_handler); cui_choice_items_event_result cui_list_multi_events(cui_context *, cui_id container, const cui_theme *, const cui_choice_item *, size_t count, bool *selected, cui_list_state *, cui_list_options, cui_choice_item_handler); cui_choice_items_event_result cui_base_toggle_group_events(cui_context *, cui_id control, const cui_choice_item *, size_t count, bool *selected, cui_toggle_group_options, cui_choice_item_handler); cui_choice_items_event_result cui_toggle_group_events(cui_context *, cui_id container, const cui_theme *, const cui_choice_item *, size_t count, bool *selected, cui_toggle_group_options, cui_choice_item_handler); ``` Single List's `legacy_activated` preserves its activation bool. The bool-array result uses `legacy_result` because List multi returns activation while ToggleGroup returns accepted change; neither proves rejected activation. Preserve each original meaning without an invented acceptance counter. Missing callback accepts/ignores user and still writes owners. Actual callback counts saturate with `count_overflow`, following shared conventions. Single List must keep its existing order: owner write -> legacy activate -> legacy confirm -> typed selection CHANGE; cancel remains on its old independent branch. Same-ID confirmation emits no CHANGE unless old callbacks actually redirect the owner. Do not replace confirm/cancel with SUBMIT/LIFECYCLE, add a second dispatch, or change when popup adapters act. Options' old callbacks and typed handler may coexist; no arbitrary conflict-preflight is needed for this independent observer. Retain old callback arguments/userdata and permit their existing owner-update behavior. As with current Select, typed payload reads the final owner after those callbacks; writes elsewhere by user callbacks are not automatically observed. List multi needs a real typed hook in the private activation/adapter path: capture that item's previous bool immediately before its reducer flip, preserve legacy activate/confirm calls, then read that item's final bool and emit if different. Do not dispatch from the adapter before legacy confirm, nor infer bool transitions from action IDs after the full pass. Repeated toggles deliver true/false in order, even when final array equals entry. Legacy callback redirects may cancel the item's net transition; unrelated legacy array writes get no fabricated events. ToggleGroup needs a private common reducer, with the old entrypoint using its unobserved path. On single-mode selection emit each actual true->false clear in array order at its real write, then the chosen false->true write; skip false->false stores. `trigger_item` identifies the activated cause for cleared siblings. In multiple mode emit only that item's actual flip. `allow_empty` rejection emits nothing. Callbacks can observe an intermediate array during the clearing loop; this is a new per-write observer contract, not an atomic whole-array snapshot. Preserve old navigation/focus/consumption and paint after all reduction. No heap copy or aggregate compare is needed. Single List, multi List and ToggleGroup can land as separately reviewed/tested slices. ## Metadata, ownership and limitations Only ordinary active, enabled submissions notify; disabled/inert/layout-only paths retain their exact old behavior without typed calls. Preserve event order. At a real transition capture shared CHANGE metadata with compound control target, current frame/index and source only when established from the accepted event. Use an activation snapshot only if the existing API actually supplies it; List registers semantics after reduction and existing Select tests explicitly lack HAS_ACTIVATION. Fall back to truthful frame/index/source, never synthesize a snapshot or claim a physical origin from selection values. Sibling clear events share the causal input metadata; their `item` differs from `trigger_item`. Navigation-only focus/typeahead/scroll changes are not selection transitions. List OPTION is focusable in existing routing, but [Core's accessibility ACTIVATE allowlist](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/core/cui.c#L1245) does not include ordinary OPTION (unless explicit pointer-activatable details already apply). Test actual queue rejection; do not relabel options as buttons or claim new accessibility activation parity. Menu-mode MENUITEM and ToggleGroup BUTTON have different supported activation contracts. Secondary highlight is not CHANGE; confirm modifier semantics remain legacy. No general bubbling or input routing. Payloads contain stable IDs/bools and are pointer-free copies, not array indices or item pointers. Handler/user borrow only this synchronous submission. Descriptors, labels, state and selected arrays must remain alive and retain ordering/identity through reduction, legacy callbacks, custom rendering and renderer consumption. During typed callbacks forbid owner/array/state/model mutation, item insertion, removal/reorder, recursive submission, storage/context destruction and foreign unwinding. Unrelated application state may change; defer edits/teardown until submission and renderer consumption finish. Legacy callback timing is preserved, not broadened into permission for arbitrary destructive legacy operations. No retained registrations or unsubscribe/teardown architecture is introduced. ## Regression plan and omissions Use real queued pointer, key and supported accessibility input. Check each transition and copied payload, including single A->B->A, repeated same-item confirmation, multi double flip and ToggleGroup multiple initially-true values cleared before the new selection. Assert legacy activate/confirm/cancel trace and userdata, including owner redirects, nil typed observer, consumed events, allow_empty rejection, disabled items/parents, inert/layout-only and empty lists. Exercise roving focus, typeahead, window scrolling plus stale pointer-up, secondary modifiers/highlight and empty scoped Escape. Compare legacy/new bools, owners, states, semantics/focus, visible windows and custom/default paint. Keep Select/Combo/Simple Menu regressions unchanged to prove private seam compatibility. Run strict C11/C++ checks and private-display wrapper tests after implementation. No new Select-multi/Combo-multi/chip-removal facade or binding schema in this first proposal: their filtered/scratch arrays and removal paths require separate stable-ID mapping audits before forwarding these bool events. Existing bridge legacy change queues and Python/Node/Go/Rust wrappers remain unchanged. Native typed APIs do not imply typed binding selection payloads or new accessibility support. ## Implementation checkpoints Single List now exposes the existing per-transition private hook through Base and Styled facades. Its narrow Styled common seam retains direct legacy reduction and paint; existing Select/Combo/Menu forwarding is unchanged. New typed callbacks retain the existing selection-forwarding ability to consume later input events, without permitting active owner/resource mutation. Multi List now captures bool facts at the real private activation path, after which legacy activate/confirm retain their original timing and the final item bool is observed. New facades preflight the required compound ID before paint. ToggleGroup now has a private common reducer and immediate per-write events, with sibling clears before the chosen value and no workspace. New tests compare real legacy/new reducers, callback traces, copied payloads, intermediate arrays and semantics/paint; existing Choice/Select/Combo/Simple Menu/Dropdown/Tabs regressions remain unchanged. --- ## MenuTree command observer checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/MENU_COMMAND_EVENTS_SLICE.md # MenuTree command observer checkpoint Status: reviewed checkpoint, audited at `4ecd73dd`; the Base/Styled MenuTree subset is now implemented in [MENU_EVENTS.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MENU_EVENTS.md). This narrows the [event contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_CONTRACT.md) to Base/Styled MenuTree command observation. Simple Menu, ContextMenu, Dropdown and other forwarding remain later slices. No Core/surface change, ledger promotion or complete Menu family claim is proposed. ## Existing contract and evidence - [Public descriptors/state/options](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h): caller owns action output, tree state, descriptor tree, check bools and radio integers. IDs must be globally unique throughout the tree. Render slots borrow users/resources; no command callback exists on MenuTree. `cui_base_menu_tree` returns an aggregate bool, and `cui_menu_tree` forwards that bool after drawing. - [Base reducer](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_choice.c), `cui_base_menu_tree`: ordered input loop resolves the active level/item, navigation/typeahead, submenu opening, depth limits, scroll/drag invalidation, and command activation. At its command branch it updates active/depth, toggles CHECK or assigns RADIO, writes `*action`, applies close policy, sets `activated_any`, then returns immediately if closed or continues if still open. ACTION normally closes; CHECK/RADIO stay open only with `keep_open_checks`. Repeating a check can toggle twice; assigning the already-selected radio option is still a command activation. No equality check suppresses commands. - `cui_menu_entry_is_disabled` excludes explicit disabled entries, labels/separators, CHECK without storage, RADIO without storage, and SUBMENU without children. Opening a submenu is navigation, not committing that submenu as a command. Raw local activation and keyboard redirection establish the reducer decision; they are not proof of an already accepted current Core activation snapshot. - [Styled renderer](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_choice.c), `cui_menu_tree`: validates existing geometry/theme arguments, sets drag policy, calls Base once, draws trigger, retains metrics, and paints open levels. Entry semantics are registered by later `cui_base_menu_entry`/paint work. Do not move registration to obtain earlier evidence. - [Choice tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_choice.c), `test_menu_tree`: two Enter events toggle the same CHECK twice in one call while only bool=true and the final action ID survive. Tests also establish radio mutation, nested navigation/escape, depth/focus restoration, hover opening, parent check activation, role/checked snapshots, typeahead and disabled close. `test_menu_depth_bound`, `test_menu_configuration`, `test_hierarchical_menu_scroll`, `test_menu_pointer_drag_scroll`, `test_menu_check_glyphs` and `test_menu_popup_paint_composition` establish other retained behavior. These are legacy proofs, not typed event/lifetime coverage. Core's existing accessibility ACTIVATE allowlist includes MENUITEM, MENUITEMCHECKBOX and MENUITEMRADIO (unlike OPTION). A new fixture can therefore prove genuine menu accessibility input without a Core extension, but still must not fabricate an accepted snapshot before current semantic registration. ## Compare two possible seams | Approach | Preserves existing reducer? | What it can truthfully deliver | | --- | --- | --- | | Aggregate-last wrapper around existing bool/output | Yes, if purely observed after return. | At most “this call activated something; final action output is X.” It cannot recover each command, repeated same-ID commands, check/radio intermediate mutations, or each input index. Calling that one event a per-command ACTIVATE would misrepresent multiplicity. | | Private per-command hook at the existing commit branch (recommended) | Yes, with no replay, early registration, new veto path or close-policy rewrite. | One synchronous ACTIVATE notification for every command branch actually reached, including repeated same ID, plus genuine input facts captured before mutation/close. Closing commands still terminate the existing loop; keep-open commands preserve the remaining event sequence. | The aggregate-last exception is unnecessary here: the single commit branch is narrow and already establishes the command ID. Do not reconstruct events from final `*action`, state getters, a post-frame queue, or check/radio equality. Aggregate bool/output remain unchanged compatibility results beside new observer bookkeeping. ## Proposed additive API New Base-dependent `cui_menu_events.h` contains common metadata and pointer-free command payload/handler/result. It does not depend on Components or expose descriptor pointers. Existing `cui_choice.h` declares Base/Styled forwarding functions. Proposed exact names/layout: ```c typedef struct { cui_component_event_metadata event; /* ACTIVATE, target=public trigger */ cui_id command; /* actual committed leaf entry ID */ } cui_menu_command; typedef void (*cui_menu_command_fn)(void *user, const cui_menu_command *command); typedef struct { cui_menu_command_fn on_activate; void *user; } cui_menu_command_handler; typedef struct { bool valid, submitted, count_overflow; size_t command_count; /* actual observer invocations */ bool legacy_activated; } cui_menu_command_result; cui_menu_command_result cui_base_menu_tree_events( cui_context *, cui_id trigger, cui_str name, const cui_menu_entry *, size_t count, cui_id *action, cui_menu_tree_state *, bool disabled, float dt, bool keep_open_checks, cui_menu_command_handler); cui_menu_command_result cui_menu_tree_events( cui_context *, cui_id trigger, const cui_theme *, cui_str name, const cui_menu_entry *, size_t count, cui_id *action, cui_menu_tree_state *, cui_menu_tree_options, cui_menu_command_handler); ``` `valid` means applicable argument/geometry preflight passed, not success of all later rendering. `submitted` follows the shipped ordinary active-submission convention; disabled may submit but cannot command, inert/layout-only cannot notify. `command_count` counts actual observer invocations, saturating at `SIZE_MAX` with `count_overflow`; missing observer preserves all ordinary commands/mutations/close behavior and reports zero. `legacy_activated` is exactly the original aggregate bool and can be true with zero observer calls. No generic request count or selection-change result is reused with a different meaning. The minimal payload deliberately omits label/shortcut/icon text, entry pointers, indices, menu kind and check/radio value fields. Applications already own their model and can dispatch by stable command ID; observers can read applied owner state synchronously. Any future copied typed check/radio snapshot needs a separate additive payload/version decision, not an ACTIVATE-to-CHANGE reinterpretation. Check/radio writes are applied before observation and are not vetoable. Command callbacks have no bool return, cancellation/default prevention or owner acceptance result. ## Exact timing, mutation and evidence Refactor Base into an internal implementation with optional handler/result bookkeeping. Legacy Base passes no observer. New Base and Styled wrappers borrow copied handler/options for one invocation; Styled calls the implementation once and keeps its existing draw/retain/paint order. No public option/state/result struct layout changes are needed. At each existing command branch: 1. Freeze command ID and genuine event metadata before check/radio writes or close/focus changes. Do not retain `entry` in the payload. 2. Run existing active/depth updates, check/radio mutation, `*action` write, close policy and `activated_any=true` in their current order. 3. Freeze the existing `exit_after_command = !state->overlay.open` decision before calling the observer. Increment callback count and synchronously dispatch ACTIVATE if an observer exists and submission is active. 4. Use that frozen decision for the original immediate return versus continue. A callback cannot extend a closing command's reducer pass by reopening state. Keep-open input still proceeds in original event order, subject to callback consumption of later input. This position means callbacks see already-applied check/radio/action state and the already-applied close policy/focus effects. Repeated same command always notifies when the reducer reaches it, even if the radio value was unchanged or action output already matched. Navigation, submenu opening, Escape/outside close, scrolling, disabled/malformed entries and external state assignments are not command ACTIVATE notifications. No CHANGE, COMMIT, SUBMIT or lifecycle event is inferred from these branches. `event.target` is the public trigger ID and `command` is the leaf ID. If a genuine accepted `cui_activation_snapshot` is already available before mutation/close, copy it unchanged and retain its original child target; never rewrite that snapshot to impersonate a redirected command. Normal Styled MenuTree registers entry semantics later, so HAS_ACTIVATION is ordinarily absent. Fallback metadata contains only actual frame/index and source established by explicit pointer-up, key-down/up or accessibility-action event type. It cannot invent coordinates, touch detail, accepted accessibility evidence or programmatic origin from an absent snapshot. Keyboard redirection can commit a different active leaf than the original routed target: preserve both facts without manufacturing a Core activation for the leaf. Callbacks can update unrelated application state and owned command values, or consume later input. Such writes are not additional synthesized commands and do not undo an already-applied operation. Later eligible commands use existing live owner values. Directly changing popup/tree navigation state in a callback is outside this first slice's supported mutation contract: the frozen return policy only preserves the reducer boundary; it is not permission to mutate in-flight navigation. Descriptor arrays/children must remain stable throughout submission, and active storage/users/resources cannot be freed. Request removal/shutdown in application state and perform it after submission/frame completion. Context destruction and recursive same-frame submission remain unsupported; no fake runtime guard is introduced. Payload/user are borrowed synchronously; copying the pointer-free payload preserves it beyond frame/context lifetime. No callback retention, new input routing, queue, scheduler, binding hook or deferred fanout is added. Existing queued foreign notifications keep their timing and current typed allowlist. ## Ownership and meaningful proof before shipping Suggested production scope, pending approval: new `include/cui/cui_menu_events.h`; narrow declarations in `include/cui/cui_choice.h`; Base/Styled implementation changes in `src/base/cui_choice.c` and `src/components/cui_choice.c`; new `tests/unit/test_menu_events.c`; human/LLM guide `docs/MENU_EVENTS.md`; this checkpoint. Root owns CMake/module/generator/SDK/bindings and API-guide indexing. No Core, surface, descriptor-layout or manifest edit. Required tests with real reducers/input: - Base and Styled ACTION, CHECK and RADIO; repeated CHECK twice in one invocation (two callbacks and original final bool/action), same-ID/same-radio reactivation, nested leaf command ID and trigger identity. Observer sees applied model and close state. - Keep-open commands continue; ordinary closing command returns before later eligible commands. Callback count zero with missing observer while mutation/close/bool remain normal. Frozen original return decision has focused internal proof without endorsing arbitrary navigation mutation. - Pointer, touch, Enter/Space and genuine supported accessibility menu actions; snapshot absence at the legacy registration seam, truthful source/index, any genuinely available snapshot retained unchanged. Keyboard redirection must not fabricate leaf-target evidence. - Observer updates check/radio owner state before later commands, consumes later input, and copies payload past frame/context lifetime; handler/user separation and no recursively generated events. Descriptor/user teardown remains explicitly unsupported rather than tested as safe. - Disabled group/entry, labels/separators, missing check/radio storage, empty submenu, inert/layout-only/omitted submission, invalid arguments; no observer callbacks for navigation/typeahead/hover/scroll/dismissal. Scroll/drag invalidation and depth/focus restoration retain existing legacy suites. - Strict portable C11 and C++17 header checks, targeted legacy `choice` regression and new CTest through `python scripts/test_local.py --build-dir build` only. Native/headless evidence must not claim desktop/GPU or full-family parity. Defer simple Menu, ContextMenu, Dropdown, SplitButton, tab-overflow and menu-popup-paint forwarding until each trigger/context identity and callback boundary is audited. Also defer controlled/vetoable commands, check/radio CHANGE payloads, open/close observers, async listeners, foreign synchronous hooks and full menu-family verification. Implementation proof uncovered a separate existing paint-ID collision: radio12 left icon (`id ^ 0x9e3f5d2a91bca001`) and submenu15 chevron (`id ^ 0x9e3f5d2a91bca002`) both derived `0x9e3f5d2a91bca00d`. A separate renderer fix makes the paint-only wrapper anonymous, preserving routing and named icon resource IDs. The ordinary new unit now retains compact IDs and asserts both glyph rasters/geometry. This targeted renderer fix is not a full-renderer parity claim. --- ## Menu and dialog event facade proposal Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/MENU_DIALOG_EVENTS_SLICE.md # Menu and dialog event facade proposal Design only; audited at `6231cc2a` on `integration/next39-components`. No new API below exists yet. Preserve legacy entrypoints, caller-owned state, command dispatch, input routing and callback timing. Do not introduce bubbling, a general dispatcher, controlled menu requests, or binding subscriptions in this slice. ## Current contracts and evidence | Entry point | Actual ownership and delivery | Consequence | | --- | --- | --- | | [`cui_menu`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h#L220) | Caller owns `cui_choice_popup` and action ID; returns true for command activation, including the same action again. Popup options expose a render slot, not an activation callback. | Do not detect commands by comparing old/new selected ID. This is command activation, not selection CHANGE. | | [`cui_base_menu_tree`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_choice.c#L1272) / [`cui_menu_tree`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_choice.c#L1893) | Caller owns overlay/path/list state and borrowed recursive descriptors. Reducer writes `*action`, toggles `*checked` or writes `*radio_value`, then may close the overlay. Styled reduction precedes trigger/popup painting. | These are committed uncontrolled writes. A void observer cannot become a veto or controlled request. | | [`cui_base_context_menu`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_choice.c#L1612) | Opens against an existing target and delegates tree reduction; it does not submit/paint that target. | Keep target, popup and command identities distinct; do not submit another control to obtain events. | | [`cui_base_dropdown_button`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_choice.c#L1637) / [`cui_dropdown_button`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_choice.c#L2126) | Explicit action and trigger IDs are independently focusable; Styled container is paint-only. Result has `action_activated` and `menu_activated`. Action reduction runs before menu reduction. | `menu_activated` means a menu command, not merely opening its trigger. Both flags can be true; result order is not global input order. | | [`cui_surface_state` / options](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_surface.h#L24) | Caller owns state. `decide(user,result)` may refuse a requested close. `on_close` runs after close/focus restoration; its function and user pointer are copied into state during open updates. | Decision and completed lifecycle notification are separate contracts. Close registration is retained, unlike a render-call-only observer. | | [`cui_alert_dialog`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_surface.c#L217) | Composes surface plus cancel/confirm buttons using derived part IDs. Base surface reduction recognizes those activations on later submission. | Do not attach an additional button observer that closes again or bypasses decision policy. Ordinary Dialog instead uses composed begin/end. | Tree details matter. At [`activation commit`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_choice.c#L1528), checks/radios mutate their owners before `*action` and dismissal. With `keep_open_checks`, several accepted events can run in one reduction, while the public result remains one bool and the action output is the last ID. Submenu opening, keyboard navigation, scrolling and dismissal are not commands. Disabled entries, labels and separators retain existing eligibility rules; missing check/ radio storage is handled by `cui_menu_entry_is_disabled`. Render callbacks are borrowed presentation slots, not action listeners. Generic List's [`on_activate`, `on_confirm`, `on_cancel`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h#L168) are distinct contracts; their per-event callback capabilities must not be attributed to Menu or DropdownButton. Dropdown loading/disabled policy is asymmetric: `action_loading` disables the action half; whole-control/menu-popup disabled also gates the menu. Hidden halves are omitted via zero IDs; both zero is invalid. Omitting the trigger closes an existing menu. Preserve these policies, tooltip registration, independent focus, custom rendering and inherited variants/sizes without resubmitting either half. For surfaces, [`finish_close`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_surface.c#L58) sets the result, restores/dismisses the focus scope, closes the overlay, then calls `on_close`. [`cui_surface_close`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_surface.c#L77) is an imperative close and bypasses `decide`; [`request_close`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_surface.c#L91) stores one pending reason, normalizes invalid reasons to CLOSED, and invalidates. The next [`update`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_surface.c#L267) clears that pending reason before consulting decision policy. A refusal is not a close, and pending requests are not a queue. `take_result` consumes the persistent result, not a callback/event. Opening resets prior result/pending state. The update loop also offers close reasons for confirm/cancel/close activation, Escape and eligible outside pointer-down. Alert outside dismissal and its close button require opt-in; generic dialog defaults differ. A veto can leave the surface open so subsequent events can offer further decisions in that frame. Do not infer acceptance from event consumption. Animated Sheet retains its modal while exiting and notifies only on completed exit; although this first proposal covers Dialog/Alert, a shared lifecycle hook must not retime Sheet. Options are refreshed before animation completion, so the currently registered callback can receive completion of an earlier request. Existing regression evidence: [`test_menu_tree`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_choice.c#L513), [`test_context_menu`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_choice.c#L648), [`test_menu_configuration`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_choice.c#L1406), [`test_dropdown_button`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_choice.c#L1465), optional-half, loading and popup-paint tests in the same file; surface [`sheet_motion`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_surface.c#L480) and [`requested_close`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_surface.c#L557) check completion timing, focus restoration and decision refusal. These are existing tests, not execution claims for this documentation-only work. ## Smallest first facade: aggregate command observation Use a separate Base-only events header including `cui_component_events.h`. Proposed `cui_menu_command_event` contains shared metadata, an explicit owner ID, the activated command ID and a discriminator for plain menu command versus split primary action. It contains no descriptor pointers, labels, callback/user values, check storage pointers, or invented item generation. Callback payloads are copyable; command IDs alone do not extend owner lifetimes. Add `cui_menu_events`, `cui_base_menu_tree_events`, `cui_menu_tree_events`, and context-menu equivalents by private common implementations; legacy functions supply no observer. Callback occurs once after successful aggregate reduction, before Styled painting, even when the command repeats the previous ID. Its metadata is ACTIVATE, target the command (or split action) ID, source UNKNOWN, HAS_FRAME only when this submission actually has a frame. No event index or activation snapshot can be reconstructed from the final action/bool. For keep-open tree reduction explicitly name delivery **aggregate last command**. The event guarantees only that command's ID, not its old/new checked/radio value, all intermediate commands, or a unique physical cause. Absence of an observer still performs the same writes. Return the original aggregate control result plus actual observer invocation count, not a fabricated native activation count. A future per-event tree reducer is a different review: instrument acceptance inside the loop and freeze evidence before mutable callbacks; never replay it. For `cui_dropdown_button_events`, preserve the original two flags and action ID output. Emit zero/one primary-action aggregate and zero/one last-menu-command aggregate, in existing action-then-menu reduction order. State clearly that this is not event-index order across halves. Reject invalid handler combinations before mutation; do not reinterpret content/tooltip callbacks as conflicts. Keep popup opening/closing, submenu navigation and check/radio requests out of this facade. Implement simple Menu/tree first; split composition follows after callback-before- paint behavior is tested, without using two legacy submissions. ## Surface lifecycle needs explicit retained registration Proposed payload: `cui_surface_lifecycle_event { metadata; cui_surface_result result; }`. First expose only completed CLOSED lifecycle, whose result is ACCEPTED, CANCELLED or CLOSED. Do not promise OPEN, requested, vetoed, destroyed or per-input events. Keep existing `decide` unchanged; typed veto/request callbacks are separate future work. Notify at the existing finish-close seam after focus restoration and overlay close, independent of whether the owner later takes the result. A stack-local adapter in `surface_begin_events` is invalid: state retains `on_close/close_user` and imperative close can call it after the render function returns. Attaching a trampoline to an ordinary state once is also insufficient: every open legacy update overwrites those fields from its options. Use a new caller-owned state wrapper, not a promise that attach intercepts old functions. ### Proposed exact first-slice API Names are proposals; keep these declarations in a separate header, with Base functions implemented below Components and Styled functions implemented in Components. No platform types or heap allocation are required. ```c typedef struct { cui_component_event_metadata event; cui_surface_result result; } cui_surface_lifecycle_event; typedef void (*cui_surface_lifecycle_fn)( void *user, const cui_surface_lifecycle_event *event); typedef struct { cui_surface_lifecycle_fn closed; /* NULL means no observer. */ void *user; } cui_surface_event_handler; typedef struct { cui_surface_state control; cui_surface_event_handler handler; /* Adapter-owned: callers must not edit these fields. */ bool attached, active, notifying; size_t call_close_count; } cui_surface_event_state; typedef struct { bool valid; /* Adapter preflight accepted; not a rendering success claim. */ bool control_result; /* Original update/begin bool; false for void Alert. */ size_t close_count; /* Observer invocations during this call only. */ } cui_surface_event_result; void cui_surface_events_init(cui_surface_event_state *, cui_id, cui_surface_kind); bool cui_surface_events_set_handler(cui_surface_event_state *, cui_surface_event_handler); bool cui_surface_events_detach(cui_surface_event_state *); bool cui_surface_events_options(cui_surface_event_state *, cui_surface_options input, cui_surface_options *output); cui_surface_event_result cui_base_surface_update_events( cui_context *, cui_surface_event_state *, cui_surface_options); cui_surface_event_result cui_base_surface_begin_events( cui_context *, cui_surface_event_state *, cui_str title, cui_str description, cui_surface_options); cui_surface_event_result cui_surface_begin_events( cui_context *, const cui_theme *, cui_surface_event_state *, cui_str title, cui_str description, cui_surface_options); cui_surface_event_result cui_alert_dialog_events( cui_context *, const cui_theme *, cui_surface_event_state *, cui_str title, cui_str description, cui_str confirm, cui_str cancel, cui_surface_options); ``` The proposed struct is concrete portable storage, not a variable opaque allocation. Init initializes `control` with the existing init function, sets the empty handler and installs the internal trampoline with the enclosing state as its user pointer. This enclosing object's address is stable until detach; copying/moving an attached state is unsupported. Init is for fresh or detached, closed storage only; it is not an implicit teardown/reinitialization operation. `set_handler` replaces one retained registration; it does not append listeners. A NULL function ignores user data and clears the stored user pointer. Reject NULL/detached state, unexpected legacy callback fields, and calls during an active wrapper/trampoline. Failure changes nothing. Changing the handler while open is allowed between component calls: the latest handler receives a subsequent completed close, including an already-started Sheet exit. A NULL handler still keeps adapter registration intact and native mutation continues. No callback count or queued close is replayed on replacement. Every event-aware update/begin wrapper preflights the **whole call** before any state or UI mutation, then calls `cui_surface_events_options` on its by-value options. The helper rejects NULL/detached state, NULL output, non-NULL incoming `on_close` **or** `close_user`, an unexpected retained callback/user pair, or an active invocation; it leaves output and state untouched on failure. On success it copies every option unchanged, including `decide`/`decision_user`, then sets only `on_close` to the trampoline and `close_user` to this enclosing state. The internal common implementation handles the guard once; wrappers must not recursively call another public guarded wrapper. The existing open-update assignment therefore refreshes the *same* retained trampoline each frame. Do not mutate the caller's options or cache a pointer to it. The options helper itself never changes native state or starts an active call. `valid=false` means adapter preflight failed; native reduction/submission must not have run. After successful preflight, preserve the exact legacy return in `control_result`, including false for closed/invalid native geometry; `valid=true` does not upgrade native failure. For the legacy void Alert composition, `control_result` is always false and callers inspect `control.overlay.open` when needed. A completed close can precede a later submission failure; its callback and count remain real. Base/Styled end and footer helpers stay unchanged and are called only when the corresponding begin's `control_result` is true. Never run update separately and then begin on the same input to manufacture notification. Imperative lifecycle operations use the existing functions on `&state.control`: `cui_surface_open`, `cui_surface_close`, `cui_surface_request_close` and `cui_surface_take_result`. This deliberately adds no second close policy. The retained trampoline receives direct close; request-close still waits for a submitted update and its unchanged decision policy. Imperative operations have no per-call facade result/count. An invalid/no-op repeated close emits nothing. Taking a result neither unregisters nor replays the callback. Existing legacy update/begin calls on `&state.control` with ordinary options are **not supported while attached**: they can clear the retained trampoline before an imperative close, and the adapter cannot intercept them. Prefer the wrappers. For custom composition that must use a legacy update/begin, call the options helper first and pass its returned options to that exact call; this preserves registration but reports no wrapper-local count and supplies no wrapper completion frame evidence. Keep both options and their enclosing state alive for the call; only the enclosing state/handler owner must remain alive afterward. The helper must not be used to pass the callback to a different surface state. A subsequent wrapper detects a lost/replaced registration and fails; it cannot recover a close already missed through an unsupported legacy call. Document this restriction in examples and migration guidance rather than imply attach handles arbitrary calls. Detach is an explicit operation between calls. It succeeds only when closed, not exiting, and neither a wrapper nor trampoline is active. It clears only the matching trampoline/user pair, empties the handler and marks the adapter detached; unexpected replacement means failure with no mutation. After detach ordinary legacy entrypoints may use `control`, and the enclosing storage may be released. To resume event-aware use, initialize a closed detached state again (discarding its old control/result as explicitly requested by init). Detach does not close, consume a result, invoke a callback or free resources. Rejecting open detach prevents accidentally dropping an outstanding animated completion. The trampoline copies the handler and pointer-free payload before calling the observer, after native focus restoration/overlay close. Increment the active call's count only when invoking a non-NULL observer; outside a wrapper there is no returned count. Reentrant surface operations on this state, including the legacy imperative operations, are unsupported during notification; the owner may change unrelated application state. This bounds completion notification to the existing close transition rather than enabling observer-driven close recursion. Its event is LIFECYCLE with surface ID and committed result, UNKNOWN source and no frame/index/activation flags in this first slice, consistently for imperative close, wrapper update and the options-helper escape hatch. Do not read a possibly previous `cui_frame_sequence` value between frames and advertise it as a completion frame. A later extension may add frame evidence only where active-frame validity is actually established; no retained request frame is completion evidence. No source inference comes from result: ACCEPTED is a result, not proof of keyboard/pointer/programmatic origin. Explicit programmatic origin would require a separately reviewed new operation. This design leaves `cui_surface_state` and all legacy signatures/layouts intact; its cost is distinct event-aware storage plus explicit migration of *all* update/ begin calls for that storage. That is smaller and safer than changing the legacy state's callback overwrite rules, adding a context registry, or retaining stack adapters. Implement Dialog/Alert registration and imperative-close tests first; shared Sheet paths remain compatibility gates, not a claim of new Sheet coverage. Callbacks may copy metadata/result and mutate application owner state. Destruction of context/state/registration or descriptor storage during any callback is unsupported. Queue teardown until the outer component call returns; a close callback is not an unmount/destruction guarantee. C++/foreign exceptions must not unwind through C. A future binding adapter must catch/store exceptions and report them after native stepping; partial native transitions cannot be rolled back. ## Binding boundary and delivery gates The bridge currently uses simple [`cui_menu` and DropdownButton](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/bridge/cui_bridge.c#L3109) and translates returned aggregates into queued changes; primary split action is CLICK. It does not expose recursive check/radio menu descriptors, these proposed synchronous C callbacks, or surface decision callbacks. V1 types surface CLOSE with its result at [`bridge_surface_close`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/bridge/cui_bridge.c#L2887), but menu changes remain LEGACY. Surface results are queued after Styled rendering via `take_result`, not delivered at the native `on_close` seam. Manual V1 polling in all four bindings is committed queued observation, not these facades; it shares the legacy FIFO and omits native per-input activation evidence. Do not promote binding parity or expand reserved V1 selection tags as part of this work. Before implementation, add headless acceptance tests that compare old/new state, output IDs, semantics, focus, event consumption and paint geometry. Cover repeated commands, multiple keep-open checks/radios and last-command coalescing; disabled/ inert/omitted/loading controls; pointer, keyboard and actual supported accessibility activation; submenu/scroll/dismissal producing no command; both split flags and explicit observer order. Callback owner mutation must be visible to subsequent painting without reprocessing input. Test invalid options before any mutation. For lifecycle, cover all three results, veto/retry, pending overwrite, direct close versus request close, take-result before/after callback, focus restoration, re-registration/detach, registration preserved across changing options in every Base/Styled wrapper and helper-bridged legacy call, unsupported plain-legacy update clearing registration detected on the next wrapper, no callback on repeated close, and animated completion across frames. Retain existing legacy tests unchanged. Compile with strict C/C++ header checks and run CTest through the private headless wrapper. No dispatcher, Core teardown, generated SDK or binding changes belong in this first slice. Implementation preflight correction: only request-close is documented safe between frames. Existing imperative close calls `cui_dismiss_focus_scope`, which requires an active frame (`src/core/cui.c`, `cui_core_active`). Outside-frame close can commit and notify while recording CUI_ERROR_LIFECYCLE. The facade must preserve that diagnostic and must not promise safe between-frame imperative close or full scope restoration there. Test valid imperative close after begin returns within an active frame; preserve the legacy outside-frame restriction and diagnostic; no Core architecture change belongs in this slice. The completed CLOSED slice is now specified by `include/cui/cui_surface_events.h` and `docs/SURFACE_EVENTS.md`: callback order is `(void *user, const event *)` and the shared metadata field is named `event`, matching the other facades. No menu implementation is included; Choice ownership remains a separate workstream. --- ## Menu forwarding event checkpoints Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/MENU_FORWARDING_EVENTS_SLICE.md # Menu forwarding event checkpoints Status: ContextMenu, Simple Menu and paired DropdownButton slices implemented in this branch. See [DropdownButton events](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/DROPDOWN_EVENTS.md). See [Simple Menu events](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SIMPLE_MENU_EVENTS.md). Original source audit: `b4146c89`. See [ContextMenu events](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/CONTEXT_MENU_EVENTS.md) for the implemented API and proof. Preserve [MenuTree's implemented per-command contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/MENU_EVENTS.md), [event ownership/timing rules](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_CONTRACT.md), all legacy entry points/layouts, and the 78-family manifest. No Core/surface change, new queue, capture/bubble routing or binding request hook is proposed. No builds were run for this read-only checkpoint. ## Actual entry points and seams | Public path | Current reduction and IDs | Existing result/callback limitation | | --- | --- | --- | | Simple `cui_menu` | Styled `cui_choice_popup_render(..., menu=true)` uses flat `cui_choice_item` IDs, caller-owned action output and `cui_choice_popup`. Full `cui_base_list` pass precedes popup close and focus-scope dismissal. Trigger is its public `trigger` argument. | Bool means any activation, including same action again; only final action output survives. Public options expose render slots, not command handlers. The private Select list observer emits CHANGE only when previous differs, so it is unsuitable for repeated commands. | | Base/Styled ContextMenu | Base scans unconsumed secondary pointer-down events inside existing target bounds and permitted popup scope, calling `cui_context_menu_open`. It then delegates to MenuTree with `trigger=target`; Styled validates geometry, sets drag policy, reduces once and paints at `state->anchor`. | Bool is MenuTree aggregate; per-command forwarding is currently missing. Context opening/reanchoring is not a command. `overlay.trigger` is independently used for restoring focus and may differ from the target; do not substitute it for metadata identity. | | Base/Styled `cui_dropdown_button` | Separate public `action_id` and `trigger_id`; Styled also has a paint/layout `container`. Base calls `cui_base_button` for action first, updates loading semantics, then reduces MenuTree for menu commands. Hidden/absent trigger closes existing menu and clears depth. Styled draws halves, retains menu metrics, composes action tooltip, maps anchor corners, then paints menu. | `{action_activated,menu_activated}` are aggregate booleans, not per-event counts. Primary action has no typed observer; menu command observer is not forwarded. Content/render/tooltip callbacks are not command listeners. | Source: [choice header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h), [Base choice](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_choice.c), [Styled choice](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_choice.c), [`cui_base_button`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_base.c), [typed activation handler](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_control_events.h). There is no separate public `cui_split_button` symbol: split-button presentation is the paired DropdownButton; `hide_action` gives a menu-only presentation and `hide_menu` gives action-only. The canonical manifest family is DropdownButton; these presentations do not add manifest families. Actual legacy proof in [test_choice.c](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_choice.c): `test_lists_and_popups` verifies Simple Menu same-ID reactivation, popup close/focus and paging; `test_context_menu` verifies right-click anchor/reanchor, nested command dispatch, focus restore and outside target; `test_context_modal_guard` verifies popup scope restrictions. `test_dropdown_button`, `test_dropdown_optional_halves`, `test_dropdown_anchor_corners`, `test_dropdown_action_tooltip`, `test_dropdown_loading_keeps_content`, `test_dropdown_loading_subtree_opacity`, `test_dropdown_real_artwork` and presentation/inheritance tests cover paired-half behavior and rendering. These legacy tests do not establish new typed multiplicity, callback mutation or evidence lifetimes. ## Slice 1: ContextMenu command forwarding Implemented as the first slice: reuse `cui_menu_command_handler/result` unchanged. Exact additive signatures append the handler to existing arguments: ```c cui_menu_command_result cui_base_context_menu_events( cui_context *, cui_id target, const cui_menu_entry *, size_t count, cui_id *action, cui_menu_tree_state *, bool disabled, float dt, bool keep_open_checks, cui_menu_command_handler); cui_menu_command_result cui_context_menu_events( cui_context *, cui_id target, const cui_theme *, cui_str name, const cui_menu_entry *, size_t count, cui_id *action, cui_menu_tree_state *, cui_menu_tree_options, cui_menu_command_handler); ``` Refactor only ContextMenu's opening scan into a shared private implementation with optional forwarding. Legacy calls the old MenuTree path; new calls MenuTree events exactly once. Do not call `cui_base_context_menu` and then try to re-observe its aggregate result, or scan/reduce twice. Preserve original opening/reanchoring order, scope checks, anchor bounds, retained state, check/radio writes, keep-open behavior and close timing. `event.target` is the public ContextMenu receiving `target`, even when restore focus is another control or programmatic `cui_context_menu_open` was used. Command is the actual leaf ID; copied activation retains its real routed child target. Right-click opening alone emits no ACTIVATE command, and opening input is not relabeled as the later command's source. Programmatic open adds no fabricated input evidence. Reuse MenuTree source/snapshot limitations and callback-count semantics: missing handler mutates normally with count zero; repeated keep-open command IDs notify individually. Proof: real right-click open/reanchor without command; nested action/check/radio per-command multiplicity; programmatic open with distinct restore-focus ID; pointer/touch/key/supported accessibility menu actions; scoped modal rejection; missing handler; disabled/inert/omitted invocation; callback owner writes/later consumption; close/focus/anchor invariants and copied payload lifetime. Preserve compact-ID renderer and legacy ContextMenu/MenuTree regression tests. No open/close observer is added. ## Slice 2: Simple Menu flat command observer Implemented exact signature reuses existing command payload/result: ```c cui_menu_command_result cui_menu_events( cui_context *, cui_id trigger, const cui_theme *, cui_str name, const cui_choice_item *, size_t count, cui_id *action, cui_choice_popup *, cui_choice_popup_options, cui_menu_command_handler); ``` Add private per-activation command forwarding to the flat list reducer, without changing public list options or the current Select observer seam. A small private list implementation can take optional selection and command forwarding; legacy/Select calls retain their existing mode, and only new Simple Menu enables command notifications. Do not interpret `previous!=value` as command eligibility, and do not accidentally emit both CHANGE and ACTIVATE for the same Menu call. At every existing flat-list activation, freeze command ID/input facts before callbacks, preserve assignment and existing activation→confirmation callback order, then emit ACTIVATE for that command even if action output already matched. Preserve the complete list pass and close/dismiss after it: A→A→B yields three notifications and final B, while legacy bool remains true. Simple Menu cannot gain MenuTree's early-return-after-closing-command policy: its existing close occurs after the list pass. Render slots/painting remain in their current phase. `event.target` is the public trigger; command is the activated flat item ID. The existing flat `menu=true` path registers MENUITEM roles (unlike Select's OPTION roles), so genuine accessibility ACTIVATE should be tested against the actual previous-frame menu semantics. Accepted snapshots are ordinarily unavailable before current registration; retain genuine facts only and never register early. Existing Menu flat descriptors do not expose check/radio/submenu behavior; do not imply that this API adds those features. Proof: repeated same-ID commands and multi-command list pass, final output/legacy bool, observer owner writes and consumed later input, trigger/leaf identity, pointer/touch/key/accessibility menu roles, same-item closing, dismissal/scroll-invalidated pointer activation, disabled/inert/omitted/missing handler, renderer slots and copied lifetime. Keep Select/Combobox/List callbacks and all legacy aggregate semantics unchanged. ## Slice 3: DropdownButton paired action and menu events Implemented as one separately reviewed public paired facade after the two forwarding slices, rather than silently declaring a partial uniform event API. Reuse the shipped typed activation handler for primary action and MenuTree command handler for menu leaves: ```c typedef struct { cui_component_activation_handler action; cui_menu_command_handler menu; } cui_dropdown_event_handlers; typedef struct { bool valid, submitted, count_overflow; size_t action_count, command_count; /* actual callback invocations */ cui_dropdown_button_result legacy; } cui_dropdown_event_result; cui_dropdown_event_result cui_base_dropdown_button_events( cui_context *, cui_id action_id, cui_id trigger_id, cui_str action_name, cui_str menu_name, const cui_menu_entry *, size_t count, cui_id *menu_action, cui_menu_tree_state *, bool disabled, bool action_disabled, bool action_loading, float dt, bool keep_open_checks, cui_dropdown_event_handlers); cui_dropdown_event_result cui_dropdown_button_events( cui_context *, cui_id container, cui_id action_id, cui_id trigger_id, const cui_theme *, cui_str action_name, cui_str menu_name, const cui_menu_entry *, size_t count, cui_id *menu_action, cui_menu_tree_state *, cui_dropdown_button_options, cui_dropdown_event_handlers); ``` The result deliberately counts callback invocations, with zero for missing handler. Do not reuse Button's `cui_component_action_result.activation_count`, whose accepted-attempt semantics differ for missing handlers; no unused request count is introduced. Legacy aggregate booleans remain unchanged. Both counts saturate; overflow never suppresses dispatch. `cui_control_events.h` provides the Base-dependent activation handler; adding its include/type use needs public-header C/C++ proof, not a Components dependency in Base. Preserve existing **action phase → menu phase → Styled painting/tooltip**. Call existing `cui_base_button` once, retain its aggregate result and loading/busy semantics, then enumerate genuinely accepted action events/snapshots before entering the menu reducer. This is possible because Base Button submits its current semantic and does not itself run external action callbacks. Reuse current acceptance/snapshot APIs; do not call Styled `cui_button_events`, draw another button or synthesize one callback from the aggregate bool. Action metadata kind ACTIVATE targets `action_id`; menu command metadata targets `trigger_id`. `container` is layout identity, never an invented input target; opening the menu trigger is not itself a menu leaf command. Action and menu phases may report nonmonotonic event indices when mixed input was queued; preserve those phases and truthful indices rather than sort/replay/defer. Action callbacks can consume later input before menu reduction; menu observer uses the existing per-command seam exactly once. Freeze callback payloads before mutable callbacks. Action disabled/loading suppress only action; outer/menu disabled policy suppresses both as currently composed. Hidden action gets no semantic/callback; hidden menu closes existing popup and dispatches no menu commands. Preserve Link role updates, menu-only/action-only geometry, anchor mappings, content slots, tooltip trigger/disabled policy and all retained resource lifetimes. Any role-sensitive evidence mismatch from Styled Link's existing post-reduction role update must be reported rather than normalized into fabricated evidence. Proof: multiple primary activations with exact evidence, independently disabled/loading and missing handlers, action-first ordering versus earlier-index menu input, later-input consumption/owner mutation, menu check/radio repeated commands, distinct action/trigger/container IDs, hidden halves and existing popup-close behavior, Link accessibility roles, tooltip/content order and rendering. Use genuine supported accessibility actions, pointer/touch/keyboard, inert/layout-only/omitted calls and copied payload lifetime. No extra SplitButton family/symbol alias is necessary unless a separately reviewed discoverability decision requests it. ## Shared boundaries and implementation ownership All new payloads are synchronous borrowed views; pointer-free copies survive frame/context destruction. Copy handler/options at entry; active descriptors/children, values, users/state and render resources must remain alive/stable through existing boundaries. Callback owner writes are not recursive events, and notification is not rejection/rollback. Direct in-flight popup/navigation mutation, context destruction, freeing active storage and recursive same-frame submission remain unsupported. Schedule removal/shutdown for after submission/frame completion. Preserve MenuTree's frozen closing-command return decision; do not transfer it to flat Simple Menu's different close policy. Each slice should be its own production commit plus meaningful unit/guide proof, with source ownership limited to `cui_choice.h`, Base/Styled choice implementation, a new slice fixture and human/LLM guide. Slice3 may need a narrow include/use of existing control-event types; no shared type layout changes. Root owns CMake/modules/generated distributions/SDK/bindings/indexing. No build or production edit belongs to this design checkpoint. Future implementation must use strict portable C11/C++ header checks and native CTest through `python scripts/test_local.py --build-dir build`; browser tests stay headless. Deferred: menu open/close observers, vetoable/synchronous foreign requests, check/radio CHANGE payloads, global event-index ordering, auto callback fanout, tab-overflow/command/surface forwarding, async listeners and parity promotion. Aggregate-only fallback must be explicitly labeled if a later path lacks a true per-event seam; it must never masquerade as complete per-command observation. Implemented Dropdown proof boundary: Styled root menu paint remains modal regardless of overlay.modal; mixed-phase decreasing-index proof uses genuine Base modeless composition. Existing post-Base LINK role updates reject queued Link accessibility activation at current BUTTON registration; no observer/evidence is fabricated. See the guide and fixture for exact coverage. --- ## Multiline CHANGE observer proposal Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/MULTILINE_EVENTS_SLICE.md # Multiline CHANGE observer proposal Design audit at `0426a540`; none of the APIs below is implemented. This is a compatible notification slice, not a rejectable edit transaction or a parity claim. ## Existing ownership and ordering | Path | Actual behavior | Consequence | | --- | --- | --- | | [`cui_base_textarea`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_textarea.c) | Owns one frame-event loop; snapshots committed state before reduction and compares final revision, primary selection, visual affinity and scroll afterward. IME has a separate early-continue branch. | A final committed-state CHANGE seam is available. Per-event hooks would need every mutation branch, not just the ordinary edit tail. | | [`cui_base_editor`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_editor.c) | Validates/probes layout, snapshots state, handles completion, handles multiple selections, then calls Base Textarea. Synchronizes cursor anchors, completion and search afterward. | Observing only its Textarea call misses completion and multi-cursor edits. The composite owns notification. | | [`cui_textarea`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_textarea.c) | Establishes viewport/composition, calls Base once, then lays out and paints Styled content. | An additive common function can pass an observer at the existing Base seam without replay. | | [`cui_editor`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_editor.c) | Owns Styled geometry, gutter/folds/completion UI around Base Editor. | Keep the existing sequence and use a common implementation; do not compose a second Base submission. | [`cui_textarea_result`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_textarea.h) exposes aggregate `changed`, `selection_changed`, `scrolled`, and **last** Enter flags, not a submit count. Enter inserts a newline unless `submit_on_enter` is enabled without Shift; readonly does not set `pressed_enter`. The ordinary Enter branch does not have Input's nonrepeat qualification. These differences must remain intact. Editor can consume Enter to accept completion before Textarea sees it. Its multi-selection pass can consume edits before the Textarea pass. Neither the final result nor consumed-event bits identify a unique cause for the whole submission. There is no existing public single-event Textarea reducer equivalent to Input's. ## First independently reviewable slice: aggregate CHANGE Propose a new `cui_multiline_events.h` with: ```c typedef struct { cui_textarea_result control; size_t change_count; /* Zero or one actual observer invocation. */ } cui_multiline_event_result; ``` Reuse `cui_component_text_event` and `cui_component_text_handler` from [`cui_text_input_events.h`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_text_input_events.h), with an explicitly different delivery granularity. Proposed entrypoints mirror each existing signature, append the handler, and return the new result: `cui_base_textarea_events`, `cui_textarea_events`, `cui_base_editor_events`, `cui_editor_events`. Keep all existing options, results and entrypoints unchanged. An absent observer still edits and yields zero callback count. For Base Textarea, capture scalar `before` at its existing snapshot, compare the final committed revision, then notify once after final semantics/invalidation and before return. For Base Editor, capture at its existing pre-pass snapshot and notify once after its final search/completion/cursor synchronization, before return. Its internal Base Textarea call must remain unobserved. Styled wrappers delegate at the current Base seam and paint afterward. Refactor a private common function rather than call legacy UI twice. Emit only if the committed revision differs, independently of final layout/search error: edits already applied before a later geometry failure are still committed. Include the unchanged control error in the return value; observer delivery does not certify rendering success. Every early return after the snapshot must route through the notification finalizer, including Editor's multi-pass failure. Early validation failures before any mutation do not notify. Do not infer CHANGE from selection, scroll, `pressed_enter`, event consumption or a callback count. Metadata is CHANGE with target and actual frame sequence, source UNKNOWN, HAS_FRAME only: no index, activation or claimed physical-input source. Several edits, Undo/Redo, completion acceptance, newline/indent and multi-selection edits can coalesce. Equal final bytes may still have a changed revision; report that revision change. External programmatic edits completed before entry do not notify. A scalar before/after snapshot describes primary selection only, not all cursors. Document this and keep multi-selection snapshots a separate future payload. ## IME, lifetime and compatibility limits Preedit START/UPDATE/CANCEL normally changes composition presentation without a committed revision and must not notify. Accepted COMMIT notifies if revision changes; failed commit does not. Focus/readonly cancellation keeps existing behavior. Undo/Redo are ordinary committed revision changes, with no new undo ownership or replay. See [`test_textarea.c`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_textarea.c) (composition navigation, indentation/history, readonly/disabled and pointer cases) and [`test_editor.c`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_editor.c) (completion, multi-cursor, search, fold and history coverage). Borrow committed text only for the callback; bounded retention uses `cui_component_event_copy_utf8`. These multiline options have no Input password or mask mode: do not invent secure support or silently promise redaction. Hosts with sensitive documents should use scalar fields and avoid retaining text. A future explicit text-redaction option needs its own reviewed contract. Reuse Input's caller preconditions: no edit/state/context/buffer/workspace mutation, rebinding, destruction or recursive UI submission during the observer. Theme, selection/history arrays, layout rows, completion/search/fold descriptors and borrowed document storage must remain alive. Unrelated application flags are safe; defer omission/destruction until frame and renderer consumption. No runtime guard is claimed. Notifications are post-mutation and cannot reject edits. Do not add REQUEST, COMMIT, SUBMIT or selection notifications in this first slice. In particular, aggregate Enter flags cannot faithfully produce per-event SUBMIT, and a composition COMMIT is not a general editing-commit lifecycle. Do not change Editor pass ordering to manufacture Input-style evidence. ## Review and verification slices 1. Base + Styled Textarea aggregate observer: new header, narrow common functions in `src/base/cui_textarea.c` and `src/components/cui_textarea.c`, declarations in `include/cui/cui_textarea.h`, dedicated tests and guide. Compare old/new buffers, revision/history/selection, aggregate results, semantics and draw output. 2. Base + Styled Editor aggregate observer: narrow common functions in `src/base/cui_editor.c` and `src/components/cui_editor.c`, declarations in `include/cui/cui_editor.h`, dedicated tests. Prove completion and multi-cursor changes produce one outer callback and no nested Textarea callback. 3. Only if requested, separately audit a genuine per-event Textarea seam covering IME, clipboard, indentation, normal editing and early failures. Editor per-event delivery requires a distinct decision about its multipass ordering; it is not automatically inherited from that work. For both initial slices test multiple text edits in one frame, edit then Undo, selection/scroll-only frames, idle/external changes, missing observer, IME preedit and accepted/failed commit, readonly/disabled, Enter/Shift-Enter/submit_on_enter, borrowed-copy retention and bounded-copy failure, deferred omission, and failures before versus after mutation. Compare old/new timing and pixels headlessly; retain legacy Textarea/Editor suites. Native checks use `scripts/test_local.py`, never the maintainer display. Add actual event-loop fixtures rather than direct notification helper tests alone. These C proposals do not supply Python/JS/TS/Go/Rust observers. Existing queued bridge events are a separate, post-frame contract with different payloads and ownership; see [binding audit](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_BINDINGS.md). Binding exposure, exports, build registration and generated SDK copies need separately owned work. ## Editor implementation audit correction Further inspection of `src/components/cui_editor.c:cui_editor_completion_popup` shows that pointer activation can accept a completion after the main Styled paint, near the end of `cui_editor`. Observing only its Base call would miss that change. The approved Editor slice therefore wraps the entire existing Styled call exactly once and notifies after its return, including popup acceptance and painting. Base Editor likewise wraps the complete legacy call, covering every post-mutation early return. Nested Base Textarea stays unobserved; no event pass or paint is replayed. The facade preserves the legacy `control.changed` verbatim, even where that flag and revision-derived notification differ. It never repairs aggregate flags or moves popup callbacks/paint. Tests must demonstrate pointer completion, exact old return equivalence, and one final notification. Teardown remains deferred until the outer facade returns and renderer consumption finishes. The earlier proposed before-Styled-paint Editor seam is superseded by this concrete source finding. The current popup path already ORs its before/after revision comparison into `result.changed`; pointer acceptance is not evidence of an incorrect legacy flag. The facade must preserve that behavior and tests compare it directly. The outer seam is required because the mutation is later than Base, regardless of flags. --- ## Explicit named Checkbox and Radio indicators: review checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/NAMED_SELECTION_INDICATORS.md # Explicit named Checkbox and Radio indicators: review checkpoint Status: the approved additive named-indicator slice is implemented. Audit follows first ownership slice94654394. Existing legacy Checkbox/Radio indicators remain anonymous; only explicit new entry points name them. The beta all78-parts and language-authoring milestones remain pending. ## Current entry points and timing `src/components/cui_components.c` owns Checkbox_ex, source, boolean convenience and Checkbox_events. Checkbox_ex validates ordinary options, invokes exactly one Base check reducer (legacy or extended), updates semantics/tab stop, computes motion/defaults, invokes ordered style refinements, then opens the row/anonymous column/anonymous indicator. Custom indicator callback replaces glyph painting inside that indicator box; label content follows it, and optional tooltip follows the row. The source facade sets source_behavior and delegates ex. The boolean facade projects bool through a local check-state value. The event facade captures its value/handler in stack forwarding storage and delegates source once; its valid/submitted fields do not prove completed paint. Checkbox indicator identity therefore must be selected before the existing indicator begin, without moving Base reduction or style/content callbacks. `docs/CHECKBOX_BEHAVIOR.md:86–103` already confines style callbacks to refinement and permits balanced custom layout in indicator/content callbacks. The Base `cui_base_check_indicator` already accepts a caller ID for applications composing their own noninteractive primitive, but replacing Styled's glyph/spring painter with it would risk changing pixels and is not this proposal. Radio_ex independently invokes Base radio once and paints a row plus anonymous indicator; Radio convenience delegates ex. Radio options alias Checkbox options but ignore Checkbox-specific extensions. There is no current single-Radio event facade to imply support for. `src/components/cui_radio_group.c` has a separate renderer: it invokes Base group or Base group-events once, then directly paints item rows/anonymous indicators for up to CUI_RADIO_GROUP_MAX64 items. Group-events preserves legacy owner request before its observer. It must not be implemented by calling the individual interactive Radio facade for each item. ## Approved additive public surface Use one small value descriptor in cui_components.h; no existing options/state structure grows and no descriptor contains platform types or borrowed pointers: ```c typedef struct { cui_id indicator; } cui_selection_indicator_parts; bool cui_checkbox_ex_with_parts(cui_context *, cui_id, const cui_theme *, cui_str, cui_check_state *, cui_checkbox_options, cui_selection_indicator_parts); bool cui_checkbox_source_with_parts(cui_context *, cui_id, const cui_theme *, cui_str, cui_check_state *, cui_checkbox_options, cui_selection_indicator_parts); bool cui_checkbox_with_parts(cui_context *, cui_id, const cui_theme *, cui_str, bool *, bool disabled, cui_selection_indicator_parts); cui_component_action_result cui_checkbox_events_with_parts(cui_context *, cui_id, const cui_theme *, cui_str, cui_check_state, cui_checkbox_options, cui_selection_indicator_parts, cui_component_check_handler); bool cui_radio_ex_with_parts(cui_context *, cui_id, const cui_theme *, cui_str, int *, int option, cui_radio_options, cui_selection_indicator_parts); bool cui_radio_with_parts(cui_context *, cui_id, const cui_theme *, cui_str, int *, int option, bool disabled, cui_selection_indicator_parts); ``` The implemented descriptor/entry signatures above retain the approved contract. Both IDs must be nonzero and indicator must differ from row ID. New entry points require explicit indicator identity; descriptor0 is invalid, not an implicit request to change anonymous defaults. Old functions keep their anonymous route. No pure getter advertises a node that old functions never emit. Applications can retain a stable indicator ID alongside their row ID and apply copied shadows to it after submission. Bool return keeps existing changed semantics, not validity; invalid local parts report INVALID_ACTION and return false. Event result.valid is false on local descriptor rejection; later capacity/layout failure remains a frame diagnostic rather than an invented changed/result interpretation. Group additions belong in cui_radio_group.h, preserving existing result types: ```c cui_radio_group_result cui_radio_group_with_parts(cui_context *, cui_id, const cui_theme *, const cui_radio_group_item *, size_t count, cui_id *selected, cui_radio_group_state *, cui_radio_group_options, const cui_selection_indicator_parts *, size_t part_count); cui_radio_group_event_result cui_radio_group_events_with_parts(cui_context *, cui_id, const cui_theme *, const cui_radio_group_item *, size_t count, cui_id *selected, cui_radio_group_state *, cui_radio_group_options, const cui_selection_indicator_parts *, size_t part_count, cui_selection_handler); ``` part_count must equal count<=64; a zero-count group allows NULL parts/zero count under its existing empty-group rules. Item and part identities are stable by item identity, not array index when reordering. Preflight rejects full-ID duplicates across group root, all item rows and all indicator parts before reduction. Copy the <=64 part descriptors into bounded stack storage before invoking any owner callback. Caller storage may then change after return; no pointer enters paint. The item array retains its existing borrowed/no-mutation callback contract. ## Collision and failure boundary requiring explicit approval Local structural validation (nonzero, root/part distinct, group cardinality and pairwise full-ID uniqueness) can occur before Base and submit no semantics, callbacks, layout or value writes on rejection. Numeric/style/theme validation retains each existing facade's rules; do not expand legacy behavior accidentally. There is no public current-frame layout identity query/reservation API. Semantic queries omit passive boxes; cui_bounds may be previous-frame. A component must not duplicate Core's private folded-ID hash to pretend it checked collisions. Thus collision with already submitted application boxes, internal conditional parts/tooltip IDs, or distinct IDs sharing a folded hash is caught by existing Core begin_box registration at paint submission. At that point Base and owner callbacks may already have run, as with existing composition/capacity failures. This proposal does NOT promise rollback of input, owner callbacks or state for such late failures. Do not use a known stale bounds/semantic query as preflight. Recommended first contract: retain that existing failure boundary, document it, and test it precisely. Local descriptor rejection is early/atomic; a global/folded collision is a frame diagnostic that suppresses ambiguous element styling through the existing Core guard. If acceptance requires no reduction/callback for every global collision, stop implementation and separately review a Core batch identity reservation design. A read-only query alone cannot prevent later callback/content composition from taking an ID. No new Core query, reservation or input dispatch architecture is approved or implemented by this checkpoint. Callbacks may accept/reject the requested owner value exactly as today. Do not mutate/free active state, options' borrowed arrays/strings/resources, theme or item arrays, destroy the context, or recursively submit the same owner. Style callbacks remain refinement-only. Descriptor values are captured before callbacks, so changing external caller descriptor storage cannot redirect this submission. Custom indicator/content callbacks may compose balanced child UI under existing rules, but must not reuse row/indicator IDs or change owner geometry after the owner has been captured. No new callback or dispatch sequence is introduced. ## Internal painter change Extract existing Checkbox_ex body to one private renderer accepting a captured indicator ID argument (0 for all old calls). Change only the existing indicator `cui_begin_box(ui, 0, paint.indicator)` to use that argument. Keep column/spacer, glyphs, spring state, styles, semantic owner, focus, label, content and tooltip in place. Old ex/source/bool/events preserve their exact chain and reduce once; new wrappers preflight/capture parts and reach the same renderer once. Events forwarding must route to the named source branch without reducing a second time. Apply the same parameterization to Radio_ex's private painter; keep ignored Checkbox-only extension fields ignored. Parameterize the separate group renderer with a captured optional part array; old group functions pass no array and retain all anonymous IDs. New group functions select each copied item indicator ID but still execute the single group Base/event call. Do not synthesize extra wrapper boxes, interactions, semantics, focus stops or pointer hitboxes for naming. New explicit IDs occupy named-ID registration slots and can alter descendant Clay auto IDs in the opted-in route. Node count need not change, but naming is not free identity capacity and is not promised to be byte-identical internally. Legacy routes must retain exact IDs, capacity boundaries, command streams and pixels. New route budgets, registration failures and new collision opportunities are explicit tests, not silently inherited parity assumptions. ## Shape, clip and shadow contract Named indicators remain ordinary paint boxes. Shadow lists are copied by the existing element setter after composition; no list or descriptor is retained by the component. Checkbox style refinement can change indicator radius/corners and size; Radio uses its existing size/2 circle. Callers supply matching radii when applying shadows. Shadow does not infer circle shape or a custom glyph alpha mask. DROP/INSET follow current caster/radii, ancestor masks and opacity, with existing phase ordering and local child-overflow rules. Label-row bounds and indicator bounds differ; tests must assert the actual caster is the indicator. Disabled, checked/mixed and invalid states do not create a second semantic control. Custom indicator content can still be independently clipped by its own descendants. ## Acceptance and future bridge mapping Prove old ex/source/bool/events Checkbox routes and individual/group/events Radio routes unchanged with command/pixel, capacity/identity and genuine queued input regressions. Named tests cover all check states, enabled/disabled/invalid, bounded labels, design sizes, spring and custom indicator/style callbacks, content order, source pointer-focus policy and event owner/observer ordering. Explicitly count Base requests/callbacks once. Local invalid descriptor/cardinality/duplicate tests must show no reduction or semantic submission; late full/folded collision tests must assert the documented composition-failure boundary without claiming rollback. Also cover stable reordering, omitted owners, copied descriptors surviving callback storage mutation, current-layout move/resize, actual DROP/INSET software pixels, matching circular/custom radii, clipping/opacity, no extra focus/input/semantic records, command/node/ID capacity failures and recovery. Browser headless probes and language examples follow implementation; none run for this proposal. Current bridge paints Checkbox/Radio through boolean convenience facades in `src/bridge/cui_bridge.c:4636–4651`; RadioGroup uses its own retained group path. Future MAIN_PAINT_PART maps to the explicitly named indicator for these families, while an explicit ROOT target remains the full row. The bridge owns stable per-node/per-item IDs and copied <=8-layer style values; no frontend derives private salts. Only nodes opting into indicator styling use named composition; unset style preserves legacy anonymous paths. Explicit empty style still requires a named route so it can clear component defaults without meaning unset. Hidden, deleted/reused and reordered retained nodes obey bridge generation/lifetime rules. Never map MAIN silently to a label row because its indicator is still anonymous. All five typed language facades need the same declared target capability and copy/error/clear semantics. That rollout and the remaining78-family ownership matrix stay pending, rather than marking Checkbox/Radio or shadow authoring full. ## First implementation evidence Eight additive entry points share the old private Checkbox, individual Radio and RadioGroup painters with only indicator-ID parameters; every legacy route passes 0/NULL. Group descriptors are locally validated and copied before Base callbacks. No Core source, identity query/reservation, renderer or dispatch path changed. Existing public options/state layouts and old component defaults remain intact. All changed C sources/headers/tests use clang-format23.1.2 before generation. A capture-only harness was compiled against the existing pre-refactor ownership libraries before any new source build. Its external24 command/software pairs live in `tests/unit/named_selection_legacy.golden`; adjacent provenance records known 94654394 source, GCC16.2.1, library/harness/binary/fixture SHA256 and exact capture flags. The capture ran through the private-Xvfb wrapper. Expectations were never computed from the new implementation. Hashing uses owned scalar values, literal text/bitmap bytes and actual software output, not pointer addresses or padding. Font-free software omits text commands; explicit stub metrics supply layout. The regression then checks all24 old-facade scenes and24 corresponding unstyled named scenes against those frozen outputs: Checkbox ex/source/bool/events, individual Radio ex/bool, group and group-events in three state/disabled scenes. New tests independently exercise genuine queued requests, accepted owner state, immutable event snapshots, group owner-before-observer order, captured descriptor storage surviving callbacks and reorder, custom style/indicator/content order, local rejection without semantics/model/callback effects, and approved late full/folded collision diagnostics after exactly one accepted owner request. Current-layout indicator geometry, mixed DROP/INSET actual software changes, explicit Checkbox/circular Radio radii, ancestor clip/opacity and absence of indicator semantics are checked for all eight named routes. A1..16 element-budget sweep compares old/named Checkbox and group failure/count boundaries. The focused strict portable Release build used the existing build-shadow, nice19, CPU0 and -j1. Wrapper checks passed7/7: new named fixture, legacy Checkbox source/motion, RadioGroup, control/selection events and prior component-shadow ownership. Canonical SDK/distribution/consumer-skill resources are regenerated. Installed skill tests passed17/17; SDK checksum, distribution and skill freshness checks passed, as did the78-entry manifest check and clang-format23.1.2 dry-run. No new browser/GPU/sanitizer or foreign-builder evidence, no renderer pixel-equivalence claim and no all78-family completion claim is added. Bridge MAIN indicator mapping and consistent Python/Node/TypeScript/Go/Rust layer authoring remain subsequent mandatory slices; the current C capability does not complete those beta rows. --- ## Native decoded video with SDL software-mixer audio: integration checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/NATIVE_VIDEO_AUDIO_INTEGRATION.md # Native decoded video with SDL software-mixer audio: integration checkpoint Status: design/probe only, based on `95527cf2` (audio service `ef93fec5`, controller foundation, SDL transport). No production/example integration changed. The next deliverable should be a runnable native video **with sound** example for an explicit supported local-file profile, rather than more disconnected foundation APIs. Hardware audibility remains a manual validation claim. ## What exists, and the actual gaps | Existing source | Actual behavior | Required integration decision | | --- | --- | --- | | `examples/video_player/main.c:requested/iterate` | Controlled requests, owner-thread state, SDL monotonic wall-time advance, 3-slot decoded frame leases; paused seek preview replaces model position with acquired video timestamp. | Audio mode must use observed consumed media frames exclusively; wall time and preview timestamp must not move audio position. | | `examples/video_player/decoder.c:decode` | Local-file FFmpeg video worker, FFV1 fixture, bounded RGBA slots, seek/flush/stale-publication guards. Video PTS subtracts **video stream start_time**; AVIO interrupt currently observes shutdown, not seek. | Add an example-private common-container-origin mode/metadata and cancellation audit; unchanged stream-relative origin is insufficient for arbitrary A/V offsets. | | `examples/video_audio_ffmpeg` | PCM-only, common container origin, fixed stereo48k output, SWR drain, bounded linear replay/trim seek, <=10s timeline. | Admit a usable muxed PCM fixture; reject unsupported input explicitly. Do not advertise the browser MP4/AAC or WebM/Opus sample as supported native sound. | | `examples/video_audio_sdl` | Callback-free owner pump, exact successful-put minus queued-input prefix, fixed both-end F32/stereo48k/ratio1. | Schedule pump during all active playback, preserve fault/reset semantics and add sticky device-change invalidation. | | `cui_sdl3_run` / `cui_sdl3_size` | Callback-main runner protects reentry and supports live native modal resize; UI idle switches callback hint to waitevent. | Keep runner and invalidate while playing/loading/seeking so sound is not dependent on user input. No nested event pump or blocking decode in frame callback. | | `cui_window_host` / SDL3 backend | Window query includes fullscreen; action enum has no fullscreen action, SDL handle is private. Existing native video explicitly omits fullscreen. | This is an existing native gap, not behavior available to preserve. Add a narrowly coordinated SDL host fullscreen action before claiming fullscreen support; keep browser fullscreen unchanged. | Core/Base/components remain codec/platform free. No public framework schema or playback state machine is required for audio. A narrowly typed optional native host function for fullscreen, if approved, is adapter work and must be reviewed separately from this example's private session API. ## Supported first consumer example Prefer a new optional `examples/video_player_audio` using the existing callback runner and video lease adapter, with an independently testable private session controller. Retain the existing silent example/explicit silent mode for video-only tracks. Audio-open/decode/output failure must be a visible failure in audio mode; never silently claim successful sound by switching to silent playback. Initial documented input profile: immutable regular local Matroska, FFV1 SDR video and stereo S16LE PCM audio at48k or44.1k, known nonnegative common container origin, fixed layouts/rates, duration <=10s, bounded raster/packets/frames as the existing adapters. Generate a 2-second 64x32 red/blue clip plus signed PCM impulses (or an explicit manual-listening tone fixture) locally. The same consumer command can play that actual muxed file with SDL's real default output **only when a human explicitly runs it**; automation forcibly selects dummy. Include an exact FFmpeg command for converting a user's short local clip to the supported profile, with license/size/quality tradeoffs and no automatic conversion/download. This is useful native video with sound for that profile. It is not a general MP4 player, and must say so in title/status/readme. AAC/Opus priming, compressed seek, long files, arbitrary metadata/edit lists, playback rates and codecs stay a scoped followup; current browser Opus/AAC sound evidence does not establish native support. Rate capability/control must be absent in audio mode (rate fixed1). Audio is unmuted by default in the explicit interactive sound example, not hidden behind a fake volume control unsupported by the current transport. ## Session timeline and presentation Use one immutable source ID and one owner session generation. Keep an explicit mapping to the audio controller's generation (it starts at1 and increments on successful seek) and the video generation; compare both before publishing state. Do not assume unrelated counters remain aligned after a partial failure/reopen. Require video and audio normalized timestamps from the same rational container origin. Proposed compatible video-adapter extension: an example-private open mode that validates known origin and computes each PTS with `av_rescale_q` into48k integer ticks, subtracting the same normalized container origin used by audio. Expose copied origin/clock metadata for an owner compatibility check. Preserve existing stream-relative open behavior for the silent example. Reuse the same 3-slot lease engine rather than copy its decoder implementation. Admission must reject unknown, incompatible or negative normalized timestamps; no guessed independent stream-zero reset. An alternative smaller first step can explicitly reject any video/container origin mismatch, but cannot be called general A/V origin support. The initial probe below uses equal zero origins deliberately. Each owner iteration: process host input, validate session/format state, pump SDL, copy audio snapshot, then assign confirmed position=`position_frames/48000.0` for the mapped generation. Never add `cui_sdl3_frame_delta` to media time. Acquire the latest due video lease at that position, dropping older queued frames; keep the previous lease until synchronous renderer consumption completes, then release exactly once. Retain the last valid frame during underrun. A late video decoder may drop frames without advancing audio; a late audio decoder produces tagged underrun padding and stalls media time. No worker calls CUI, SDL event pumping, window actions or renderer APIs. The audio clock is mixer-input consumption. It advances in mix bursts and may lead physical sound by unknown downstream latency. Due-frame selection proves synchronization against that observable boundary, not lip-sync at speakers. Report that boundary in example status/documentation; do not invent a DAC correction. Paused seek has a separate presentation preview. Quantize/clamp the committed target to an integer48k frame, quiesce/discard output, then seek audio and video. The earliest video frame at/after target may be displayed while paused, but its frame PTS must **not replace** the confirmed audio target. Once playing, do not present that future preview as due until the audio clock reaches its PTS; retain an explicitly labeled preview/blank until then. The current silent example's preview acknowledgement is unsuitable for this mode. EOF policy for the first profile: require matching known audio/video timeline endpoints within one video-frame rounding interval and reject large mismatches at admission. Actual audio/controller EOF plus drained media controls finish; container duration alone must not finish before the last audio sample. Continue acquiring video through the terminal audio time, retain the final frame, stop feeding redundant padding, and show ended only after current media drains. A video tail beyond audio needs a later explicit clock policy, not accidental wall clock fallback. Unknown duration and unequal-track-end recovery are deferred. ## Owner transactions, faults and resource lifetime Play succeeds only after video metadata/origin validation and audio prefill; set confirmed playing only after audio output start succeeds. Pause calls audio pause first (freeze/reconcile), copies final consumed position, then confirms paused UI state. Failure leaves session failed/paused with no fictitious success. Audio mode does not make automatic worker waits in a UI callback: readiness is polled and loading/seeking schedules another owner frame. Seek computes the next session state, pauses/quiesces audio, discards queued old output and requests both workers. Confirm the new generation/target only after both requests are accepted; asynchronous readiness remains loading/seeking. If one side accepts and the other fails, never roll back counters or resume the old session: keep output quiescent, report error and require explicit whole-session reopen/reset. Old leased pixels stay valid until released, but cannot enter the new generation. Play during pending seek is a requested intent applied after both new-generation workers are ready, not permission to mix stale PCM. On a failed SDL put, no additional acknowledgement is possible across its unsubmitted ticket. Pause/discard and reset from the last acknowledged source frame, or destroy/recreate the whole session. Record error before cleanup; do not hide partial failure behind a new healthy UI generation. A failed stop/clear is not release authority. Preserve live host/output/service and retry cleanup; never free service userdata before successful controller join. Source-read I/O can still delay joining; no hard shutdown deadline is claimed. Shutdown ordering: stop owner pumps/input, pause/quiesce/discard audio, successfully destroy/join audio controller, destroy its FFmpeg service, remove/quiesce device watch and destroy SDL output, release video lease after last renderer use, close/ join video worker, then destroy Core/window/font. A failure at an ownership boundary preserves that resource; do not continue freeing objects it can reach. Initial-open failure must unwind only resources actually acquired. ## Device-format invalidation policy Observed format mismatch currently faults before consumption credit, but a format change and restoration between owner polls is not observable from format snapshots. For real output integration, add a private SDL event watch whose only userdata is a dedicated atomic invalidation endpoint (no host/UI/sink pointer). After SDL audio init and paused stream open, register the watch before validating format/starting the generation. Any output-device ADDED, REMOVED or FORMAT_CHANGED notification conservatively sets a sticky invalid flag, including notifications for other output devices. No filtering/remapping or silent default migration is assumed. The backend `format` check must include this flag under the same stream transaction before queue reconciliation. Never clear it on seek or restore it merely because the current format matches again: require explicit whole output/ controller recreation and fresh validation. A late startup notification may fail closed and require retry. Ensure those SDL event types remain enabled and no application event filter suppresses them. Pinned3.4.18 source evidence: `src/events/SDL_eventwatch.c` holds its watcher-list mutex across callback dispatch and uses the same mutex for removal. Remove from the owner outside every callback and outside stream/device locks; it waits for in-flight dispatch before endpoint free. Callback performs only atomic store, never CUI, allocation, output pause, locks, wake userdata or SDL lifecycle calls. This avoids an unbounded retired-endpoint pool on the inspected build. Do not infer generic cross-version quiescence from the API name; rerun concurrent actual watch/removal tests on every admitted SDL build. OS notification guarantees and physical hotplug behavior still need platform validation; synthetic SDL events prove sticky handling/lifetime only, not real hardware notifications. Do not advertise universal dynamic-device recovery from those fixtures. ## Resize and fullscreen Keep `cui_sdl3_run`, layout from `cui_sdl3_size`, ordinary responsive controls and borrowed frame leases. Modal resize can delay owner pumping and exhaust the bounded audio queue; SDL then emits silence and media time stops after queued media drains. Owner resumes/reconciles safely. Continuous sound throughout an arbitrary modal stall is not promised by callback-free pumping. No worker or event watch attempts to repaint or pump the UI during the stall. Fullscreen is missing from the audited native example. Preferred next action: coordinate a minimal optional SDL host `set_fullscreen` operation with observed window-state confirmation (plain bool/types, no SDL handle in public types), and wire the existing capability-gated video request to it. Native example needs no Core fullscreen schema; `cui_video_view.fullscreen` already exists. Only set the confirmed view after observed success; keep resize/aspect/lease logic unchanged. A private example using `SDL_GetWindows` to guess the backend's window is rejected as ambiguous ownership. If the integrator defers that host action, explicitly retain the current native omission and do not claim fullscreen preservation/ implementation. This decision must be settled before final consumer-example scope. ## Reviewable implementation slices and evidence 1. New private session controller + combined no-window fixture. Reuse production audio decoder/output and actual video worker; add common-origin video mode and sticky device invalidation in separately coordinated existing adapter files. Assert actual PCM/sample counts, colored decoded pixels selected against observed mixer clock, pause retention, seek target versus preview, two-track EOF, stale generation, injected one-sided seek failure and shutdown ownership. 2. New runnable optional sound player using existing UI controls/runner, supported muxed fixture generation, explicit help/errors, rate omitted. Implement the approved fullscreen action or document the existing omission. External CMake harness builds needed targets only; preserve exact SDL/FFmpeg pins and license audit, adding no codec dependencies to Core. 3. Private-Xvfb native smoke with SDL dummy audio: presented red/blue captures, pause/seek and generation, resize, fullscreen if available, mixer-frame counts, no desktop/physical audio. Continue independent headless non-window tests and strict GCC/Clang ASan/UBSan CI. Manual real default-device launch/listening is separate evidence, never an automated side effect. Root owns canonical build/CI, metadata and consumer skill guidance/regeneration. Production work waits for review and explicit ownership of existing video/native host files. No browser regressions or manifest parity promotion follows this plan. ## Actual combined feasibility result An external no-window harness compiled **unchanged** production video decoder, audio controller, FFmpeg audio service and SDL output from this checkpoint. Strict GCC16 C11/Werror and ASan/UBSan each passed2/2 wrapper CTests (local mux fixture plus combined session). Actual SDL runtime: `SDL-release-3.4.18-0-g829a65d76`, driver=dummy. Exact libraries: avformat/avcodec 63.1.102, avutil61.1.102, swscale10.1.102, swresample7.1.102; CLI n9.0.2. No Core context, window, renderer, actual device or network was opened. The harness muxes20 actual FFV1 red/blue frames with96000 stereo S16 PCM frames, asserts actual decoded RGBA colors for every acquired due lease, observes media advance only after real asynchronous dummy draining, freezes position/lease on pause, coordinates seek57600/1.2s across both workers, verifies exact terminal media frame96000 and both decoder EOFs, then releases/joins in ownership order. It does not prove nonzero video-origin handling, unequal end policy, presentation pixels, device invalidation, physical sound or the proposed fullscreen action. Retained reproducible harness and builds: `/home/matteo/.cache/cui-validation/video-audio-hookup-probe/{probe.c,fixture.py,CMakeLists.txt,build,build-san}`. Run with dedicated home-cache TMPDIR through `scripts/test_local.py --build-dir .../build -- -V` (or `build-san`). Complete probe source follows so this design checkpoint is reproducible without relying on retained cache files. Extract the three blocks into an external directory; replace CMake ROOT with the checkout path. Configure normal and sanitizer builds (`-DCMAKE_C_FLAGS=-fsanitize=address,undefined`), build, then run each through the private wrapper. This appendix is a design experiment, not a new installed production example. ### Probe `CMakeLists.txt` ```cmake cmake_minimum_required(VERSION 3.20) project(probe C) set(CMAKE_C_STANDARD 11) set(CMAKE_C_STANDARD_REQUIRED ON) set(CMAKE_C_EXTENSIONS OFF) set(ROOT /home/matteo/.cache/cui-worktrees/video-audio-integration) find_package(PkgConfig REQUIRED) find_package(Threads REQUIRED) find_package(Python3 REQUIRED COMPONENTS Interpreter) pkg_check_modules(DEPS REQUIRED IMPORTED_TARGET sdl3=3.4.18 libavformat=63.1.102 libavcodec=63.1.102 libavutil=61.1.102 libswscale=10.1.102 libswresample=7.1.102) add_executable(probe probe.c ${ROOT}/examples/video_player/decoder.c ${ROOT}/examples/video_audio_host/host.c ${ROOT}/examples/video_audio_ffmpeg/decoder.c ${ROOT}/examples/video_audio_sdl/output.c ${ROOT}/examples/video_audio_sdl/sdl.c) target_include_directories(probe PRIVATE ${ROOT} ${ROOT}/include) target_link_libraries(probe PRIVATE PkgConfig::DEPS Threads::Threads m) target_compile_options(probe PRIVATE -Wall -Wextra -Wpedantic -Werror -UNDEBUG) enable_testing() add_test(NAME fixture COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/fixture.py ${CMAKE_CURRENT_BINARY_DIR}/media) set_tests_properties(fixture PROPERTIES FIXTURES_SETUP media) add_test(NAME combined COMMAND probe ${CMAKE_CURRENT_BINARY_DIR}/media/fixture.mkv) set_tests_properties(combined PROPERTIES FIXTURES_REQUIRED media TIMEOUT 20 ENVIRONMENT SDL_AUDIODRIVER=dummy) ``` ### Probe `fixture.py` ```python import pathlib,struct,subprocess,sys p=pathlib.Path(sys.argv[1]);p.mkdir(parents=True,exist_ok=True) (p/'video.raw').write_bytes(bytes((255,0,0,255))*64*32*10+bytes((0,0,255,255))*64*32*10) (p/'audio.raw').write_bytes(b''.join(struct.pack(' #include #include #include static void delay(void) { struct timespec t = {0, 1000000}; thrd_sleep(&t, NULL); } static void prefill(video_audio_host *h) { for (int i = 0; i < 10000; i++) { video_audio_snapshot s = video_audio_poll(h); assert(!s.failed); if (s.pcm_frames >= 1024) return; delay(); } assert(0); } static void frame(video_decoder *v, uint64_t g, double due, video_lease *held, bool *have) { video_lease next = {0}; assert(!video_decoder_poll(v).failed); if (video_decoder_acquire(v, g, due, &next)) { assert(next.frame.frame.generation == g); assert(next.frame.frame.timestamp <= due + 0.000001); const unsigned char *p = next.frame.frame.bitmap.pixels; assert(next.frame.frame.timestamp < 1 ? p[0] > 240 && p[2] < 10 : p[2] > 240 && p[0] < 10); if (*have) assert(video_decoder_release(v, held)); *held = next; *have = true; } } int main(int argc, char **argv) { assert(argc == 2); assert(SDL_setenv_unsafe("SDL_AUDIODRIVER", "dummy", 1) == 0); assert(SDL_Init(SDL_INIT_AUDIO)); video_decoder *v = video_decoder_open(argv[1], 1, 1); assert(v); video_audio_ffmpeg *a = video_ffmpeg_create(argv[1], (video_ffmpeg_limits){0}); assert(a); video_sdl_output *o = video_sdl_open(4800, 1024); assert(o); video_audio_host *h = video_audio_create((video_audio_config){ 4800, 512, video_ffmpeg_interface(a), video_sdl_interface(o)}); assert(h); video_lease held = {0}; bool have = false; prefill(h); assert(video_audio_play(h)); for (int i = 0; i < 10000 && video_audio_poll(h).position_frames < 12000; i++) { assert(video_sdl_pump(o)); frame(v, 1, video_audio_poll(h).position_frames / 48000.0, &held, &have); delay(); } assert(have); assert(video_audio_poll(h).position_frames >= 12000); assert(video_audio_pause(h)); uint64_t paused = video_audio_poll(h).position_frames, revision = held.frame.frame.bitmap.revision; for (int i = 0; i < 40; i++) { assert(video_sdl_pump(o)); assert(video_audio_poll(h).position_frames == paused); delay(); } assert(held.frame.frame.bitmap.revision == revision); assert(video_audio_seek(h, 57600)); assert(video_decoder_seek(v, 2, 1.2)); assert(video_decoder_release(v, &held)); have = false; prefill(h); assert(video_audio_poll(h).position_frames == 57600); assert(video_audio_play(h)); for (int i = 0; i < 10000 && !video_audio_poll(h).ended; i++) { assert(video_sdl_pump(o)); frame(v, 2, video_audio_poll(h).position_frames / 48000.0, &held, &have); delay(); } assert(video_audio_poll(h).ended); assert(video_audio_poll(h).position_frames == 96000); assert(have); for (int i = 0; i < 1000 && !video_decoder_poll(v).eof; i++) { frame(v, 2, 2.0, &held, &have); delay(); } assert(video_decoder_poll(v).eof); assert(video_ffmpeg_poll(a).video_packets == 20); assert(video_decoder_release(v, &held)); assert(video_audio_destroy(h)); video_ffmpeg_destroy(a); assert(video_sdl_destroy(o)); assert(video_decoder_close(v)); printf("PASS combined real FFV1+PCM, dummy mixer clock, red/blue due frames, " "pause, seek57600, EOF96000; SDL %s\n", SDL_GetRevision()); SDL_Quit(); return 0; } ``` --- ## Optional native video audio host: design checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/NATIVE_VIDEO_AUDIO_PLAN.md # Optional native video audio host: design checkpoint Status: proposal only. Native playback is still explicitly silent. This document adds no implementation or parity claim. Audit baseline: video integration `9d4914830f29bcdd8b12517f21841fbdae17f631`; browser audio proof does not establish native audio support. ## Existing implementation and the necessary boundary `examples/video_player/decoder.c` owns one local-file FFmpeg demuxer on its C11 worker. It selects only video, discards other packets, converts to RGBA, and blocks when its three reusable frame slots are occupied. Generation checks and explicit frame leases protect pixels through renderer consumption. The UI in `main.c` advances the silent `cui_video` timeline using `cui_sdl3_frame_delta()`. Its fixture explicitly uses `-an`. Neither that fixture nor the native screenshot tests exercise audio. Audio therefore requires a coordinated host implementation, not merely opening an output device. Two readers must never call `av_read_frame()` on one format context. Blocking video publication must not prevent feeding audio. Separately subtracting each stream's start time would destroy intentional A/V offsets. Keep Core, Base, components and their existing public headers unchanged. Add an optional application host alongside this example, with platform-free C11 status, command and PCM types; FFmpeg and SDL types stay in private implementation files. The existing timeline remains host-driven. No framework audio dependency, codec, thread pool, network loader, or device initialization is introduced. The current exact audited FFmpeg dependencies are libavformat 63.1.102, libavcodec 63.1.102, libavutil 61.1.102 and libswscale 10.1.102. The installed libswresample 7.1.102 is a practical optional conversion dependency, but is not currently a dependency of the example. A production slice must explicitly pin and audit it in the external harness, recording version, configuration and license with the other FFmpeg libraries. The locally audited FFmpeg build is GPLv3-or-later; MIT host sources do not change linked-library obligations. Do not silently install or fetch another codec stack. SDL's repository fallback is pinned to `7f3ae3d57459e59943a4ecfefc8f6277ec6bf540`; system SDL currently satisfies an SDL >=3.2 requirement rather than that exact source revision. `cui_sdl3_create()` initializes VIDEO only. The optional host must separately balance AUDIO subsystem ownership and close audio before destroying the window host. SDL runner callbacks and all CUI calls remain on the owner/UI thread. The runner's idle waits reset its frame delta, making that delta unsuitable as an audio master clock. Window actions do not supply audio controls. Existing VideoPlayer requests expose play, seek, skip, fullscreen and rate, but no volume or mute request; host configuration can supply initial gain without inventing framework capabilities. ## Minimum implementation decision Start with local files, one selected audio stream, rate exactly 1, and explicitly supported PCM layouts converted on the decode worker to interleaved float32, 48 kHz stereo. Reject unsupported layouts, invalid timestamps, discontinuities and oversized data with actionable status. Files without audio may retain the existing explicitly silent clock. Failure to open audio for a file containing an audio track must fail audio playback or require an explicit user-selected silent fallback; it must not report successful sound output. Use one demux/decode worker initially. It owns the format, both codec contexts, resampler and conversion scratch. Drain each codec correctly around send/receive EAGAIN and EOF. Publish video without blocking audio: replace only unleased queued video frames, dropping superseded video as needed. Never overwrite a leased frame. If no video slot is free, skip conversion/publication of that frame; continue draining codecs. PCM publication may wait on a bounded ring, with stop/seek commands waking that wait. The audio callback never waits for the worker. There is no unbounded demux packet spool: retain only the current packet and codec-required references, reject a packet above a documented byte limit, and bound scratch dimensions/sample counts before allocation. FFmpeg internal allocations and device/OS buffers are outside the host-owned memory bound. Suggested initial host limits: 250 ms PCM (12,000 stereo float frames, 96,000 bytes), three existing video slots, one packet capped at 8 MiB, and a configured maximum decoded audio frame/sample count. Exact limits become tested constants, not tunable promises without validation. Deeply interleaved or malformed media can exceed these limits or starve output; expose buffering and ultimately a bounded-progress failure rather than grow a packet queue or discard audio packets. A later independent demux/audio/video worker design may improve this case, but requires byte-and-count-bounded queues and command cancellation at every wait. It is unnecessary for the initial local-file slice. The output callback copies available PCM and fills any remainder with silence. It performs no allocation, decoding, CUI call, blocking wait, or host destruction. It maintains a bounded ledger of generation, media-frame ranges and inserted silence. A small lock protecting ring/ledger operations is permitted only after measuring bounded critical sections; no FFmpeg, UI or device calls occur under that lock. UI commands use acknowledged serials and generations, not raw pointers passed through callback events. ## Clock and synchronization contract Use a common source timestamp origin with rational rescaling. Preserve audio and video start offsets; account for codec priming, sample trimming, resampler delay and final drain. The first implementation must reject cases it cannot map rather than silently reset each stream to zero. `swr_get_delay()` and actual converted sample counts determine bounded conversion output and timestamp bookkeeping. The master is output progress through the media-frame ledger, never decoded or submitted sample count and never UI frame delta. An injectable output transport reports consumed frames and queued latency; deterministic tests provide exact consumption. For SDL, distinguish frames pulled into SDL processing from frames physically heard. SDL 3.2 exposes queued input bytes and device buffer size, not an exact DAC presentation timestamp. Callback byte requests can overestimate actual demand. Do not use those requests as a hardware clock or equate `SDL_GetAudioStreamQueued()` with converted/device-pending bytes. The first SDL transport must document its software-consumption clock and bounded latency estimate, keep SDL staging bounded, and measure callback-consumed PCM rather than requested bytes. It cannot claim sample-exact audible A/V sync. If the chosen SDL stream mode cannot expose sufficient actual consumption to maintain this contract, stop at the injected transport slice and require a separate output-clock design review. No fallback to a submission clock. Exact hardware presentation timing is a later backend-specific extension. On owner-thread polls, copy a coherent clock snapshot, advance the existing `cui_video` by the nonnegative media-time difference, and select the latest video frame due at that clock (with a stated small scheduling tolerance). Never count inserted underrun silence as media progress. Enter BUFFERING, freeze at the last consumed media sample, prefill, then rebase after restart. Video may drop late frames but may not pull audio forward. Active playback requests regular owner polls independently of UI animation. Use an owner-controlled bounded timer/frame schedule first; a future SDL user-event wake requires runner dispatch proof, coalescing, failure fallback and shutdown lifetime tests. Worker callbacks must never invalidate CUI directly. ## Controls, generations and destruction - Play starts only after format negotiation and prefill. Pause pauses output, acknowledges its effective state, and freezes the consumption clock; samples already in hardware impose a documented audible latency. Resume rebases from retained media position. UI state must not race ahead of command acknowledgement. - Seek increments the shared generation and serial, pauses/quiesces output, clears pending PCM/SDL staging, flushes both codecs and resampler, seeks the common source, then trims decoded audio to the requested sample boundary. Discard stale worker output and clock snapshots. Keep old video leases valid until released, but never render them in the new generation. A video preview timestamp must not independently rebase the audio clock. Paused seek stays paused. Restart/loop use the same transaction. - Remove RATE capability and reject non-1 rate requests in this slice, including the example's current 1x/2x toggle. Pitch-preserving rate conversion is deferred. - EOF means demux EOF, both codecs and resampler drained, all media PCM consumed, and the documented output tail drained. Video EOF or container duration alone cannot end audio. Keep the final video frame leased as today. Distinguish EOF, underrun and decode/output failure. - Close first rejects commands and detaches notifications, signals stop and wakes all producer waits. Quiesce/detach the output callback before freeing its ring or userdata; pause alone is not proof of callback quiescence. Join the worker without holding a callback/queue lock, release renderer leases on the owner, destroy streams/device, free codecs/queues and balance AUDIO initialization. The exact SDL stream-lock/detach ordering requires an implementation-level review and test. No raw host pointer survives close in an event or callback. Output loss, seek, failure and close must all unblock bounded producer waits. AVIO interruption observes shutdown; bounded seek latency for arbitrary local formats remains unproven and is not advertised. ## Reviewable slices and validation gates 1. Add an optional platform-free controller/clock/ring with injected decoder and output transport. Strict C11 warnings and deterministic threaded tests cover actual sample values and frame counts, wrap/overflow, partial callback reads, starvation/silence clock freeze, delayed UI polls, A/V offsets, pause/resume, seek trimming, stale generations, EOF tail, output loss and close while every producer wait is occupied. Test callback quiescence and late notification rejection after host free. This slice alone is not native audio support. 2. Add real FFmpeg audio decoding/resampling and deterministic muxed fixtures: known stereo tone/impulses with red/blue video markers, different source sample rates, nonzero offsets, audio shorter/longer than video, and no-audio input. Assert decoded PCM counts, channel content and tolerances, timestamp mapping, seek content and resampler drain. Include deliberately excessive packet/frame sizes and invalid timestamps. Existing `-an` fixtures remain video-only proof. 3. Add SDL output and example UI integration only after the clock gate above. Run `SDL_AUDIODRIVER=dummy` with an explicitly selected nonphysical device and verify submitted/consumed ledger counts, pause, clear, restart, EOF and teardown. Dummy timing is integration evidence, not proof of physical sound or latency. Linux native window tests run only through `scripts/test_local.py` with its private Xvfb; never fall back to a desktop display. Prefer the injected sink for exact timing assertions; dummy driver tests use bounded timeouts, not brittle wall-time equality. No automated real speaker/device activation. Use a standalone external CMake harness building only needed example/library and test targets, pinned audited dependencies, strict warnings, and the native wrapper's CTest result. Add ASan/UBSan and concurrency stress where supported. No broad rebuild or package/skill regeneration is needed for this proposal; production integration must update corresponding metadata and consumer guidance through the integrator. macOS and Windows need actual focused build/test proof; Linux dummy output cannot establish their device behavior. Manual opt-in speaker checks must later assess audible A/V alignment, device switching, latency, Bluetooth and long playback. Hardware timing, rate changes, volume UI, network sources, multitrack selection, edit-list coverage and universal codec support remain explicit gaps. ## Primary API references - [SDL audio callback contract](https://wiki.libsdl.org/SDL3/SDL_AudioStreamCallback): callback thread/stream lock, approximate requested counts, no callback destruction. - [SDL queued input bytes](https://wiki.libsdl.org/SDL3/SDL_GetAudioStreamQueued): input queue accounting differs from converted output and is not a hard queue cap. - [SDL device format/buffer size](https://wiki.libsdl.org/SDL3/SDL_GetAudioDeviceFormat) and [pause](https://wiki.libsdl.org/SDL3/SDL_PauseAudioStreamDevice). - FFmpeg's installed pinned `libswresample/swresample.h` documents conversion bounds, `swr_get_delay`, timestamp conversion and draining; implementations must validate against these pinned headers rather than assume newer API behavior. ## Implemented independent foundation; transports still proposed `examples/video_audio_host` now implements the first injected-only controller slice without modifying existing decoder/UI/Core code. It owns a bounded PCM ring and a separately bounded per-output-frame media/silence ledger, one decoder worker, generation-aware sticky cancellation and synchronous output-quiescence requirements. Render/submission does not advance the clock. Ordered actual consumption acknowledgements advance source-frame position only for media; silence, duplicates, reordering and stale generations cannot advance it. The example README/header specify the consumption and lifetime contract for review. In particular output stop must prove no active/future callbacks and release host references on discard; failed stop leaves storage allocated. Seek is paused, asynchronous worker work with an explicit generation change, not a claim of sample-accurate container seek. Input is already normalized contiguous 48 kHz stereo float PCM; timestamps, priming and sample conversion remain future transport work. Ordinary bounded mutex sections are used, not a hard realtime or lock-free callback guarantee. Host-owned allocations and both queue bounds are explicit; external service/device allocations are excluded. The standalone strict-C11 fixture uses injected decoder/output operations only. No SDL/FFmpeg transport, physical device, UI integration or audible native audio support has been added. Those slices remain gated on review of actual consumption accounting and platform-specific quiescence/latency evidence. Foundation validation: six focused offline cases passed through the private native-test wrapper in normal and ASan/UBSan Linux builds. They include exact known PCM and consumption counts, independent queue exhaustion, stale returned DATA after seek cancellation, blocked read/seek shutdown, output callback join before host free and concurrent stream accounting. This validates the injected contract only; it supplies no evidence of a physical output consumption clock. ## Real-adapter feasibility checkpoint (no adapter implementation) Audit after foundation `c63af6de`: installed SDL 3.4.18, FFmpeg n9.0.2, libavformat/libavcodec 63.1.102, libavutil 61.1.102, libswscale 10.1.102 and libswresample 7.1.102. Inspected existing headers and the SDL fallback source at `7f3ae3d57459e59943a4ecfefc8f6277ec6bf540`. No device was opened. The only added executable is an offline mutex observation fixture; controller production code is unchanged. The following real transport design still requires review. ### Three different boundaries | Boundary | Evidence available | Meaning and limit | | --- | --- | --- | | Host/SDL submission | Successful host render ticket and `SDL_PutAudioStreamData` | Bytes accepted into a software queue; not playback progress. | | SDL stream input consumed by mixing | Successful-put byte ledger minus remaining input queue, under the restricted invariant below | Actual asynchronous removal of this stream's PCM for SDL mixing; useful software clock, not device acceptance. | | Backend accepted / physically presented / acoustically audible | No equivalent portable SDL timestamp/count API established in this audit | Backend buffering, OS routing, DAC, speakers and propagation are outside the proven clock. These stages are themselves different. | The recommended first SDL clock is explicitly **SDL software-mixer input consumption**. Native audio playback need not wait for a universal hardware presentation timestamp, provided this boundary, queue bounds and latency limits are visible. Do not silently equate the controller's generic consumption wording with acoustic truth. The adapter's example-local documentation and UI host status must name its chosen clock boundary before integration. Source evidence: the pinned stream implementation invokes its get callback before removing input; it returns the bytes actually retrieved to its caller. `SDL_GetAudioStreamQueued` reads remaining input bytes. Equal-rate operation with unity frequency ratio and zero resample offset bypasses its resampler. These facts permit a restricted drain calculation, not a general resampling clock. See [pinned SDL stream implementation](https://github.com/libsdl-org/SDL/blob/7f3ae3d57459e59943a4ecfefc8f6277ec6bf540/src/audio/SDL_audiocvt.c). The pinned device loop drains bound streams, invokes postmix, then calls the backend `PlayDevice`; postmix is consequently before backend acceptance. See [pinned SDL device loop](https://github.com/libsdl-org/SDL/blob/7f3ae3d57459e59943a4ecfefc8f6277ec6bf540/src/audio/SDL_audio.c). Neither callback request sizes nor postmix buffer length prove that this particular stream supplied all those frames. SDL can mix automatic silence. [Postmix documentation](https://wiki.libsdl.org/SDL3/SDL_SetAudioPostmixCallback) also permits changing channel counts/rates and describes synchronous callback replacement. [Get-callback documentation](https://wiki.libsdl.org/SDL3/SDL_SetAudioStreamGetCallback) provides a refill opportunity, not a post-play acknowledgement. ### Restricted same-format software-drain adapter Use one private logical playback device and one privately owned bound stream. Normalize decoder output to native float32 stereo 48 kHz on the worker. Require stream source and destination to remain float32 stereo 48 kHz, unity frequency ratio, default channel maps and no format changes for the whole generation. Check the bound destination and postmix spec, not just the requested open spec. An unsupported obtained format or hot device change stops playback with an explicit error; do not continue with an unproved sample mapping. SDL can still convert final float values to a physical integer format without changing the selected software frame-count boundary; no physical-clock claim follows. For a generation, maintain checked successful-put bytes P, remaining queued input bytes Q, and previously acknowledged frames A. All values are private to this stream and measured coherently with its stream lock: ``` frame_bytes = 2 * sizeof(float) = 8 software_drained_frames = (P - Q) / frame_bytes new_consumption = software_drained_frames - A ``` Only acknowledge this ordered prefix, never all submitted frames or callback request sizes. Require nonnegative/aligned Q, Q <= P, monotonic drain, and a prefix within outstanding controller tickets. Cap both software queues well below SDL's int-count clamp; C=12,000 means at most 96,000 input bytes. Prove the identity on each admitted SDL build using unbound-stream actual reads, then a private dummy-output postmix fixture. No resampling, format-track changes, foreign puts/gets/clear calls or silent queue reset may occur inside this identity. A copied frame value of zero can be valid decoded media; only controller-added underrun padding is tagged nonmedia and excluded from media-time advancement. A refill callback may submit a bounded aligned chunk when requested. Count P only after a successful put. Postmix observes actual remaining queue after the mixer's read and acknowledges newly drained entries. Do not synthesize consumption from postmix silence. Input drain can include frames in SDL's current mix buffer that are never accepted if the backend fails afterward; status must say software consumption rather than successful hardware playback. There is a transaction limitation in the existing foundation: render reserves a ticket before SDL put can fail, and no unsubmit API exists. On put failure, immediately stop feeding and surface an adapter failure on owner poll. Quiesce, discard and require seek/reset from the last acknowledged source position or destroy/recreate before retry. Never acknowledge the failed put or send later chunks across its unsubmitted sequence gap. No Core schema change is necessary; minimal example integration can keep this failure in host-owned state. ### Pause, seek, flush, close and locking Open/configure while paused, validate format, then install callbacks and resume only after the host is ready. A failed start must leave no callbacks running; resume/setup failure branches need injected coverage before claiming the foundation start contract is met. All SDL operations run outside the controller mutex. Callback paths take stream lock then controller lock, never call CUI, never wait for owner/UI, and never change device/callback lifecycle themselves. The owner must never acquire those locks in the reverse order. The proposed stop sequence is: pause the logical device, detach postmix with `SDL_SetAudioPostmixCallback(..., NULL, NULL)`, detach get callback using its stream-serialized setter, then observe a final coherent input-drain prefix. The first setter waits out the current device iteration; the stream setter serializes with an active get callback. Report final consumed frames while the host is still logically playing, then return success to freeze owner-visible state. Failure to prove either detach keeps the host allocated, as the existing foundation requires. Verify exact order against both supported builds and injected failures; pause alone is not the quiescence proof. For pause, retain stream queue and outstanding tickets for ordered resume. For seek/close, after detachment acknowledge only the final drain, then clear the stream and discard mappings. Queue reduction caused by clear is **discard**, not consumption. `SDL_ClearAudioStream` does not retract already submitted hardware buffers: see [clear contract](https://wiki.libsdl.org/SDL3/SDL_ClearAudioStream). Only then may the host increment generation/reset queues or free storage. Remove all retained raw host/wake pointers and queued notifications before success. No old postmix/get event may acknowledge a new generation. A small adapter mailbox can report errors; owner polling can initially provide all UI scheduling. The foundation ended flag means all media reached the chosen software boundary. It does not prove the speakers finished. Likewise pause/seek can leave a hardware or OS tail from the previous position. Application queue latency has a known capacity bound; total audible latency does not. Device buffer size/frequency is only a latency component, not a promise about OS/backend queues. Start with no acoustic compensation promise; a later optional calibrated video delay can use an explicitly estimated latency. There is no hard A/V error bound under UI/OS stalls. Report synchronization against the software clock and defer measured speaker/display alignment to explicit manual platform checks. ### FFmpeg service: bounded asynchronous conversion and seek Keep one worker as sole owner of the format, both codec contexts, frames, packets, scaler and resampler. Its injected audio read can demux/decode video encountered on the way to audio and publish into a bounded video lease queue. Video publication drops superseded unleased frames rather than blocking audio. Never add a second reader to the same `AVFormatContext`. Deep interleave and per-packet/decoded-frame limits remain explicit rejection/buffering cases. Use `avcodec_send_packet`/`avcodec_receive_frame` with EAGAIN drain discipline, then null-packet EOF drain. The [FFmpeg 9 decoding contract](https://ffmpeg.org/doxygen/9.0/group__lavc__decoding.html) defines those operations; it does not make concurrent seek/flush safe. An owner seek publishes a serial/generation and atomic cancellation ceiling only. AVIO interrupt checks those atomics; it never calls CUI or touches a context being mutated by another thread. Old results, including successful DATA, remain quarantined by generation. The first implementation can reopen the local file on the worker for each seek to avoid relying on demuxer-specific recovery from an interrupted AVIO operation. This adds I/O and has no universal seek-latency bound. Preserve file-only protocol restrictions and bounded copied paths. Maintain one rational container origin for both streams. Decode preroll, warm the resampler, map output frames to that origin, then trim converted output to the requested 48 kHz target before returning contiguous DATA. Do not independently zero each stream or reset source time at each converted chunk. Gaps, negative preroll and fractional-rate rounding need actual muxed impulse/video-marker fixtures. Never subtract a guessed fixed resampler delay from every timestamp. Proposed initial limits: mono/stereo input, fixed rate per stream (8-192 kHz), no midstream layout/rate changes, decoded frames <=8,192 input samples, one bounded converted spill buffer <=65,536 stereo output frames. Query `swr_get_out_samples` immediately before conversion, reject a bound beyond that buffer, use returned sample counts, and hand back chunks no larger than the controller's D. Do not repeatedly feed input into insufficient output space; that can grow internal buffered conversion data. `swr_get_delay`, checked `av_rescale_rnd`/`av_rescale_delta` and optional `swr_next_pts` provide accounting primitives, not a complete timestamp policy. In particular `swr_next_pts` uses 1/(input_rate*output_rate) units; automatic timestamp compensation must stay off for rate 1. Any timestamp operation that changes SWR state requires recomputing its output-space bound. Drain codec and converter at EOF; recreate/reset both for seek. The pinned installed `libswresample/swresample.h` is authoritative; see also the [FFmpeg 9 resampler API](https://ffmpeg.org/doxygen/9.0/group__lswr.html). Start the actual decoder proof with lossless PCM audio muxed with the existing lossless video markers, then 44.1-to-48 kHz conversion/seek impulse fixtures. Do not claim AAC/Opus priming parity yet. The pinned codec header's `AV_CODEC_FLAG2_SKIP_MANUAL` exports skip metadata instead of automatic skipping; manual plus automatic trimming would double-skip. A first PCM-only subset can reject nonzero codec padding/preroll and defer compressed-audio trimming until fixtures establish the selected mode. Missing/unsupported timestamp or edit-list cases must fail explicitly instead of returning invented contiguous timestamps. `avformat_seek_file` uses the selected stream timebase (or AV_TIME_BASE for -1) and ignores AVSEEK_FLAG_BACKWARD; choose min/target/max deliberately and decode forward rather than assume that flag establishes an exact landing sample. ### Smallest real integration sequence and pins 1. Implement the FFmpeg service behind the injected interface and prove actual decoded/resampled PCM offline against the controller. No output device yet. 2. Prove same-format SDL queue-drain arithmetic with actual unbound streams, then a dummy logical output's postmix callback. Cover zero-fill versus media zeros, partial reads, pause retention, clear-as-discard, failed put/setup, generation-stale callbacks, stop failure, format mismatch and teardown. 3. Only after those proofs, add an optional example combining the shared demux service and SDL output. Owner polls source-frame position, converts to seconds at 48 kHz, advances the existing video model by coherent deltas and acquires due video leases. Seek must coordinate video/model/audio generations; any partial failure leaves the whole example paused/failed. Preserve leased pixels until renderer release. While playing/buffering, owner schedules frames independently of UI input; callbacks do not call CUI. Rate stays 1 and RATE capability is omitted. No-audio tracks retain the explicit silent mode; audio output failure cannot silently become successful sound playback. Reuse existing exact FFmpeg pins and add explicit optional libswresample `=7.1.102` with version/buildconf/license audit. The observed n9.0.2 package has `--enable-gpl --enable-version3`; its recorded GPLv3-or-later linked obligations remain unchanged. Record the entire linked configuration rather than infer LGPL from the library name. SDL remains zlib-licensed, with existing fallback commit pin above. Installed SDL 3.4.18 is an audited system version, not proof that every `>=3.2` build behaves identically. Admit only tested builds for the drain adapter; retain a runtime version/configuration record and require the same queue probes when changing that set. No new dependencies enter Core, and no dependency is installed by fixtures. macOS/Windows native compile/dummy proof and physical playback checks remain separate prerequisites for platform claims. ### Mutex observation, not a realtime guarantee The new Unix-only `bench_mutex.c` uses injected services and CLOCK_MONOTONIC to measure 4,000 render-plus-consume pairs of 256 frames, with a contending decoder worker, C=12,000 and D=256/4,096. It validates PCM classes and actual counter identity while recording p50/p95/p99/max and observations exceeding the 5.33 ms block duration. There is no deadline pass threshold. It measures controller calls, not SDL callback duration, device latency or a worst-case scheduler bound. Worker critical sections include finite validation/copy loops; the callback uses an ordinary C11 mutex, so priority inversion and scheduling delays remain risks. Run it through the private test wrapper using the standalone Release build: `python scripts/test_local.py --build-dir BUILD -R video_audio_mutex_observation -V`. The example README records the observed run. Future SDL dummy tests must also measure the complete get/postmix path under decoder contention, queue pressure and UI stalls; move validation/copies or redesign synchronization if measured budget risk is unacceptable. Neither successful sanitizer tests nor a fast microbenchmark establishes hard realtime behavior. Alternatives retained for review: immediate acknowledgement after put is a submission clock and is rejected; using only postmix buffer length incorrectly counts SDL-generated silence and other streams; an unbound conversion stream's manual read is valuable conversion proof but is not real device progression; platform-specific hardware presentation timing could improve latency estimates but would add another optional backend and platform validation scope. The restricted bound-stream software-drain clock is the minimum useful native playback route, with honest latency limits, rather than a reason to block native sound until universal DAC timestamps exist. Checkpoint validation: Release and ASan/UBSan standalone wrapper runs passed 7/7 (six controller cases plus the new observation fixture). The Release probe recorded p99 render/consume pair durations about 31 microseconds and observed maxima 427/106 microseconds for D=256/4,096 on this Linux GCC host. The unpaced loop also produced underrun padding, which was separately counted and did not advance media time. Full SDL callback timing and hardware playback are untested. --- ## Configured Badge authoring: Node/TypeScript checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/NODE_CONFIGURED_BADGE.md # Configured Badge authoring: Node/TypeScript checkpoint Design only, against root `956a853c`; no bridge/Node production change or executed validation. Existing `badge(key,text)` remains the standalone kind11 text pill. All 78 entries remain; configured foreign Badge and complete Icon authoring are pending in every language until their individual gates pass. ## Actual authority and gaps There is no `include/cui/cui_badge.h` at this revision. Badge authority is `include/cui/cui_components.h:470–515`, Icon is `include/cui/cui_icon.h`. `src/components/cui_components.c:cui_badge_compose` owns corner placement, content-before-indicator order and configured artwork fallback. `src/components/cui_icon.c:cui_icon` owns Icon option validation/layout/paint; `src/base/cui_icon.c` owns source copies, immutable masks and bounded versions. Current bridge `src/bridge/cui_bridge.c` renders BADGE with `cui_badge()` and ICON with named artwork plus positive visual width/height only. Its parent admission does not make BADGE an arbitrary-content container. Node mirrors those limitations (`badge()` kind11, `icon()` kind50). Adding JS methods alone cannot reach `cui_badge_ex` or `cui_badge_with_icon`. | C surface | Required foreign mapping; no reduced substitute | | --- | --- | | Badge defaults/options | COUNT/DOT/ICON, full `size_t` count/maximum, four control sizes, design size, optional explicit RGBA including alpha0, copied name and named-icon string | | `cui_badge_ex` | Arbitrary ordered child subtree; count0 omits only indicator; count>maximum displays maximum+; maximum0 retained | | `cui_badge_with_icon` | Owned Icon resource + complete Icon options; `submitted` separate from `icon_error`; structural rejection invokes no child callback | | `cui_badge_indicator_id` | Existing indicator target, not wrapper/artwork; absent on count0; pure ID is no presence guarantee | | Icon source/state | name/path/raw SVG/empty, source replacement/reload, limits/defaults, explicit owner lifetime, counters/errors, collect after render consumption | | Icon geometry | All six sizes, custom/inherited text size, explicit width/height presence including0, design size/rem, affine six floats and identity/rotation helpers | | Icon paint | Explicit/inherited tint presence, opacity presence including0, debug placeholder, complete applicable box style and numeric constraints | | Icon semantics | Standalone named image/decorative contract; configured Badge forcibly decorative, sole Badge STATUS remains | | Icon utilities | Catalog count/name/path/default, query/embedded asset copied bytes, headless prepare, copied bitmap/paint bounds; named/spinner convenience routes tracked separately | | Custom C loader | Cannot pass JS function/user pointer through a record or invoke it during Core composition; explicit policy decision below | ## Recommended narrow bridge prerequisite (proposal, not exported API) Use one reusable app-owned Icon resource abstraction, then configured Badge node composition referencing it. Do not invent a Badge-only record containing merely SVG/size/color. Do not put `cui_icon_state*`, `cui_box*`, callbacks or pointer-sized fields into foreign payloads. Root must approve the C bridge schema/signatures before implementation; the sketch below does not reserve symbols or enum values. ``` const art = app.icon_resource({source:{kind:'name',value:'check'}, limits:{...}}); const badge = configured_badge('unread', { variant:'icon', count:123n, maximum:99n, size:'medium', designSize:'inherit', color:[220,30,40,255], name:'Unread', artwork:{resource:art, options:icon_options({size:'custom',customSize:20, transform:icon_rotation(Math.PI/4), color:[240,120,30,255], style:{...}, constraints:{...}})} }).children(button('open').label('Inbox').on_click(openInbox)); // After successful or failed step: immutable current-frame result, never replay. const result = badge.latest_result(); // frame, submitted, iconError, frameStatus ``` Proposed bridge operations: complete-group/version/layout support query; app-local generation-tagged resource create/destroy/source/limits/reload/get-info; full copied Icon options configure/get; dedicated configured Badge create/configure/ get-result; copied catalog/asset/bitmap utilities. An atomic full replacement setter must retain the previous resource/options/strings on invalid input or allocation failure. Exact native descriptor sizes, reserved words, active-field rules and optional-symbol list require a separate reviewed C checkpoint, not guesswork here. A new explicit configured Badge kind is preferable to silently changing kind11 child acceptance/rendering. Only it is a content container. C bridge recursion is the `cui_button_content_fn`: it renders each child once, never invokes JS inside Core, and ordinary child actions dispatch synchronously after stepping. Mount preflight rejects absent/partial capability before creating any nodes. ## Complete options, ownership and numeric rules Represent every Icon option field with its actual presence flag; do not equate zero with absent. Copy style and constraints into stable bridge-owned storage and reconstruct private native pointers only during synchronous submission. Include all `cui_box` scalar/color/edge/corner/flag fields in the shared style mapping; document which Icon deliberately overrides: width/height/fixed/percent/max and paint padding are resolved by `cui_icon`, not reapplied by JS. Constraints include explicit maximum0; minima win, then padding/border floor. Do not implement layout or SVG parsing/rasterization in JS. Preserve native normalization versus rejection for opacity/style exactly; do not reject inactive poison differently without an explicit binding-level contract and tests. Use BigInt for count/maximum and resource/frame generations. Query native size_t width; accept the entire target domain, reject overflow before conversion. All floats require checked double→float conversion under the corresponding C active field rules; enum/boolean/presence/reserved validation is explicit. Strings are owned strict UTF8 with NUL policy and published byte bounds; never silently truncate. Native C records are native-endian; any internal LE Buffers require fieldwise conversion, including size_t/u64, as with the localized TimeField facade. Each app owns resources; handles reject cross-app/stale use. Node configuration retains referenced resources. Destruction while referenced rejects or marks a retired handle whose storage survives final render; choose one precise policy in C review (recommend reject while referenced). Replacement/omission/removal cannot collect old masks before the synchronous renderer finishes its borrowed list. Close/error/destroy must release exactly once; poststep callbacks may mutate next frame state, never invalidate the just-rendering list. No implicit file/network I/O. For host-provided sources, prefer copied path→SVG asset maps with revision/reload, served by a C-resident loader. This covers deterministic application assets without foreign callbacks during Core. It is **not** equivalent to arbitrary deferred `cui_icon_loader_fn`; do not advertise that callback API as supported. If full callback equivalence is required, review a pre-frame host preparation service separately. Eager JS loader calls at setter time change callback/error timing and are not a transparent implementation of C's next-prepare/reload semantics. ## Results, alternatives and acceptance slices Structural invalidity submits nothing and renders no child. Artwork invalidity, NOT_FOUND/PARSE/LIMIT/ALLOCATION occur after content and shell and preserve them; report `submitted=true` plus exact Icon error, independent from Core/frame failure. Do not translate every Icon error into a failed whole frame or swallow it. Badge overrides decorative and missing inherited size/color only; explicit artwork options win. No extra image semantic, focus stop, click target or JS reducer. A JS-only wrapper of ordinary `icon()` loses styles/state/errors and cannot preserve Badge zero-flow placement. A Badge-specific SVG wire repeats an incomplete Icon API. Direct JS rendering callbacks inside Core violate the existing host model. Recommended slices: (1) reviewed reusable owned Icon bridge/options contract; (2) its resource/old-consumer tests; (3) configured Badge C recursion/results; (4) Node/TS complete authoring, examples and root acceptance. Catalog/spinner/custom loader omissions must stay explicit until implemented; none closes source parity. Meaningful gates: frozen scalar Badge/Icon ABI/pixels/callback counts; complete old/partial optional group refusal; every size/variant/count0/max0/full size_t; all option presence/zero/constraints/style/transform/opacity combinations against independent ordinary C Icon trees; exactly-one STATUS and child activation; first-frame/resize/nested/clip/omission/reappearance; malformed SVG/missing assets/ resource cap and allocation injection with shell retained; copied-source replacement and old-list masks alive; cross-app/stale/refcount/destruction/reentry/exception; strict TS typed configs/results and actual English UI with count/dot/custom-SVG badges around buttons. All native execution uses private Xvfb; browser headless. No public implementation, generation, build or tests ran for this checkpoint. --- ## NumberInput numeric CHANGE observer proposal Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/NUMBER_EVENTS_SLICE.md # NumberInput numeric CHANGE observer proposal Design only, audited at `4ecd73dd`. NumberInput's owner is a **double**; its borrowed `cui_edit` is a separate draft. Propose one aggregate committed numeric CHANGE observer per submission. Do not reconstruct REQUEST, per-event CHANGE, COMMIT or SUBMIT from the existing aggregate result. No Core, bridge, dispatcher, legacy callback, state layout or generated SDK change belongs in this proposal. ## Actual reduction and rendering The public [`cui_number_state/options/result`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_numeric.h#L23) separate owner value, initialization/last-value bookkeeping, focus history, invalid draft state, composition and scroll state. `cui_number_result.changed` is final numeric inequality, `submitted` is an aggregate Enter flag, `step_direction` is the last attempted step direction, and `error` is an edit result, not a transaction rollback indication. None is an event count or a unique cause. [`cui_base_number_input`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_numeric.c#L292) rejects a nonfinite owner, multiline editor, invalid bounds or absent required pointers before normal reduction. Initial submission or an owner differing from `last_value` formats that owner into the draft. This can change edit revision without changing the owner. The reducer then captures its numeric original, handles composition/input/steps, parses the final draft, publishes semantics, updates `last_value/was_focused`, sets `changed = *value != original`, and invalidates on numeric change. Valid draft text updates the owner even outside minimum/maximum until Enter or editable blur requests clamping. Incomplete drafts such as `-` can change edit revision while preserving the last owner and setting `invalid`. Rejected text can report INVALID_ARGUMENT while leaving the prior valid owner/draft. Enter sets `submitted` even without a numeric change and without the activation API's nonrepeat qualification; blur can normalize without Enter. The reducer's final commit flag coalesces the frame; it does not identify one commit event. Preserve all these behaviors rather than adding new emitters inferred from flags. [`cui_numeric_try_step`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_numeric.c#L251) starts from the owner, uses a parsed draft when available, records attempted direction, and only writes the stepped owner after rewriting the draft succeeds. The public [`cui_number_step`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_numeric.c#L93) uses `step_by(user,value,sign)` as a **step magnitude policy**, not a resulting-value callback. It is called before bound no-op checks; finite positive magnitude, finite arithmetic and an actual numeric difference are required. Do not call it twice, turn it into a new request callback, veto it through an observer, or change its timing/side effects. A step at a bound may run policy and emit no numeric CHANGE. On commit, [`final parse/clamp`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_numeric.c#L426) writes the clamped owner and tries to normalize the draft. If normalization fails, owner is set back to the **parsed draft value**, not necessarily the entry owner, while the first edit error is retained. Earlier mutations are not rolled back wholesale. Initial draft synchronization and later operations can also leave error results; no proposal may equate `error != OK` with "nothing changed." [`cui_number_input`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_numeric.c#L79) validates Styled metrics, width and string storage first, then reduces Base exactly once, then paints from `s->edit`, composition/invalid state and computed metrics. It does not read the owner again to rebuild displayed text after Base. Its semantic value is [`float-clamped`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_numeric.c#L150), but that does not narrow the actual double owner. Payloads must not reuse semantic float as numeric truth. ## Exact additive API proposal Place declarations in a separate `cui_number_events.h`; Base declarations depend only on existing Base/numeric and shared metadata headers. The Styled declaration may share that header as with other family facades. ```c typedef struct { cui_component_event_metadata event; double before, after; } cui_number_change_event; typedef void (*cui_number_change_fn)(void *user, const cui_number_change_event *event); typedef struct { cui_number_change_fn change; void *user; } cui_number_event_handler; typedef struct { cui_number_result control; size_t change_count; /* Actual observer invocations: zero or one. */ } cui_number_event_result; cui_number_event_result cui_base_number_input_events( cui_context *, cui_id, cui_str name, cui_number_state *, double *, cui_number_options, cui_number_event_handler); cui_number_event_result cui_number_input_events( cui_context *, cui_id, const cui_theme *, cui_str name, cui_number_state *, double *, cui_number_options, cui_number_event_handler); ``` An empty handler still performs ordinary reduction; a non-NULL user pointer with an absent callback is accepted and ignored, matching immediate Input/selection handlers. `step_by/step_user` remain independent legacy policy callbacks. No retained registration is needed: handler/user are borrowed for this call only. Capture the valid finite double owner at entry, before native mutation; after native reduction finishes capture its finite final double once. Emit iff exact C numeric inequality `before != after` holds, independent of error and handler presence. With an observer, freeze both doubles and shared metadata, then invoke it once after Base's final bookkeeping/semantics/invalidation and before Styled painting. Count actual calls only. An absent observer yields zero count, while `control.changed` retains native meaning. Preserve every control result field. Do not infer change from draft revision, text length, `submitted`, step direction, error, callback count, normalization, or consumed-event bits. Use a private common implementation for the Styled seam, leaving its legacy entrypoint on the no-observer path; never run a legacy Styled call followed by a second Base call. All returns after mutation must run the change finalizer, even when an edit error is already set. A later Styled paint/layout error cannot undo an already completed owner change/callback. Preflight rejection before reduction notifies nothing; nonfinite entry values are invalid input, not a NaN CHANGE. Callback count does not certify rendering or input validity. Metadata is CHANGE with the NumberInput root ID, source UNKNOWN and HAS_FRAME only when `cui_frame_sequence` proves the same nonzero active submission before and after reduction. That API excludes inert/layout-only ancestry and protected phases. No index/source/activation flag is inferred from an aggregate. Notify only for ordinary active, enabled, editable submissions: inert/layout-only/outside-frame, disabled and readonly calls do not notify. Still run the original reducer exactly once, preserving any legacy synchronization/normalization and diagnostics; lack of callback is not a promise of no model mutation. Draft synchronization and normalization are not evidence of physical input. Compare legacy/facade passive state and owner behavior explicitly in tests rather than silently fixing Base. ## Equality, normalization and lifetime Keep finite double precision with no float conversion, epsilon, decimal rounding or bitwise comparison. Thus `+0.0` and `-0.0` compare equal and do not emit; distinct representable finite values do, including subnormals. Several changes ending at the entry value emit nothing. This is aggregate numeric observation, not edit revision observation or an audit log of intermediate values. `cui_number_parse` accepts strict finite ASCII decimal/exponent grammar, rejects NaN/Inf, whitespace, commas and underflow to zero, and accepts representable subnormals. Insertion separately normalizes supported full-width digits/signs and punctuation before validating the candidate draft, with the existing 127-byte limit. Do not add locale-dependent parser policy, enable exponent input when the existing option forbids it, canonicalize signed zero for event comparison, or reformat the owner a second time for notification. Invalid/nonfinite step magnitude or overflow retains the existing no-op policy and emits nothing unless another operation in the same submission actually changed the owner. The payload is pointer-free and copyable beyond the callback. State/editor/value, composition resources and owner/user storage must remain alive until the outer call returns. No context/editor/state destruction, recursive submission, edit mutation, selection changes or composition mutation during observer delivery. The observer may assign a **finite** new application owner value through its own captured pointer, or update unrelated application state. Its event remains the frozen native before/after snapshot and does not recursively notify. Do not update `last_value` or resynchronize the draft afterward: the next submission detects the owner mismatch normally. Current Styled paint still shows the already-reduced draft/semantics, not the observer's newly assigned value; this intentional boundary must be in the public guide and tested. A nonfinite observer assignment makes the next native submission invalid; it is outside the supported owner-update contract. Do not alter `step_by`'s legacy policy contract to enforce these new observer rules. Foreign exceptions must not unwind through C; language adapters would catch/report them after returning from native code in a separate binding integration. ## Evidence and implementation gate Existing [`models`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_numeric.c#L35) exercises finite/subnormal parse, invalid NaN/Inf syntax, locale-independent formatting, dynamic step policy, nonfinite step and overflow. [`number_events`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_numeric.c#L135) covers draft `99`, Enter clamp, invalid `-`, subsequent valid negative text, blur clamp, full-width normalization, readonly, disabled and external owner synchronization. [`number_composition`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_numeric.c#L602) covers IME paths; size, geometry and part-button tests in the same file cover Styled composition. The similarly named `test_input_number_control.c`/`test_input_number_engine.c` exercise formatted text Input, a different control: do not count those alone as proof of NumberInput numeric observation. New headless tests must compare legacy and facade owner, draft, result fields, semantics, focus and geometry. Cover one/multiple steps, changes cancelling to the entry value, repeated Enter without numeric change, clamp on Enter/blur, pending invalid draft, full-width/IME commit versus preedit, Undo/Redo, external owner sync, readonly/disabled and invalid options. Exercise signed zero, adjacent doubles, subnormals, NaN/Inf owner rejection, no-op overflow/bounds and `step_by` call order/ count. Force draft-capacity/normalization errors with actual edit storage to prove postmutation owner-change delivery; do not mirror the reducer in a fake fixture. Test zero/one observer counts, empty handler, ignored user data without callback, retained payload copies and finite observer owner updates with next-frame draft sync. Keep legacy tests unchanged, compile strict C11/C++ headers, and run native CTest through the private headless wrapper before a production slice is proposed. Bridge NumberInput currently queues legacy CHANGE from its aggregate result; its V1 payload remains LEGACY, not the reserved SCALAR tag. No new typed bridge schema, per-event delivery or cross-binding parity follows from this C-only proposal. Implementation checkpoint: the additive C facade is described in [NUMBER_EVENTS.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NUMBER_EVENTS.md) and `cui_number_events.h`. The whole Base wrapper preserves canonical Base Numeric unchanged; the Styled private common seam retains the legacy no-observer path. This does not promote binding coverage or any deferred per-event/commit/submission API. --- ## Rating, Stepper and Pagination CHANGE observers Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/NUMERIC_SELECTION_EVENTS_SLICE.md # Rating, Stepper and Pagination CHANGE observers Design only; audited at `b4146c89`. Tabs is excluded and belongs to its separate workstream. These controls already mutate caller-owned scalar values and return aggregate bools. The smallest compatible facade observes their final committed values, rather than introducing controlled requests or reconstructing activations. No production code, Core routing, bridge schema or generated SDK changes are proposed in this checkpoint. ## Current behavior | Family | Owner and normalization | Input/multiplicity and presentation | | --- | --- | --- | | [Pagination](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_numeric.c#L469) | `size_t *page`, one-based when total is nonzero; zero when empty. Clamps to `[1,total]` before processing input, even when disabled. Bool compares entry and final page. | All queued activations can update the owner. First/Previous/Next/Last use stable part IDs. Numbered buttons map through the **entry normalized page's** item window, while final semantics/Styled paint use the final page's window. | | [Rating](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_numeric.c#L524) | `float *value`; maximum defaults to 5 and caps at 100. Nonfinite owners normalize to zero; finite values round to whole/half steps and clamp to the effective range before input, including disabled/readonly calls. Bool is `!isfinite(before) || after != before`. | Multiple star/clear activations and root-targeted key-down events can coalesce. Pointer left-half selection gives half a star; keyboard/other star activation chooses the full star. Home clears even when `clearable` is false; Delete/Backspace clearing requires it. | | [Stepper](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_numeric.c#L587) | `size_t *current`, zero-based index; clamps to last item, or zero with no items, even when disabled. Rejects missing descriptors with nonzero count and counts over 100. | Multiple activations select the last eligible step. Per-step disabled state gates activation. Status descriptors are caller-owned and **not** rewritten to match selection. Root is a non-tab-stop group; each step is a button. | Public types/signatures and stable part-ID rules are in [`cui_numeric.h`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_numeric.h#L65). No family here has a legacy value-change callback. Rating has readonly in addition to disabled; Pagination and Stepper have only disabled. None has a draft revision or NumberInput's `step_by`, parsing, Enter-submit or edit error result. Do not reuse NumberInput's double payload or add its callbacks to these APIs. All three reducers process existing input then publish semantics/invalidate and return final inequality. They expose neither a per-event result list nor a counter. Returning to the entry value yields false even after several accepted operations. Selecting the already-current step/page or a no-op at a boundary is not a CHANGE, and must not become an ACTIVATE notification through this facade. Their loops use existing activation/target queries; do not add consumption, nonrepeat filtering or new accessibility behavior while adding observation. [`cui_pagination`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_numeric.c#L154), [`cui_rating`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_numeric.c#L229) and [`cui_stepper`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_numeric.c#L296) each call Base once before painting. They subsequently read the owner again. Rating also prepares retained icon resources; failure to prepare artwork is not evidence that Base did not mutate. Stepper's selected index determines the visible "Current" label; nonselected ACTIVE status is presented as Pending, while Error/Complete retain their existing presentation. These painting and ownership rules must remain unchanged in the legacy entrypoints. ## Proposed portable types and entrypoints A separate `cui_numeric_selection_events.h` can include existing numeric types and shared metadata. Keep the three event types distinct so one-based page, zero-based step index and float rating cannot be accidentally interchanged. ```c typedef struct { cui_component_event_metadata event; size_t before, after, total; } cui_pagination_change_event; typedef struct { cui_component_event_metadata event; size_t before, after, count; } cui_stepper_change_event; typedef struct { cui_component_event_metadata event; float before, after; unsigned maximum; /* Effective defaulted/capped maximum. */ bool before_finite; } cui_rating_change_event; typedef void (*cui_pagination_change_fn)(void *user, const cui_pagination_change_event *event); typedef void (*cui_stepper_change_fn)(void *user, const cui_stepper_change_event *event); typedef void (*cui_rating_change_fn)(void *user, const cui_rating_change_event *event); typedef struct { cui_pagination_change_fn change; void *user; } cui_pagination_event_handler; typedef struct { cui_stepper_change_fn change; void *user; } cui_stepper_event_handler; typedef struct { cui_rating_change_fn change; void *user; } cui_rating_event_handler; typedef struct { bool control; /* Original aggregate bool, not validation/render success. */ size_t change_count; /* Actual observer invocations: zero or one. */ } cui_numeric_selection_event_result; cui_numeric_selection_event_result cui_base_pagination_events( cui_context *, cui_id, size_t *page, size_t total, bool compact, bool disabled, cui_pagination_event_handler); cui_numeric_selection_event_result cui_pagination_events( cui_context *, cui_id, const cui_theme *, size_t *page, size_t total, bool compact, bool disabled, cui_pagination_event_handler); cui_numeric_selection_event_result cui_base_rating_events( cui_context *, cui_id, cui_str name, float *value, cui_rating_options, cui_rating_event_handler); cui_numeric_selection_event_result cui_rating_events( cui_context *, cui_id, const cui_theme *, cui_str name, float *value, cui_rating_options, cui_rating_event_handler); cui_numeric_selection_event_result cui_base_stepper_events( cui_context *, cui_id, const cui_step *, size_t count, size_t *current, bool disabled, cui_stepper_event_handler); cui_numeric_selection_event_result cui_stepper_events( cui_context *, cui_id, const cui_theme *, const cui_step *, size_t count, size_t *current, bool vertical, bool disabled, cui_stepper_event_handler); ``` `size_t` payloads preserve the native unsigned width, including Pagination totals near SIZE_MAX; do not pass through semantic float or double. Total/count are by-value context snapshots, not proof of item storage lifetime or immutable items. They distinguish empty zero from a nonempty Stepper's valid index zero. Effective Rating maximum is also a scalar snapshot, not a new range policy. Rating deliberately differs from NumberInput: NaN/Inf input owners are normalized by the legacy reducer rather than rejected. Preserve `before` as its float value and expose `before_finite=false`; consumers must not perform ordinary equality on NaN or assume its payload bits are canonical. `after` is the finite committed rating. Notify for nonfinite-to-finite normalization in an eligible active call, matching the legacy changed condition. For finite values use exact float inequality, no epsilon or double reinterpretation; signed zeros compare equal. Rounded/clamped finite normalization can itself produce CHANGE. Do not claim a pointer/keyboard cause for any of these corrections. ## Delivery, passive behavior and implementation seams Capture the entry owner before native normalization. Run Base exactly once, capture final value and notify once after final semantics/invalidation, before Styled painting. Pagination/Stepper use exact entry/final inequality; Rating also uses the nonfinite-entry rule. Preserve the original bool independently of handler presence and later drawing/resource errors. An absent callback accepts/ignores user data and still reduces. No listener registration, heap allocation or queued payload is needed. Handler/user are borrowed only for the call. Only ordinary active, enabled calls notify; Rating additionally requires not readonly. Require the same nonzero `cui_frame_sequence` before and after native reduction. Emit shared CHANGE metadata at the family root ID, source UNKNOWN, HAS_FRAME only. No event index, source flag, activation snapshot, request or commit/submission reason can be inferred from the aggregate. Suppress notification for inert/layout-only/outside-frame and restricted calls while preserving their legacy reduction, including normalization. **Zero callbacks is not a promise of no owner mutation.** Test this especially for disabled out-of-range pages/indices and readonly nonfinite ratings. Do not patch passive Base behavior as a side effect of an observer implementation. Whole-frame Base wrappers appear sufficient because no Base value callback seam must be preserved. Styled variants need a private common implementation with the old entrypoint using an unobserved Base path and the new entrypoint observing that same single reduction. Do not wrap Styled after it has already painted or submit Base a second time. Native validation/Styled preflight rejection must preserve its existing bool and produce no invented event. A committed normalization/change is still observable if a later artwork, layout or resource error occurs; callbacks do not certify rendering success. Expose no synthetic error field in this result: the legacy Core diagnostics remain the error channel. These are committed observers, not controlled selection: returning void cannot reject, roll back or defer the native write. Pagination's entry-window mapping, Rating's half-step rules and Stepper's descriptor statuses remain family-specific. Do not unify them into a generic list selection reducer or add bubbling/dispatch. ## Callback lifetime and owner mutation policy Payloads are pointer-free and may be copied. Owner pointers, user data, descriptors, titles/descriptions and context resources must remain valid through the outer call and applicable frame rendering. Do not destroy/rebind the owner/context, mutate Step descriptors, recursively submit, or unwind foreign exceptions through C. Update unrelated application state and defer teardown safely. For the smallest first implementation, **owner mutation during the observer is unsupported for all three families**, including Base, to keep one uniform family contract. Styled implementations reread the owner to paint. Unlike NumberInput, whose paint reads its reduced draft and therefore safely defers a finite observer owner assignment to next-frame synchronization, an immediate assignment here can change displayed page/star/current-step state after old semantics were published. Do not silently promise coherent paint/semantics under that mutation. Applications can copy the event and assign the owner after the outer call. A later explicit snapshot-paint design could permit mutation, but requires separate geometry, semantics and lifetime review; it is not needed to ship these observers. ## Evidence and production gates [`models`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_numeric.c#L35) exercises Pagination item windows, bounded output, ellipses and SIZE_MAX totals. The [`other_events`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_numeric.c#L263) scenario covers keyboard Next, same-frame Last/Previous ending at page 99, pointer Last, half-star pointer selection, Rating root keyboard adjustment/clear, readonly Rating, eligible versus disabled Stepper and whole-family disabled input. It runs Base/Styled variations via the existing scene helpers. [`stepper_visible_selection`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_numeric.c#L485) checks actual "Current" painting across selection, and [`rating_star_graphics`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_numeric.c#L516) checks artwork. [`pagination_counter_center`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_numeric.c#L710) checks compact/ noncompact label geometry. These are existing source evidence, not new executed validation for this documentation-only checkpoint. Before production, compare old/new owner, bool, semantics, focus, consumption and geometry in a meaningful headless harness. Cover each Base/Styled entrypoint; normalization with no input; empty/count/total changes; invalid counts/descriptors; Pagination entry-window remapping and SIZE_MAX; multiple changes cancelling to entry; repeated same choice; whole/per-item disabled and Rating readonly; inert/layout-only; real supported pointer, key and accessibility activation; Rating NaN/Inf/out-of-range/half rounding and signed zero; zero/one callbacks, borrowed user data without callback and retained payload copies. Distinguish unsupported or absent accessibility actions rather than simulating parity. Keep legacy tests unchanged and compile C11/C++ headers. Run any native CTest through the private headless wrapper; no build is needed for this proposal. Bridge Pagination/Rating currently convert native results into queued legacy CHANGE, and Stepper uses its existing grouped-selection bridge path. All remain V1 LEGACY payloads; reserved selection/scalar tags do not become supported because these C facades exist. Exact native `size_t` values are not proof of exact existing bridge numeric transport. Binding subscriptions, controlled requests, per-input multiplicity and Tabs remain excluded. ## Implementation checkpoints Pagination now has an additive Base wrapper and a narrow Styled common seam. Legacy paint and reduction remain on their original unobserved path. Stepper has a separate aggregate wrapper/common seam with zero-based exact index payloads; its legacy descriptor statuses and rejection rules remain unchanged. Rating now has a distinct float/nonfinite-aware aggregate wrapper and a narrow Styled common seam. All three families preserve their direct legacy Base path and paint; none adds per-event requests or bridge tags. The implemented ownership restriction remains: callbacks may copy payloads/request deferred work, but owner mutation is unsupported until the outer call returns. --- ## OTP aggregate notification slice Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/OTP_EVENTS_SLICE.md # OTP aggregate notification slice Design checkpoint, audited at `ffb39cd7`. No production, dispatch, bridge or SDK changes in this checkpoint. Prefer one aggregate CHANGE observer first: the legacy result already supplies operation/completion counts, but not intermediate text snapshots or submission intent. ## Existing contracts and important differences [`cui_otp.h`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_otp.h) owns the public state/options/result. State borrows a NUL-terminated caller buffer and capacity; `state.length` is the **target cell count**, not current bytes or an editor revision. Targets are at most 256, including zero. `cui_otp_count` counts UTF-8 code points, not grapheme clusters. Programmatic `cui_otp_set_value` permits arbitrary valid UTF-8 and values longer than the target; there is no 256-byte model bound. It changes no per-frame result and invalidates caller-owned composition sessions. There is no validation callback, editor revision, legacy observer or readonly option. The [Base reducer](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_otp.c#L164) validates state, UTF-8 and options before interaction; it registers a textbox, updates focus transitions, processes existing targeted/unconsumed events, updates blink state and final semantic count/range, then returns `cui_otp_result`. No network verification or credential-validity decision exists. Details that a facade must preserve: - Ordinary text appends only the first ASCII/fullwidth digit, normalizing fullwidth to ASCII; it does not paste all digits from a text event. Ctrl/Meta/Alt text and IME-composing keydown are excluded. A full model rejects more digits. - Backspace removes one UTF-8 code point, and is accepted even on empty text. Accepted ordinary operations increment `change_count`/set `changed` even if final bytes equal the entry bytes. Do not replace this with final inequality. - Each accepted ordinary operation whose resulting count equals the target increments `complete_count`/sets `complete`. Thus deleting an overlength value down to the target can complete; empty Backspace with target zero also completes. Filling, deleting, refilling can produce multiple completions in one call; final text can be incomplete despite `complete=true` earlier in that call. - Composition updates/cancellation can change session/paint without model CHANGE. Commit appends only its first eligible digit; duplicate stale commit does not append again. A successful append increments counts, including completion when reaching the target. Composition events are consumed; ordinary accepted text/ Backspace do not explicitly consume in this reducer. Preserve that distinction. - Capacity/UTF-8/boundary/session errors can coexist with earlier accepted changes. Ordinary append capacity failure sets an error and continues. Composition capacity failure can retain visible preedit. Never gate all observation on an entirely successful `error` result or roll back previous changes. - Disabled prevents input but can report blur/cancel composition; caret time, focus and resource/session bookkeeping are independent of CHANGE. Inert and layout-only behavior must be measured against legacy, not described as frozen state merely because the new observer is suppressed. [Styled OTP](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_otp.c#L4) validates theme/design size and resolves design metrics before Base once. It then paints cells from the final model and active preedit, masking each visible code point with `*` when requested, and updates the text-input rectangle. Base validation failure skips paint; other errors do not. No callback currently sits between reduction and paint. ## Proposed first API New `cui_otp_events.h` includes existing OTP types/shared metadata; old public state/options/result layouts and entrypoints remain untouched. ```c typedef struct { cui_component_event_metadata event; /* CHANGE, aggregate completion frame. */ size_t before_bytes, after_bytes; size_t before_count, after_count, target_length; size_t accepted_count, completion_count; /* Legacy operation counts. */ bool final_complete; /* after_count == target_length, not result.complete. */ bool has_text; cui_str text; /* Final committed bytes, borrowed only through callback. */ } cui_otp_change_event; typedef void (*cui_otp_change_fn)(void *user, const cui_otp_change_event *event); typedef struct { cui_otp_change_fn change; void *user; } cui_otp_event_handler; typedef struct { cui_otp_result control; /* Exact original result, including errors/counts. */ size_t change_count; /* Actual callback invocations, zero or one. */ } cui_otp_event_result; cui_otp_event_result cui_base_otp_events(cui_context *, cui_id, cui_otp_state *, cui_otp_options, cui_otp_event_handler); cui_otp_event_result cui_otp_events(cui_context *, cui_id, const cui_theme *, cui_otp_state *, cui_otp_options, cui_otp_event_handler); ``` Capture entry scalar counts/bytes before reduction, call legacy Base exactly once, then observe `control.changed`, including accepted no-ops and return to entry. Do not replay `control.change_count` callbacks with the same final text. The payload's `accepted_count` and `completion_count` preserve those original counts, whereas outer `change_count` counts actual callbacks. A small whole-Base wrapper suffices; Styled needs a private common seam preserving its preflight, design resolution and verbatim paint, with notification between Base and paint. No Base per-event extraction is needed for this first slice. Notify only in an ordinary active, enabled submission: same nonzero `cui_frame_sequence` before/after, valid entry, and no initial invalid-argument failure. Preserve post-mutation error results and still notify for their accepted changes. Absent callback accepts/ignores non-NULL user and reduces normally. No synthetic notifications for programmatic setter calls, focus/blur, blink, composition-only updates or reading results. Disabled/inert/layout-only calls retain old reduction/result behavior and emit no callback. Metadata is root target, CHANGE, UNKNOWN source, HAS_FRAME only. No source/index/activation can be recovered from aggregate counts, even if only one change occurred. ## Completion is not submission Shared [metadata kinds](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_component_events.h#L10) have no COMPLETE kind. Do not map OTP completion to SUBMIT, COMMIT or surface LIFECYCLE. Enter has no submission branch in the legacy reducer. This first slice exposes completion counts and final completeness on CHANGE, without a separate complete callback/kind. Applications can inspect those counts and choose separate deferred verification work; no automatic verification is implied. Even final equality to target is a length condition, not proof of a valid code, user intent or a fresh transition. An already-full programmatic model emits no completion on submission. A future per-event seam is feasible only by extracting the actual mutation loop and composition-commit helper, notifying at their real acceptance points. It would need event-local before/after text, zero-target/accepted-no-op semantics, post-error ordering and consumption tests. Aggregate counts cannot reconstruct those snapshots, completion-time values or temporal input provenance. Defer it until a concrete consumer needs that additional surface; preserve the old loop exactly if extraction is later authorized. ## Text, ownership and security limits Follow [Input's borrowed-text convention](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_text_input_events.h): when masked, `has_text=false` and empty `text`, including composition preedit; unmasked events expose only final committed text, never preedit or old text. Scalar byte/code-point counts remain visible as existing model metadata; masking is presentation/redaction, not length secrecy, encryption or authentication. No raw code/preedit logging, diagnostics, automatic telemetry or persistence. The payload contains a borrowed `cui_str`, so copying its struct alone does not own its text. Consumers needing retention explicitly call [`cui_component_event_copy_utf8`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_component_events.h#L121) inside the callback with their own maximum byte count, capacity including NUL, and disjoint storage. Preserve that helper's limit/capacity/UTF-8 failure result; never silently truncate or treat copy failure as rejection of the accepted edit. No mandatory allocation/copy, implicit fixed-size array or invented 256-byte bound: a caller can preload arbitrarily long UTF-8 up to its buffer capacity. Only scalar metadata/payload fields remain usable after their explicit copies; text storage remains the caller's responsibility. No old plaintext snapshot or preedit copy is needed to compare aggregate CHANGE. Handler/user are borrowed synchronously, with no registration, replay or teardown hook. Forbid mutation/rebinding/destruction of state, model, composition/session, context or any borrowed storage during callbacks, recursive submission and foreign exception unwinding. Unrelated application state may change. Defer model edits, removal and teardown until outer submission and renderer consumption complete; Styled drawing can borrow model/preedit bytes after return. No safe owner-update promise is offered and no context-destruction guard is added. ## Focused verification and omissions Keep [existing OTP tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_otp.c) unchanged: `models` covers arbitrary/overlength UTF-8 and target validation; `editing` covers fullwidth text, coalesced counts, delete/refill, capacity-after-partial-progress and blink; `composition` covers masked preedit, stale commits, cancellation, focus/disabled, rebound buffers and retained session errors. Extend with paired legacy/new Base and Styled calls checking full result, text/state/session, semantics, focus, text-input rectangle, geometry and masked/unmasked paint: - Multiple edits, return-to-entry, empty Backspace and target-zero completion; delete overlength down to target, multiple completions with final incomplete model, first-digit-only multi-character text/commit, rejected modifiers/IME. - Already-full programmatic input/no callback; nil callback with userdata; actual callbacks/counts and payload scalar snapshots after final semantics, before Styled paint. Distinguish aggregate count from accepted operation count. - Partial accepted changes followed by capacity/UTF-8/composition errors; invalid preflight causes no callback/mutation. No error rollback claim. - Disabled, inert, layout-only, omitted frames and composition-only behavior against legacy; copied unmasked UTF-8 retention across later model changes; masked redaction, copy maximum/capacity failures, overlength byte counts. - Borrowed userdata, deferred removal/teardown, strict C11 and C++ header use; native execution only through the private-display wrapper. No GPU parity claim. [Bridge OTP rendering](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/bridge/cui_bridge.c#L4251) currently uses the old Styled call, maps any edit error to frame error and emits legacy `bridge_change` when `result.changed`. It has no typed completion/count payload. Leave it and Python/Node/Go/Rust notifications unchanged; this native proposal does not imply binding completion support, secret transport policy or registry/schema changes. ## Implementation checkpoint The first aggregate slice now uses a whole-Base wrapper and private Styled common seam; the original Base OTP source and public legacy layouts remain unchanged. Entry capture scans only declared capacity and checks valid UTF-8 before taking scalar snapshots. Delivery follows the real `changed` flag even for accepted no-ops, net-zero edits and post-mutation errors, rather than filtering all errors. Masked text is redacted; retained unmasked text requires the existing explicit bounded copy helper. No COMPLETE kind, per-event extraction or binding tag was added. Isolated strict C11/C++ checks and private-wrapper new/legacy OTP tests cover the implemented contract; root owns build registration/generated exports. --- ## Picker applied observer slices Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/PICKER_EVENTS_SLICE.md # Picker applied observer slices Design-only audit at `ffb39cd7`. No proposed API below exists. Preserve all 78 manifest entries and the existing APIs, options, mutation/paint order and results. These are independently reviewable applied notifications, not controlled requests. ## Actual state, callbacks and timing | Family | Source contract | Observer implication | | --- | --- | --- | | Calendar | [`cui_picker.h`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_picker.h) separates `cui_date_selection {start,end}` from state month/cursor/selecting_end and DAYS/YEARS/MONTHS chooser state. [`cui_calendar_reduce`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_picker.c) mutates these, returns changed/activated/navigated; `submit` registers semantics separately. Base reduces then submits; Styled Base-calls then paints. | Selected dates are the editable value. Display month, focus cursor, chooser page and range-in-progress are distinct presentation/lifecycle state. `navigated` does not mean selected date changed. | | DatePicker | Base trigger updates toggle/dismissal; Base composite reduces only while open, closes on activated single date or completed range, then submits trigger semantics. Styled calls Base, paints trigger, places popup and submits/paints Calendar without reducing again. | Outer ownership must avoid observing nested reduction twice. Opening/closing popup is not date CHANGE. Same-date activation may close without changing value. | | ColorPicker | Caller owns RGBA pointer and HSV/capture state. Base synchronizes HSV when external RGBA differs, registers parts, reduces palette/pointer/key input, updates part semantics/drag bits/last_color and returns final RGBA inequality. Styled calls Base once then paints. | Observe actual RGBA bytes, not internal HSV or drag bits. A hue change on achromatic/black color may have no RGBA CHANGE. No existing request/commit lifecycle exists. | Calendar's only value-related function pointer is `is_disabled(user,date)`, an enablement policy, not an on-change or acceptance hook. It can be called repeatedly while scanning days/year/month availability. Do not turn it into a notification or assume one call per user action. ColorPicker has no value observer callback; palette is borrowed immutable data, not an event handler table. The Calendar reducer repairs invalid presentation state (initial month, cursor, view/page), normalizes month.day and adjusts cursor availability even without selection input. It snapshots date selection after initialization and compares start/end using `cui_date_compare`. Range first activation sets start/clears end and selecting_end; second activation sorts the endpoints and completes the range. Keyboard navigation can move cursor/month without selecting. Year/month chooser navigation changes presentation only. `activated` and `navigated` are aggregates, not event counts or copied evidence. DatePicker closes before adding its modal scope, deliberately preserving input routing. Its Styled path can return false on an invalid viewport after Base has already reduced/mutated selection. Never gate notification solely on its bool. Preserve that bool verbatim rather than repairing legacy behavior in a facade. ColorPicker preserves alpha on palette selection when alpha editing is off; readonly/disabled clear drag state without applying edits. External RGBA assignment before entry resynchronizes HSV but is not a component-applied change. ## Recommended independently reviewable slices Use a new `cui_picker_events.h` including `cui_picker.h` and shared metadata. Dates and colors remain explicit value types, never float packing, strings or void values: ```c typedef struct { cui_component_event_metadata event; cui_date_selection previous, value; } cui_date_selection_change; typedef void (*cui_date_selection_change_fn)(void *, const cui_date_selection_change *); typedef struct { cui_date_selection_change_fn on_change; void *user; } cui_date_selection_handler; typedef struct { cui_calendar_result control; size_t change_count; } cui_calendar_event_result; typedef struct { bool changed; size_t change_count; } cui_picker_event_result; typedef struct { cui_component_event_metadata event; cui_color previous, value; /* RGBA bytes, including preserved alpha. */ } cui_color_change; typedef void (*cui_color_change_fn)(void *, const cui_color_change *); typedef struct { cui_color_change_fn on_change; void *user; } cui_color_handler; ``` 1. **Calendar date selection only.** Add `cui_calendar_reduce_events`, `cui_base_calendar_events`, `cui_calendar_events`, mirroring existing signatures plus date handler and returning `cui_calendar_event_result`. Reduce-only is necessary for custom popup hosts that intentionally submit later. Each invokes its corresponding legacy operation once and compares committed start/end; whole Base includes semantic submission, whole Styled includes paint. No nested observer, no reducer replay. Notify at the outer return, preserving the chosen entrypoint's existing timing and result. Do not expose a submit-only observer. 2. **DatePicker selected dates.** Add `cui_base_date_picker_events` returning `cui_calendar_event_result` and `cui_date_picker_events` returning `cui_picker_event_result`, mirroring old arguments plus date handler. Wrap each whole operation exactly once, with a pre/post date snapshot; no observed nested Calendar facade. Styled notifications occur after popup/focus/paint work, including early returns after applied mutation. Event target is trigger ID; the Base's separate calendar ID remains a rendering/reduction identity. The standalone trigger has no selected-date observer. 3. **ColorPicker RGBA only.** Add `cui_base_color_picker_events` and `cui_color_picker_events`, mirroring old signatures plus color handler and returning `cui_picker_event_result`. Whole-call wrappers compare RGBA fields, preserve bool, and notify after all original state/semantic/paint work. Do not observe HSV synchronization, latent hue, drag start/end or formatting calls. Every initial facade has **zero or one actual callback** per outer submission. Missing handler still mutates normally and yields zero count; unused user is ignored. Several updates coalesce; final equality means no notification. Payload contains previous/final values, CHANGE kind and compound target, UNKNOWN source, actual nonzero active frame with HAS_FRAME only. No event index, activation, physical device, reason or timestamp can be inferred from aggregate flags. Observers are not rejectable and cannot retroactively veto writes or dismissal. Before production, settle minimal new-entry admission checks (nonnull required pointers and nonzero target) without changing old functions' behavior. Preserve legacy passive maintenance, but emit only during active painted non-disabled submission; Color readonly additionally suppresses observations. Calendar has no readonly option. Core inert/modal targeting remains authoritative, not a new picker suppression policy. Test swallowed/consumed event behavior as it exists: these reducers do not uniformly check `cui_event_consumed` in every loop, so do not promise new propagation or consumption guarantees as part of a notification API. ## Explicit exclusions and later alternatives No generic NAVIGATE or popup lifecycle event is in the initial slice. If requested, Calendar presentation notifications need a separate typed snapshot covering month, cursor, chooser view/page/year/month cursor and selecting_end, with specified normalization versus input causes. A month-only payload cannot describe chooser navigation. Do not call it selected-date CHANGE, and do not use result.navigated as a count. Popup open/close outcomes need reasons and owner/focus timing beyond sampling overlay.open. Existing Surface contracts are not automatically inherited. Color drag COMMIT/CANCEL or owner-controlled color requests would require a new reviewed reducer seam/ownership contract; an aggregate bool cannot implement them. A per-event selected-date/color alternative is possible only with genuine loop hooks covering all branches and typed before/after values. It would have different multiplicity and must not silently replace these aggregate APIs. TimeField is a separate family/slice, despite sharing the picker source files. ## Lifetimes, tests and foreign boundary Values/metadata are pointer-free and copyable. Keep model/state/options, locale strings, disabled-policy users, palette, theme and context alive through submission; overlay state and resources retain their existing longer lifetimes. Observers must not mutate/free/rebind these resources or recursively submit UI. Unrelated application flags are allowed; defer omission/teardown until outer return and frame/renderer consumption. Do not dispatch again from result inspection. The facade does not change the existing disabled policy's callback requirements. Existing evidence is [`test_picker.c`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_picker.c): Calendar model/year-grid/events/range/weekend policy/locale/presentation cases, DatePicker popup/focus/escape/outside/disabled cases, and ColorPicker random model roundtrips, channels, palette, alpha, plane drag and readonly/disabled cases. Some tests compile with `CUI_PICKER_BASE_ONLY`; retain both Base and Styled variants where registered. New dedicated tests should pair legacy/facade contexts and compare date/RGBA, state, focus, results, semantics and draw commands. Cover several changes/net-zero within a frame, same-date activation, reversed range completion, month/year chooser and keyboard cursor motion without selection, invalid presentation initialization without notification, disabled-policy scanning and bounded dates, popup-close focus before observer, invalid viewport after mutation, alpha-off palette rules, latent HSV changes without RGBA change, pointer/key edits, readonly/disabled drag cleanup, inert/layout-only silence with preserved maintenance, absent handler, payload copies after later frames, callback/result coexistence and deferred omission. Use real queued input rather than invoking notification helpers alone. Private native display/headless browser rules apply when implementation is authorized. No builds were run for this audit. Python/JS/TS/Go/Rust queued V1 notifications do not automatically expose new C picker observers; a separate typed schema/wrapper slice needs full date fields/RGBA tags, stable IDs, owning bounds, handler retention and exception containment. Existing notification queues cannot reject applied changes. See [the binding audit](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_BINDINGS.md). No new source/test or feature-ledger status is promoted by this checkpoint. ## First slice implementation status Calendar selected-date observers only are implemented by `cui_picker_events.h` and the new Base/Styled wrapper sources. See [Calendar observer guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/PICKER_EVENTS.md). Each whole legacy operation is called once; date comparison, callback count, passive silence and outer completion timing follow the first slice above. DatePicker and ColorPicker remain proposals awaiting separate review. No TimeField, navigation/popup lifecycle, foreign binding or parity-ledger promotion is included. ## Second slice implementation status Base and Styled DatePicker selected-date wrappers are implemented in the same owned event header/sources. They observe the complete outer legacy operation once, including late false Styled returns after mutation, with trigger-ID metadata and post-dismiss/focus timing. The guide records the distinct legacy result types. ColorPicker remains awaiting review; no popup lifecycle or foreign API is added. ## Third slice implementation status Base and Styled ColorPicker RGBA observers are implemented in the same event header/wrapper sources. Whole-operation comparison uses explicit RGBA fields, retains alpha policy and HSV/capture maintenance, and never treats latent HSV or external synchronization as applied CHANGE. See the implementation guide. TimeField, navigation/lifecycle, controlled requests and foreign wrappers remain excluded. Completion of these three bounded slices does not promote family parity. --- ## Popover anchor, offset and arrow slice (proposal) Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/POPOVER_ANCHOR_PLAN.md # Popover anchor, offset and arrow slice (proposal) Design only; integrator review required before implementation. Baseline CUI `4eb9aab8`; frozen upstream reference `87d10ae5e1299d1be18670a37570c5402f952e34`. This proposal makes no present parity claim. Transitions, right-click activation, focus and controlled state are outside this slice. ## Source authority and present gap Reference paths below are relative to `/tmp/cui-upstream-reference` at that commit: * `crates/component/src/popover.rs`: `new`, `anchor`, `offset`, `arrow`, `render` (lines 145–438), `arrow_anchor`, `arrow_points`, `arrow_join_bounds` (445–498), tests 596–891. Component default anchor is TopLeft, gap is rem*0.25, arrow depth is rem*0.375; arrow depth is added to the surface gap. * `crates/base/src/popover.rs`: options and render forwarding (175–223, 320–326). * `crates/base/src/popup.rs`: live `anchor_position` (103–113), measured trigger tracking and corner positioner (133–183). `resolved_corner` is an older helper; it is NOT the live trigger geometry contract. * `crates/base/src/positioner.rs`: corner strategy (98–107), `resolve` (211–239), `clamp` (303–325), native client-frame inset integration (396–420). Corner mode clamps without flipping, retains popup size and defaults to 4px margins plus native client-frame insets. Final painted displacement is rounded. CUI `src/base/cui_surface.c:cui_surface_geometry` calls `cui_popup_place` with fixed gap 6; `src/base/cui_models.c` tries an opposite side, selects lower overflow, shrinks to viewport and clamps. Surface options expose only trigger rectangle and side. CUI has appearance refinement but no anchor selector, offset or arrow. Changing shared `cui_popup_place` would change other consumers. ## Proposed portable public contract Append to `cui_surface_options` a copied `cui_popover_position position` field; consume it only for Popover. Add types to `include/cui/cui_surface.h`: ```c typedef enum { CUI_POPOVER_POSITION_LEGACY = 0, CUI_POPOVER_POSITION_ANCHOR } cui_popover_position_mode; typedef enum { CUI_POPOVER_TOP_LEFT = 0, CUI_POPOVER_TOP_CENTER, CUI_POPOVER_TOP_RIGHT, CUI_POPOVER_BOTTOM_LEFT, CUI_POPOVER_BOTTOM_CENTER, CUI_POPOVER_BOTTOM_RIGHT, CUI_POPOVER_LEFT_CENTER, CUI_POPOVER_RIGHT_CENTER } cui_popover_anchor; typedef struct { cui_popover_position_mode mode; cui_popover_anchor anchor; float reference_rem; /* zero defaults to 16; otherwise finite positive */ float offset; /* signed logical pixels; used when custom_offset */ bool custom_offset, arrow; } cui_popover_position; ``` Zero mode must preserve current placement byte-for-byte and ignore new fields. Anchor mode defaults to TopLeft, offset reference_rem*0.25 and arrow off. Zero reference_rem selects 16 logical pixels; active nonzero values must be finite positive. Arrow depth is reference_rem*0.375. Applications configure reference_rem from their host's root sizing configuration, never by inferring theme font size. Explicit offset 0 is distinct from default; finite negative offsets are supported. TopLeft/Center/Right put popup top left/center/right against trigger bottom left/center/right. Bottom variants put popup bottom against trigger top. LeftCenter puts popup left-center against trigger right-center; RightCenter does the reverse. Offset moves outward on that side; arrow adds depth before clamp. Arrow points at the corresponding trigger point after surface clamping, never at trigger center unconditionally. Do not flip or reuse side placement in anchor mode. Existing `side` is ignored there; existing rectangle `anchor` stays the trigger bounds and must not be renamed. Add a pure bool geometry resolver with output untouched on invalid input: `cui_popover_position_resolve(cui_rect trigger, cui_size size, cui_rect viewport, float margin, cui_popover_position, cui_rect *out)` for ANCHOR mode only. Retain existing surface width/height defaults, but in ANCHOR mode do not shrink explicit popup dimensions before clamp: oversized surfaces settle at viewport minimum plus margin, matching corner clamp. A viewport represents usable client bounds; source native non-client/tiled-edge inset handling is host responsibility and not claimed here. Caller margin stays explicit (zero means zero); source-like examples set 4. Do not introduce platform or Clay public types. Add `typedef struct { float x, y; } cui_popover_point;` and pure arrow geometry output (three `cui_popover_point` points), join rectangle, and source-facing edge, computed from final surface, trigger, anchor, depth and resolved radius. Port source half=min(depth,edge/2), inset=min(radius+half,edge/2), target clamp exactly. Join uses 1px stroke and min(stroke,half-base) inset. Resolve fill from effective refined background; NONE without background refinement falls back to theme popover. Outline uses theme popover ring only when appearance is enabled, independent of border refinement. Match source theme-radius arrow inset (not refined radius) unless review explicitly chooses a documented departure. ## Architecture and review decisions Geometry and validation belong to base; component owns themed arrow drawing and join ordering. Core's portable mesh paint can draw triangles/slopes without new renderer protocol, but borrowed mesh vertices must remain alive through renderer completion: use context-owned frame storage, never retained stack arrays. Current concrete path: `cui_set_prepaint_parts` copies payload plus tail into Core frame storage (`cui_core_frame_copy_parts`, `src/core/cui.c:2811`); a prepaint callback reads its copied payload/tail and emits a borrowed mesh pointing into those copied vertices through `cui_prepaint_emit`. This allocation survives until next begin frame, as does draw data. Tail alignment must be proved (payload size multiple of vertex alignment) and callback budget/capacity rollback tested before Styled arrow work. No new Core allocation API is currently needed. Render arrow after panel border/shadow and before/after children as dictated by source overlay canvas; its join must cover the panel border on both sides. Verify portal clip and ordering with draw-list assertions before choosing storage/layout changes. Keep arrow decoration outside layout sizing, hit targets and accessibility tree; source popup dismissal tracks surface bounds, not triangle tip. Arrow must not create a focusable element or alter existing event routing. Adding fields is source-compatible for zero/designated initializers but changes the public struct ABI; rebuild C consumers. Bridge/binding exposure requires separate review of versioned fixed structs: never append blindly to bridge ABI. Until implemented and tested, bindings must explicitly report these options as C-only. Reject invalid enums/nonfinite active geometry before begin mutates state; preserve outputs and balanced begin/end behavior on rejection. Define overflow validation and degenerate zero-size trigger acceptance explicitly in headers. Integrator decisions: accept separate opt-in mode; accept explicit reference_rem with zero default16; accept oversized/no-shrink source mode; confirm source theme-radius inset and appearance NONE fill fallback. These are review decisions, not implemented facts. ## Required evidence before parity metadata changes 1. Table-driven headless pure tests: all eight anchors, offsets default/0/positive/ negative, arrow off/on, nonzero viewport origins, clamping every edge/corner, oversized panels, tiny arrow bases/radius, trigger movement and invalid finite/ enum cases. Golden values derive independently from frozen source tests and equations. Assert no flipping even where legacy would flip. 2. Regression geometry tests lock old zero-mode gap 6, side flip/shrink behavior, legacy appearance, and non-Popover behavior with garbage inactive new fields. 3. Software draw-list/pixel tests verify each arrow direction, anchor-aligned tip, seam coverage, effective fill/NONE fallback, outline toggle, tiny surfaces, edge clipping, z-order and frame-storage lifetime across nested popovers. Exercise actual begin/end and moving/resized trigger, not only helper math. 4. Reuse appearance native fixture/browser probe pattern for actual rendered arrows: native via private Xvfb wrapper only, browser headless; verify software and supported native draw adapters. GPU hardware behavior unsupported by Xvfb remains explicitly deferred. No desktop launch, dependency installation or runtime-network tests. 5. Update canonical component feature/limitation metadata, relevant consumer guidance and example; preserve all 78 manifest entries and exact authoritative header indexing. Run `python scripts/generate_agent_skill.py` and `python tests/test_agent_skill.py`; keep binding coverage truthful. 6. Configure/build with warnings and run `TMPDIR=/home/matteo/.cache/cui-validation/video-tests-tmp python scripts/test_local.py --build-dir build`. Record native/browser/backend results separately. Only then describe anchor, offset and arrow slice coverage; do not claim complete Popover parity. This design-only commit changes no behavior and requires no native launch. ## Accepted sequencing after integrator review The first implementation commit contains standalone public types/helpers and pure base geometry plus headless and WASI coverage only. It does not append the proposed options field or connect helpers to surface placement yet. Styled arrow paint is deferred until the prepaint copied-storage path above is tested. Canonical/generated metadata updates are deferred to integrator coordination; no shipped behavior parity claim yet. ## Styled consumption contract (second slice) Keep `cui_surface_options` and `cui_surface_state` unchanged. Add `bool cui_popover_begin(cui_context *, const cui_theme *, cui_surface_state *, cui_str title, cui_str description, cui_surface_options, cui_popover_position)`. It requires a Popover state; callers balance successful begins with existing `cui_surface_end`. Mode LEGACY delegates the existing surface begin exactly and ignores every other position field. No other surface kind is affected. Mode ANCHOR resolves placement afresh from the supplied trigger every submitted frame; width/height <=0 use420/260, finite positive dimensions retain their size even when larger than usable viewport. Invalid active geometry rejects before overlay update/begin. Pure `cui_popover_surface_geometry(options,position,out)` shares those defaults and legacy delegation, with untouched output on failure. There is no binary struct ABI change; clients link the new symbols only when using them. Implementation will factor the existing Styled begin into an internal routine with optional prevalidated explicit bounds and arrow payload. Existing public begin takes the identical legacy path; Base's geometry remains unchanged for all existing callers. No focus/event/semantic code is replaced. Decoration has no ID, hover hitbox, semantic entry or layout effect, and outside dismissal continues to use only the panel rectangle. Build fixed vertex arrays before submission, embedded directly in one copied prepaint payload struct. In its callback reconstruct mesh pointers into that copied struct, never retain pointers to caller stack data. Register on the panel portal and use deferred stream at the panel layer, after its border/children and before later layers. The stream inherits panel opacity and Core's host viewport clip. Clip arrow triangles to `options.viewport` in portable geometry before emission (fixed polygon buffers, no caller clip commands); intersect the join rectangle too. Panel placement retains existing portal clipping behavior. Frame arena failure rolls back registration and Core suppresses the final draw list; balance any already-opened internal boxes before returning false. Public successful begins retain their usual end contract, including a later frame-level capacity failure. Arrow fill uses resolved refined background except appearance NONE without an explicit background refinement uses theme popover. Outline is present for LEGACY/SOURCE appearance, absent for NONE, uses theme text with alpha26/255, and stays1px independent of refined border. Triangle and join follow the pure source geometry; arrow corner inset uses theme radius. This slice does not claim pixel equivalence with upstream's external PathBuilder stroke tessellator/AA. Portable outline uses two joined 1px slope strips, clamping miter displacement to2px; no base stroke. Triangle-vs-path raster/AA remains a documented gap. Any portable outline mesh topology difference must remain documented, and native GPU hardware evidence unavailable under Xvfb stays deferred. ## Input-independent visual paint correction The original deferred stream incorrectly conflated modal input eligibility with visual visibility. Core intentionally denies deferred emission outside the modal input scope; inert boxes explicitly retain painting. Arrow paint now owns a detached, inert decoration portal (surface part8) covering the supplied viewport at the panel layer. Local prepaint clips to that viewport and host bounds and remains visible when inert or behind another modal. The portal has no semantics, hover hitbox or input ownership. Floating-root order places its complete local stream after panel border/content and before higher layers. Copied payload and capacity rollback rules are unchanged. Existing order/clip/nested/failure tests plus inert/modal pixel and input-suppression regressions prove the correction. --- ## Questionnaire completion audit and proposed slices Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/QUESTIONNAIRE_COMPLETION_AUDIT.md # Questionnaire completion audit and proposed slices This is a design checkpoint, not an implemented API or a parity promotion. It audits CUI at `becbe8e0` against frozen upstream commit `87d10ae5e1299d1be18670a37570c5402f952e34` (the local reference checkout `/tmp/cui-upstream-reference`). Current upstream main is not evidence. The existing manifest's `implemented` label describes a substantial implementation; it does not establish completion of the frozen family. All 78 entries remain unchanged. ## Source authority Paths below are relative to the frozen checkout. Line numbers identify the behavior under review; the commit and file contents remain authoritative. | Source | Evidence | | --- | --- | | `crates/base/src/questionnaire/types.rs` | Definitions, answers and query records; validation context at 502; copied answer-change payload at 535; submission at 601; events at 623. | | `crates/base/src/questionnaire/state.rs` | Retained state; shortcuts default absent at 121 and lookup at 343–348; validation/navigation; submit at 746–767; adjacent-answer focus at 894–975; answer emission at 1052; current-change emission at 1187. | | `crates/base/src/questionnaire/keyboard.rs` | Held/default-prevented/IME guards, platform secondary modifier, answer navigation and confirmation. | | `crates/base/src/questionnaire/control.rs` | Checkbox/radio selection, disabled policy, focus, labels and answer-position semantics. | | `crates/component/src/questionnaire/components.rs` | Compound parts, card paint and size/theme tokens, custom children and style refinements, root capture, progress and action composition. | | `website/component/questionnaire.md` | Consumer contract and examples; not a substitute for reducer evidence. | | `crates/component-shell/src/shell/questionnaire/mod.rs` | Typed child composition, retained schema construction and fingerprint-driven rebuilding. | | `crates/component-shell/tests/questionnaire_host.rs` | Host integration examples/tests. | Content fingerprints (SHA-256): | File | SHA-256 | | --- | --- | | Base `types.rs` | `c0c41591fc90752031ca7268e3543e1404f8639825ebe6ae1d23e4b26d45c392` | | Base `state.rs` | `a8c231c29622172662a4191e25aef82173f3bf18e028cc46703464a04779e99b` | | Base `keyboard.rs` | `394e08cb2edd8fe657a42fe46f77148c93e8af5667c2cbf97de9690de277dacd` | | Base `control.rs` | `f16b4988bb9743449e8d301ca9db96ebb79a76a33a950c6b6d8d626c0911ea80` | | Component `components.rs` | `9498f77cbe508fe823e1bed956c8fc9004f3a68c44e5c64b81a1d176c3382cb3` | | Website guide | `4dd0da1253b532ce55600868bb1a10fbe74a3c91c70b435176957224401e3d28` | | Shell `mod.rs` | `f0c07b188175ded1e3bb2a4923449a781b6b0a48770f428e9d08712a586ffab6` | CUI evidence is `include/cui/cui_questionnaire.h`, Base and Styled `src/{base,components}/cui_questionnaire.c`, `docs/QUESTIONNAIRE.md`, `tests/unit/test_questionnaire.c`, `tests/unit/test_questionnaire_styled.c`, `tests/web/test_browser.py` (Questionnaire section beginning around 2806), and `include/cui/cui_bridge.h` / `src/bridge/cui_bridge.c`. No fresh runtime test was executed for this documentation-only checkpoint; checked-in assertions below are evidence of intended coverage, not a new passing run. ## Feature-level coverage “Present” means implemented with identified tests, not unrestricted parity. “Gap” identifies an observable missing capability or source difference. “Unverified” requires targeted evidence before changing behavior or status. | Feature | CUI implementation and existing proof | Remaining contract | | --- | --- | --- | | Schema and identity | Caller-owned item/choice definitions, duplicate-name/default/capacity validation; `schema_and_shortcuts`, `input_draft_reset_and_capacity`. | Present fixed-schema model. Host must not reorder/change borrowed identities during retained use. No source requirement for an arbitrary branching/schema-edit engine. | | Field types | Single choice, multiple choice, optional retained text editor, mixed choices/text; disabled/default handling. Base and Styled tests exercise these. | Present source field categories. Date/file/upload/async validation are not frozen Questionnaire requirements. | | Effective answers | Disabled choices/items excluded without destroying retained choices; single freeform replaces choices, multiple combines; Unicode blank text omitted. | Present, with retained-disabled/pending and draft/reset tests. Add independent source-vector differential fixtures. | | Editor synchronization | Explicit `set_input`/`sync_input`; Styled input owns ordered editing and synchronization. | Source subscribes to its retained editor entity. Direct host edits to CUI editor require explicit synchronization; document and test this portable integration boundary. | | Validation | Required/unfilled/custom/external errors, attempted-validation behavior, skipped/disabled suppression; first-invalid navigation. | Present core behavior. Callback-driven conditional policies and dynamic disabled anchors need broader tests; no async validator contract. | | Navigation | Previous, next, skip, confirm, submit, enabled positions; skip clears effective answer while retaining draft. | Present, including completion order tests. Source query records are richer than CUI's individual accessors. | | Delayed single-choice confirmation | New choice emits answer then schedules 150 ms confirmation, reduced motion immediate; choosing same answer confirms. | Present. Test live callback-driven policy changes before deferred tick and expired pending confirmation under disabled root. Root currently ticks even when capture is disabled; this is an explicit policy question, not a proven source regression. | | Completion and events | Synchronous legacy callback; current/answer/completed/submit kinds and item indices. Completed once; successful resubmit emits submit again. | Gap: source emits copied names/answer/status/submission payloads; CUI exposes live state plus `{kind,item,previous}` only. Querying mutable state later is not snapshot equivalence. | | Reset | Restores initial answers/editor drafts silently; retains runtime disable/external error policy. | Present bounded portable adaptation; assert callback silence and post-reset validation explicitly. | | Keyboard guards | Root and input reducers handle ordered events, IME, repeat/modifier guards and focus ownership. `automatic_root_keyboard`, `batched_input_confirmation`. | Substantial coverage; not a blanket missing keyboard feature. Two concrete policy differences below need compatible opt-ins. | | Shortcut configuration | Letters by default; numeric boolean; enabled-choice positions and badge rendering. | Gap: source defaults to no shortcuts and supports optional letters/numbers. CUI has no off mode. | | Answer-entry focus | Arrow navigation among answers, including optional input; selected-answer restoration. | Difference: CUI restores selected answer from unknown/action focus; source restores it only from item focus. Existing `radio_keyboard` action-focus assertion encodes CUI behavior. Preserve it by default. | | Submit modifier | Root recognizes Control or Meta plus Enter; explicit shortcut helper accepts host modifier. | Source uses platform secondary modifier. Root needs an explicit portable host policy if exact source behavior is requested. | | Root and containers | Group root, current-item group, radio/multiple groups, actions row, focus restoration; `composable_containers`. | Gap: source root is Form; CUI core has no Form role. Cross-layer semantic role/mapping work is required. Nested-root capture isolation remains unverified in both implementations. | | Choice accessibility | Checked/disabled/name/description, enabled positions, radio/checkbox roles, custom-slot semantics. | Present substantial semantics and browser assertions. Physical assistive-technology acceptance is not established by semantic snapshots. | | Input and errors | Textbox required/invalid, Alert error, active-item submission gating. | Source standalone Error visibility differs from current-only CUI error; separately review explicit composition policy rather than silently altering legacy helpers. | | Compound parts | Root/progress/item/choices/choice/input/error/actions and four actions; combined heading. | Gap: separate Title, Description and ChoiceDescription parts; source ParentElement custom children on parts/actions and independent styling. CUI heading is not an equivalent substitute for all compositions. | | Choice content slots | Borrowed indicator/content/shortcut renderers; stable namespaces and masked box refinements. `custom_choice_slots`, `slot_refinements`. | Present bounded subset, not arbitrary Styled. Text/font inheritance and additional root/card/part style properties are missing. | | Sizes and paint | Four legacy sizes, shared XS–9XL/density, inherited-size cache; theme/card/hover/focus/disabled tests. | Source token-driven typography/spacing/radius/custom size and general refinements need a property-by-property metric/style audit. Palette tests do not prove arbitrary themes or all source geometry. | | Localization | Six masked action/required/unfilled labels, explicit empty override, custom validation text; `localized_labels`. | Gap: fixed English progress sentence. Separate title/description composition also limits localized custom content. No requirement to invent a translation service. | | Retained ownership | Caller workspaces and disjoint answer/initial/draft buffers; bounded count and text capacity; borrowed definitions/editors/strings. | Deliberate C11 adaptation of source entities/owned strings. Needs explicit snapshot and callback lifetimes, not hidden allocations or borrowed-event retention claims. | | Language bridges | Bridge has Questionnaire builder, state query, choice selection and navigation/submit; bounded 16-item/256-choice storage. | Existing bridge is not absent. It does not expose the full mixed-editor/validator/custom-part/snapshot surface. Last generic event fields are not source event payloads. Each binding needs explicit capability accounting. | ## Callback, ordering and lifetime boundaries Frozen submit constructs one submission before emitting Completed with a clone and Submit with that same content (`state.rs:746–767`). CUI's legacy callback can query live state; it does not freeze an equivalent submission for both callbacks. The callback receives a const state pointer, but a host may retain another mutable pointer. Existing tests establish basic event order and copy input text into a trace; they do not establish unrestricted reentrant mutation, teardown safety, or immutable event retention. Do not change legacy timing to manufacture parity. Definitions, editor pointers and workspace buffers outlive the state. Custom renderers and style callbacks execute synchronously; borrowed strings must remain valid for their documented submission/validation lifetime. Validators are pure and must not mutate the model. A future observer must state whether callback mutation is forbidden, observed live for later events, or supported through an explicit queue; it must not silently introduce an event dispatcher. Source constraints matter: one active question, synchronous validation, fixed schema, host-owned persistence/transport and conditional disabled policy. The shell can rebuild retained state when its typed schema fingerprint changes; that is not arbitrary in-place schema mutation. Source framework ownership is not a reason to expose platform/entity types in portable public APIs. ## Proposed independently reviewable production slices All names below are proposed, not declarations available to consumers. Each slice needs its own exact header contract and approval. Additive entry points and zero-valued options preserve current CUI behavior and callback timing. 1. **Explicit keyboard policies.** New Questionnaire options header and `_ex` root/choice seams with typed shortcut mode `LEGACY`, `OFF`, `LETTERS`, `NUMBERS`; typed answer-entry policy `LEGACY` / `ITEM_FOCUS_ONLY`; and a portable submit-modifier policy supplied by the host. Invalid enum values fall back independently. Off suppresses both badges and activation. Inherited options and standalone part/helper behavior must agree. Keep the existing numeric boolean API unchanged. First add source-differential action-focus, item-focus, no-shortcut and modifier tests; investigate nested roots before promising a nearest-root isolation rule. 2. **Bounded answer/query snapshots.** Add checked copy-out records for answer, schema-ordered enabled submissions and navigation state. Caller supplies record/string workspace; report required counts/bytes with checked overflow, fail without partial valid output on insufficient capacity, and define NUL and empty-string rules. Snapshots must survive subsequent model edits while their caller buffers remain alive. A borrowed view alternative is smaller but cannot satisfy copied event retention; keep that distinction explicit. 3. **Typed observation with real payloads.** Separately design an observer/results facade using the snapshot primitives. Preserve legacy callback ordering and live eligibility; freeze the completed/submit pair before the first callback. Specify mutation/reentrancy and capacity-failure behavior before coding. Test conditional follow-up enablement, edits during notification, skipped and disabled entries, repeated submit and immutable retained snapshots. Do not label a wrapper that rereads live state as source payload parity. 4. **Compound presentation and localization.** Add separate title, description and choice-description parts; explicit content callbacks for actions/error/ progress where source composition needs them; a borrowed pure progress formatter with bounded output/error rules. Preserve combined heading and English defaults. Reuse ordinary CUI composition and existing masked-style conventions; define whether standalone inactive parts render explicitly. 5. **Semantic and style completion.** Review Form role addition across core, native/browser adapters and bindings as a separate ownership request. Audit source root/card/part box and text properties into a finite presence-masked portable style/metrics record, including theme token defaults and explicit custom sizes. Reuse text primitives and preserve zero-style pixels. General source Styled remains unimplemented until its properties have concrete supported equivalents; it is not a permanent blanket exception. 6. **Host/binding acceptance.** Extend bridge schemas/queries/events only after ownership and bounded callback/editor lifetimes are settled. Record each language's supported subset. Add actual WASM gallery fixtures for the new policies, localized parts and copied payloads; generated source availability alone is not binding behavior proof. These slices require Questionnaire-only Base/Styled private seams and new headers/tests/guides initially. Form requires separately assigned core/adapter ownership. Canonical CMake, modules/amalgamation, SDK/distribution, source metadata, human usage mirror and generated consumer skill belong to a later integration step. No such files change in this checkpoint. ## Proof plan and completion criteria Existing Base tests cover disabled retained pending answers, validation/skip/ completion order, draft reset/capacity, schema/shortcuts and enabled positions. Styled tests additionally cover cards, slots, progress, containers, accessibility, size cache eviction/context isolation, ordered input, automatic root keyboard, capacity failure, localized labels and invalid options. Preserve these tests. The existing actual-WASM browser story already checks radiogroup positions and descriptions, custom content semantics, delayed choice progression, required alerts, mixed checkbox/freeform submission, event counters, letters/numbers, focus and Unicode IME. It is not proof of later slot/localization APIs or of all callback contracts. WASI already registers `questionnaire` and `questionnaire_styled`; do not describe those suites as missing. For each new slice, use strict portable C11 Release tests via `python scripts/test_local.py --build-dir ` with dedicated home-cache TMPDIR; never a desktop display. Exercise real queued pointer, key and accessibility activations, multiplicity and ordering, previous-grid/part identity where applicable, input composition, disabled transitions and reduced motion. Add software-pixel assertions for actual hover/focus/disabled/style and text/size containment, alongside semantic assertions. Include zero-option draw, semantics and callback equivalence against legacy paths; avoid tests that only mirror a resolver implementation. Run the focused WASI suites and headless actual-browser fixtures after native proof. Check bounded capacities, omissions/reintroduction, invalid options, borrowed lifetimes and independently normalized policies. Run repository pinned `format.py --check` after final source edits, plus freshness/consumer checks at canonical integration. Physical AT and unavailable GPU hardware remain explicitly unverified; do not substitute DOM/software assertions for those claims. Completion requires feature-by-feature source reconciliation, meaningful tests for newly supported behavior, real compiling consumer examples and honest binding/platform limitations. Passing existing tests alone cannot promote the family to full frozen parity. Production changes await review of this checkpoint. --- ## Questionnaire typed observation contract and architecture decision Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/QUESTIONNAIRE_EVENTS_CONTRACT.md # Questionnaire typed observation contract and architecture decision Implementation checkpoint: the architectural review selected persistent caller-owned attachment, implemented in `cui_questionnaire_observer.h` and Base hooks on the `9c6d0db2` integration base. One public-state pointer is the documented ABI change; consumers must rebuild matching headers/library. Exact implemented declarations and lifetimes are authoritative in that header and `docs/QUESTIONNAIRE_OBSERVER.md`. The design rationale/source audit below records the alternatives considered; it does not expose an additional wrapper or input metadata API. The implementation also reports defensive PAYLOAD_INVALID for failed copy preflight rather than mislabeling it overflow. Pure copy-out remains independent of event-time freezing. Original audit base is `bba4eb75`, frozen source commit `87d10ae5e1299d1be18670a37570c5402f952e34`. Broader Questionnaire parity and foreign bindings are not claimed by this observation slice. ## Implemented verification boundary The worker implementation passed strict Release private-wrapper Questionnaire observer/model/Styled/keyboard/snapshot tests (5/5), focused WASI equivalents (5/5), focused ASan/UBSan observer execution, compiled C guide and C++ header, and actual pinned final format.py --check. Tests compare attached/unattached legacy callback mutations and handler/user replacement, freeze outer versus nested Completed/Submit payloads, preserve failed-pair capacity across reset/ disabling, and characterize ordered key/pointer/accessibility/text/timer paths with UNKNOWN metadata. They also exercise detach pinning and BUSY replacement. Canonical registration/generated resources and foreign bindings remain separate. The remaining proposed proof matrix below records broader future acceptance, not a claim that every future scenario or binding is implemented here. ## Actual legacy emission and timing Authority: `src/base/cui_questionnaire.c:28–32,217–245,303–334,353–535` and `include/cui/cui_questionnaire.h`. The only notification mechanism is the retained `state.event/state.event_user`. Each emit synchronously reads those live fields and invokes the callback with `{kind,item,previous}` and a const state pointer. No queue or copied name/answer/submission exists. The const pointer does not prevent a host from holding another mutable model pointer. | Trigger | State at emission | Later work and multiplicity | | --- | --- | --- | | Changed choice via activate | Effective selection updated; skipped cleared; pending and complete cleared; attempted validation refreshed. | One AnswerChanged only for effective change; multiple toggles change each time. Disabled activation is silent. | | choose | Calls activate, including its synchronous callback. | After callback returns, live current/item-disabled/multiple determine whether to confirm an already-selected answer or schedule new selection at now+150ms (zero delay for reduced motion). Callback mutation can suppress that follow-up. | | sync_input with emit=true | Effective retained answer synchronized; optional single-choice selections cleared; skipped cleared when appropriate. | One AnswerChanged on effective change. set_input and set_answer use silent paths. Styled ordered input can call sync repeatedly within one frame. | | previous / successful next | Current index already changed, pending cleared. | One CurrentChanged for a different index. Previous does not validate; next validates before choosing live enabled successor. No synthetic CHANGE for an unchanged index. | | failed submit | All currently enabled items validated; first invalid selected. | CurrentChanged only if current actually moves. No Completed or Submit. | | successful submit | Pending cleared; if not already complete, complete becomes true. | Completed once, then Submit. Every later successful submit still emits Submit. Completed callback can change state or replace handler before Submit, whose live callback fields are read again. | | skip | Effective choices/freeform cleared, retained editor draft preserved, skipped set and complete cleared. | AnswerChanged, then confirm against the live state left by that callback; may navigate or submit. No stale precomputed confirm target. | | tick | Pending cleared before confirming, only when due and current still matches pending item. | Indirect CurrentChanged/Completed/Submit from normal confirm path; no invented timer event. | Init, set_current, set_answer, set_input, reset, item/choice disable and external error do not directly emit events. They may mutate pending/completion/current or revalidate through existing paths. They must remain silent in typed observation unless the legacy reducer itself emits a notification. Observer attachment must not add per-frame, paint, validation, focus or lifecycle notifications. Legacy callback-driven conditional disabling/editing/current changes are real synchronous behavior. In particular choose checks live state after AnswerChanged; skip confirms live state after AnswerChanged; submit emits its second notification without revalidating after Completed. Nested public calls from a legacy callback can emit their own events inline. Current tests prove basic kind order, repeated submit and ordered input text traces, not arbitrary reentrant lifetime safety. Destroying the model/editor/definitions or rebinding its active workspace during an operation is unsafe today; preserving mutations is not a promise to make use-after-free safe. Validators remain pure. ## Frozen source payload requirement `crates/base/src/questionnaire/types.rs:535–632` defines copied item name, answer/status, copied optional previous/current names, and submission records. `state.rs:1037–1058` emits a copied answer after reduction; `1180–1193` captures previous name before current changes and emits copied names. Most importantly, `state.rs:746–767` constructs one submission after validation, emits Completed with a clone, then Submit with the same data. Therefore copying state after each legacy callback is insufficient. A Completed handler can change an answer, disable an item, reset completion or initiate a nested submit; the original outer Submit still requires its original frozen payload. The pure snapshot functions can build those buffers, but they cannot choose the event-time freeze boundary or hold a shared pair on their own. ## Alternatives and decision requested 1. **Callback replacement wrapper.** Save old callback/user, install a forwarding function around one public operation, then restore it. Rejected for full scope: a callback can replace event/user itself, nested calls can escape or double-wrap, timers/input/ordinary legacy calls are not all covered, and the forwarding callback sees Completed only after the reducer has chosen its event shape. State rereading at Submit cannot reproduce the pair. A limited wrapper could advertise only live-query observations, but must not claim copied source events. 2. **Explicit observed operation family.** Pass an observer argument through new private reducers and new public operations/Styled controls. Portable and no persistent state attachment, but every navigation/input/timer path needs an observed variant. A legacy callback calling an ordinary legacy operation loses observation of that nested event unless it explicitly forwards context. This can be a valid narrower API, but does not observe all legacy mutations/calls. 3. **Persistent caller-owned attachment (recommended for review).** Add one observer pointer to the retained model, initially NULL, and attach/detach a caller-owned observer with caller-supplied snapshot frames. Hook existing Base emission and the submit pair's freeze/release boundary directly. Ordinary Base, Styled, timer and nested legacy calls then see the same attachment. No global registry, thread-local forwarding, allocation, input dispatcher, capture/bubble rewrite or replacement of event/user is necessary. Option 3 was selected in architecture review. It is an explicit ABI decision: public state grows by a pointer, so matching headers/library and binding layout rebuilds are mandatory. Legacy init must initialize that pointer to NULL; attaching occurs after successful init. Reset retains the attachment. Copying/moving an attached model/observer by value is forbidden. An external global registry avoids the layout edit but adds hidden ownership/thread-safety/teardown problems and is not recommended. The implementation authority was the subsequent explicit architecture decision, not the original design checkpoint alone. ## Proposed typed payload and origin contract A new observer header would reuse existing `cui_questionnaire_event_kind`, `cui_component_event_metadata`, and copy-out snapshot records. Proposed records: ```c typedef enum { CUI_QUESTIONNAIRE_PAYLOAD_READY, CUI_QUESTIONNAIRE_PAYLOAD_CAPACITY, CUI_QUESTIONNAIRE_PAYLOAD_OVERFLOW, CUI_QUESTIONNAIRE_PAYLOAD_NO_FRAME } cui_questionnaire_payload_status; typedef struct { cui_component_event_metadata event; cui_questionnaire_event_kind kind; size_t item, previous; /* exact legacy indices, including SIZE_MAX */ cui_questionnaire_payload_status payload_status; cui_questionnaire_snapshot_requirements required; bool has_previous_name, has_current_name; cui_str previous_name, current_name; cui_questionnaire_item_snapshot answer; cui_questionnaire_submission_snapshot submission; } cui_questionnaire_observation; typedef void (*cui_questionnaire_observation_fn)( void *user, const cui_questionnaire_observation *); ``` CurrentChanged uses optional copied names, AnswerChanged uses copied item/answer/ status, and Completed/Submit use the same frozen submission. Irrelevant payload fields are zero. Presence booleans distinguish absent names from legitimate empty names. Name copying uses checked text requirements and the same NUL/length rules as copy-out. Current model UTF-8 validation rejects embedded NUL. The source snapshot has no input draft, label, validation-message or schema-mutation payload. Metadata maps CurrentChanged/AnswerChanged to CHANGE, Completed to COMMIT, and Submit to SUBMIT, while `kind` preserves exact family meaning. The observer has a required nonzero application target ID; this does not register a UI element. Default Base origin is UNKNOWN with no evidence flags, no invented frame/index/ activation and zero unused fields. A Base emission cannot infer which pointer, key, accessibility request or host call caused it. PROGRAMMATIC may only be marked through a future explicit operation context; frame metadata or genuine activation needs an audited Styled forwarding seam. Handler installation alone provides neither. First production slice should make no input-source claim. ## Ordering, freezing and legacy mutation compatibility Recommended hook order for each existing emission: 1. Capture typed payload at the existing emission boundary, before any user callback can change the model. For submit, freeze once after successful validation and before setting/emitting the outer completion pair. 2. Invoke the observational typed callback synchronously, if still attached. 3. Invoke the original legacy callback through the existing live event/user fields. 4. Continue the original reducer, checking existing live eligibility unchanged. Typed callbacks are pure with respect to CUI/model/observer configuration: they may copy payload bytes and update unrelated host bookkeeping, but must not call model operations, validators, UI submission, attach/detach, or destroy/rebind resources. This ordering preserves chronological typed event order when a legacy callback emits nested events. Delivering typed callbacks after legacy callbacks would instead expose nested typed events before their parent; that is a possible alternative but must not be silently mixed with this proposal. Legacy callbacks retain allowed model mutations and nested calls. If Completed clears complete or disables an item, the original outer Submit still occurs with its frozen payload. No revalidation, veto or additional event is inserted. If the legacy callback replaces event/user, Submit calls the replacement as before. A missing typed handler never suppresses a legacy callback or changes a return. One accepted legacy emission yields one typed attempt; repeated successful submit and batched input edits are not coalesced. No queued replay or per-frame aggregate may substitute for this synchronous stream. ## Bounded frames, errors and retention Observer attachment retains only caller-owned object, handler/user and frame-array pointers. Each frame owns independent item/choice/text workspace; regions must be disjoint from every other frame, observer state, model and schema, as in copy-out. Frame count is an explicit caller bound. One ordinary emission reserves a frame until both callbacks return. A submit pair reserves one frame across both outer emissions and all intervening nested legacy calls. Nested emitting operations use additional frames, so they cannot overwrite the outer pair. All snapshot capacity/overflow checks precede arena writes. READY payloads are complete, never partial. Insufficient capacity yields CAPACITY and exact needs; overflow yields OVERFLOW and zero needs; no free frame yields NO_FRAME and zero needs. A typed attempt is still delivered with family kind/legacy indices and honest UNKNOWN metadata, but all copied payload/presence fields are zero. No allocation, retry, dropped legacy event, model rollback or changed legacy return is permitted. Both members of a submit pair share the same readiness/failure and requirements; do not retry Submit against mutated state. A missing typed handler need not perform a copy, but counts must distinguish attempts from deliveries. Proposed observer statistics are saturating attempted/delivered/payload-failure counts plus an overflow flag, queryable without changing the model. Exhausted snapshot capacity is an observation failure, not a failed model submit. The implemented attach/detach/statistics signatures and public observer control record are in the new header. Its private-prefixed bookkeeping and explicit workspace frames implement this no-allocation direction. Idle attach to an unattached model remains a caller precondition; known in-flight attachments reject reattachment with BUSY. There is no global registry that could detect every unattached active operation. The observation pointer and nested views are borrowed through that callback only. READY bytes are independent of model edits, but frame reuse ends their storage lifetime. A by-value copy of the observation is not a retained deep copy. Hosts must copy strings/records into separate owned storage when retaining events. The outer pair's backing frame is held until the outer submit returns; callbacks must nevertheless not retain the stack-local observation pointer between calls. ## Removal, shutdown and reentrancy Attach validates initialized state, nonzero target, idle/disjoint frame storage and a not-already-attached observer; it does not replace legacy callbacks. One observer per model is sufficient initially. Idle detach clears the association. Detach requested from a legacy callback marks observation inactive immediately, suppresses later typed notifications (including outer Submit), but pins its frame storage until outermost in-flight release. Reattach/reconfigure while in flight returns BUSY. No observer shutdown callback is synthesized. Handler/user and all observer/frame storage remain alive through detach and the last in-flight operation; detach is not permission to free them on that callback's stack. Model, schema/editor/workspace and legacy user also remain alive until outer operation and any renderer consumption finish. Host omission/destruction must be deferred to that safe boundary. There is no arbitrary destruction guard. Nested legacy operations retain their existing inline behavior, bounded only for observation storage; frame exhaustion does not attempt to prohibit recursion. Typed-handler reentrancy and concurrent use remain forbidden, explicitly. ## Regression proof and remaining scope Before implementation approval, select persistent attachment versus the narrower explicit-operation alternative and approve state-layout ownership. Then test: - Zero/unattached paths: exact legacy event kinds/order/counts, return values, callback replacement, focus/timer behavior and silent setters unchanged. - Answer callback changes current or disables the chosen item before choose's follow-up; skip callback changes current before confirm; live enabled policies and attempted validation behave identically with observation attached/unattached. - Completed callback changes answers/disables/resets and performs a guarded nested submit. Outer Completed/Submit byte content remains equal to the pre-callback snapshot; nested pair has a distinct frame and live newer data. Legacy callbacks still observe live mutations and original per-emission handler replacement. - Current names preserve previous/current identity, absent versus empty names; Unicode strings are copied. Keep event-time values even after legacy callbacks edit answers. No rereading state for the second pair member. - Zero/one-short item, choice and text capacities, frame exhaustion, checked arithmetic probes, missing handler, removal during legacy callback, rejected in-flight reattachment and caller-deferred shutdown. No arena corruption, fabricated metadata, partial payload or model failure on observation errors. - Real ordered pointer/key/accessibility/input/IME paths and due timer calls, including multiple accepted edits/events in one frame. Until genuine metadata forwarding exists, assert UNKNOWN rather than infer causality from queued input. Use strict Release private headless wrapper, meaningful Base/Styled regressions, focused WASI, compiled guide/C++ header and final pinned formatting. No desktop or new dependencies. Browser marshalling requires a separate binding slice: existing generic last-event fields do not own copied names/answers/submission arrays and foreign callback/user lifetimes need an explicit design. Snapshot/observer support does not complete compound presentation, localization, Form or general styling. Canonical metadata, generated resources and bindings remain integrator-owned. The focused observer implementation is the only new family event surface here; no full-family promotion is justified. --- ## Questionnaire geometry: final additive contract Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/QUESTIONNAIRE_GEOMETRY_API.md # Questionnaire geometry: final additive contract Approved bounded implementation contract, 2026-10-22. Builds on the measured wrapper design in `bda38642`; frozen source is `87d10ae5`. A new independent `cui_questionnaire_geometry.h` exposes five masked box patches (root, item, choices, actions, card), checked complete metrics resolution, three choice text refinements and extended optional child renderers. Legacy public options, choice view and state layouts do not change. Input, Button, arbitrary style inheritance and asymmetric editor padding remain required separate work. The extended callback receives an immutable borrowed snapshot containing the old choice view, the fully resolved metric value record, and answer, secondary and shortcut text views. Each new renderer wins over the corresponding old renderer; otherwise the old renderer runs unchanged. The same child namespaces and ordering apply. Snapshots/functions/userdata are borrowed for synchronous submission only; strings drawn by children survive completed-frame consumption. Children balance boxes, do not mutate the model or dispatch input, and cannot retain the snapshot. There is no callback/style cache or numeric inheritance. Root publishes only its existing size/density. Caller explicitly passes geometry to each part. Resolution order is existing size/density, custom scalar only with shared size INHERIT, masked metric overrides, text refinements, then box instance patches. Shared XS through9XL wins over custom scalar. Legacy numeric role sizes and source custom formulas are separately documented. Custom scalar is finite (0,256]; lengths are finite [0,4096], fonts (0,512]. Unknown masks/invalid active values reject before bindings, input reduction, model mutation or callbacks. Checked metric helper failure leaves output unchanged. Inactive values are ignored. A box patch offers width (grow -1, FIT0, positive fixed, explicit fixed-zero), physical padding, gap, radius, background, border, alignment and opacity. Card outer gap stays zero; its gap patch applies to the actual answer row. Explicit minimum and fixed card heights reject fixed below minimum before interaction. The minimum uses a zero-width spacer inside the interactive outer card; there is one paint/hit/focus/semantic owner. Taller content grows FIT cards; ancestor clip and fixed-height overflow retain ordinary Core behavior. No max-height promise. Post-state card opacity changes paint only, never disabled eligibility. NULL and all-zero geometry take the exact existing tree/text path. Legacy entry points delegate without active geometry. Existing keyboard capture, callback mutation/timing, observer ordering and bool meanings remain unchanged. Text refinement changes default paint in the existing reducer, never creates a second control. Natural line height uses font metrics for first-line alignment only when active; zero preserves legacy offsets exactly. No observer/event facade or full-family parity claim is introduced. --- ## Questionnaire typography, layout and compound completion Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/QUESTIONNAIRE_LAYOUT_COMPLETION.md # Questionnaire typography, layout and compound completion Design checkpoint only, 2026-10-22. No proposed declarations below are implemented. Baseline CUI: `939c5c2f`; frozen reference: `87d10ae5e1299d1be18670a37570c5402f952e34`, verified in `/tmp/cui-upstream-reference`. This does not promote the Questionnaire row or change any of the 78 entries. It supersedes the *remaining presentation scope* in the older completion audit, not its independent behavioral/host limitations. ## Source contract and present coverage Paths below are relative to the frozen checkout unless prefixed `CUI:`. `crates/component/src/questionnaire/components.rs` is the owning skin source; `website/component/questionnaire.md` documents the same compound composition. General upstream `Styled` is an open framework surface, not a finite Questionnaire property list. The table distinguishes that from concrete skin behavior. | Frozen evidence | CUI evidence at baseline | Finding | | --- | --- | --- | | `components.rs:27-60,85-177`: root publishes size by state; 128-entry bounded table; per-part override; separate root/item/choices/card/content metrics and custom `Size(value)` | `src/components/cui_questionnaire.c:126-238,418-574`: bounded state size cache, four legacy sizes and shared XS–9XL/density, independent choices gap | Substantial coverage. Arbitrary source custom size and independent geometry tokens are absent; shared scale is a CUI extension, not exact custom-size equivalence. | | `components.rs:180-253`: answer/secondary/title/progress typography and first-line adornment centering | CUI metrics, choice paint at634-830, heading832-850, error851-880 | Answer size/line pairs match default tokens for four sizes. Description line boxes, progress/title tiers and explicit font refinement differ; no family-wide cascade. | | `components.rs:297-364,527-678,1238-1290`: root/item/choices/actions accept children and instance styles | CUI begin/end containers and existing composable-container tests | Child composition already exists. Root/card/container box refinement is missing; actions lack source automatic trailing anchors. Root is Group, source Form: separate Core role decision, excluded here. | | `components.rs:435-522`: independent Title/Description, schema fallback or replacement children; title adds item-gap bottom margin when schema description is absent | Combined `cui_questionnaire_heading` only | Real missing parts. Source text parts check schema existence, not current/disabled status themselves; active Item normally gates them. Preserve this distinction in new parts. | | `components.rs:685-1020`: stateful card with indicator/content/shortcut, custom content and two renderer seams, three slot styles; instance style last after state paint | Existing choice renderers, masked box styles, state view, semantic identity and first-line wrappers | Already covers bounded slots. Missing card-instance refinement and default answer/description/shortcut typography. Source default shortcut uses theme mono family; CUI current default is medium weight without that theme-family resolution. | | `components.rs:1024-1077`: standalone ChoiceDescription has children, secondary typography, optional size, no state | No named equivalent; caller can render ordinary text inside existing content callback | Missing convenience/explicit metrics part, not missing custom choice content. | | `components.rs:1080-1146`: Input delegates to Input with size, padding, radius, invalid border then instance style | CUI input control945-1056 delegates editor reduction/paint; custom left padding and invalid state | Existing real editor path. Generic input skin refinement remains absent; cannot safely replace the editor with a child callback. | | `components.rs:1150-1233`: Error appears only for invalid item with error, Alert wrapper, secondary text, top margin, custom children | CUI Alert/error labels/custom external messages, current-item gating, fixed default text | Missing custom error children/style and source spacing/typography opt-in. Do not silently change legacy gating. Source Error itself does not require current item. | | `components.rs:1293-1408`: four action parts use real Button, visibility from navigation, custom children replace translated text, Skip or Next/Submit gets automatic leading margin | CUI action control882-928 uses real Button and legacy reducer; explicit/localized label override | Missing compound child and automatic trailing layout; not missing activation. Custom action content needs a real Button content seam, not overlay controls. | | `components.rs:367-432`: localized numeric progress, optional replacement children, typography | `cui_questionnaire_progress.h`, production progress_ex, native/WASI/pixel/browser tests | Implemented bounded label/visible/custom child/text refinement. Do not repeat this work or call all localization absent. | Frozen typography defaults live in `crates/base/src/theme_tokens.rs:157-211`: xs12/16, sm14/20, md16/24, lg18/28, xl20/28, normal token weight. Answer uses xs/sm/md/lg; secondary uses xs/xs/sm/md; title uses sm/md/lg/xl with medium weight; progress uses xs/xs/xs/sm with medium weight. In CUI Medium, for example, heading currently18/28 matches default title, but choice description14/24 differs from source14/20; legacy progress12 with natural line differs from explicit12/16. These are concrete opt-in corrections, not reasons to change zero-option rendering. Source custom-size formulas are answer=value, secondary=.875value, title=1.125value, progress=.75value, answer-line=1.5value; source custom-size secondary/title/progress only set size, so do not invent guaranteed line-height formulas for those elements. Existing proofs include `tests/unit/test_questionnaire_styled.c` functions `source_card_styles`, `custom_choice_slots`, `composable_containers`, `choice_accessibility`, `inherited_sizes`, `slot_refinements`, `localized_labels`, `invalid_options_preflight`, and ordered keyboard/input regressions. `test_questionnaire_progress.c` proves independent legacy-zero values/pixels, custom child/visible/label precedence and preflight; browser progress and keyboard fixtures exercise actual WASM desktop/touch. Snapshots, keyboard policy and persistent observer each have their own headers/tests. None of these proves arbitrary root styles, missing named text parts, or custom action children. Observer is real synchronous observation, not a style mechanism. ## Proposed cohesive portable surface Add `include/cui/cui_questionnaire_presentation.h`; do not append legacy options or state. Reuse `cui_questionnaire_text_refinement` from progress and the existing slot mask vocabulary rather than duplicate text/style types. Keep progress_ex independent; adding an outer-box variant can be a later additive overload. The following are proposed contract shapes, not compilable declarations yet: - `cui_questionnaire_presentation`: independent masked geometry/style record, with root/item/choices/actions/card/input box refinements and answer, secondary, title, description, shortcut and error text refinements. A separate explicit metrics-policy enum selects LEGACY or TOKEN_DEFAULTS. Zero means legacy, including known differences; TOKEN_DEFAULTS opts into the frozen default typography/spacing/radius and title-without-description separation. Do not use a single boolean claiming complete source styling. - Geometry is per-part and does not publish a style cascade. Root continues publishing only existing size/density. The same presentation record may be passed explicitly to parts; omitted record does not inherit it. Independent text masks allow font family/weight, color, size and line box; existing slots remain independent. Resolve size first, optional token defaults second, existing slot refinements third, new explicit part refinement last. New card instance patches apply after built-in selected/invalid/hover/focus/disabled paint, matching source instance precedence; ancestor opacity still multiplies. - Add `_with_presentation` counterparts for root/containers/choice/input/error/ action, with an explicit keyboard pointer on root/choice where required. Legacy and current `_with_keyboard` paths share private implementations and pass NULL presentation. Avoid combinatorial public wrappers for every pair: the new entry accepts both independent pointers and documents each default. - Add `cui_questionnaire_title_ex`, `...description_ex` with schema item index, independent presentation and optional borrowed text-content record; add `...choice_description_ex` with explicit borrowed content and size, no state. Existing heading remains untouched. Named item parts follow source schema existence checks; callers use Item begin to gate current/disabled items. - Text-content record: explicit VISIBLE mask (including empty), optional child callback and user pointer. Child replaces visible fallback, while item/choice semantic names/descriptions stay schema-derived. Callback receives immutable resolved text/geometry/state view and stable child namespace. It runs once, synchronously, must balance children, must not mutate state, route input or end its owner. No retained function/user pointer. Strings live through frame draw/semantic consumption. Reuse the progress lifetime/ID-collision rules. - Error replacement stays inside one existing Alert; label remains actual localized validation text even with decorative child. New explicit visibility policy LEGACY_CURRENT versus SCHEMA_ERROR permits source-like standalone error rendering; zero must keep current-item filtering. No validation or model events occur merely from submitting presentation parts. - Actions need bounded custom **decorative** Button content, preserving the one Button semantic node and exact existing activation loop before/after content. Accessible name remains explicit/localized action label. A trailing-policy enum LEGACY versus AUTO places one grow spacer before visible Skip, otherwise Next/Finish. Per-action opt-out lets explicit layout win. Apply only inside the corresponding new Actions composition; no invisible spacers from omitted actions. This requires a predeclared composition plan or explicit caller spacer, not guessing which future children will be submitted. Recommended bounded geometry mask: existing slot width/height/padding/gap/radius/ background/border/align/opacity plus explicit min-height and separate horizontal/ vertical padding where supported by current primitives. Values must affect the same layout/hit rectangle that is painted. The source card has **minimum** height, not fixed height: long localized labels must grow. Unsupported box properties must be rejected, not accepted and ignored. Current `include/cui/cui.h:421-452` exposes physical padding edges with `custom_padding`, so per-axis padding needs no Core extension. It exposes maximum but not minimum dimensions or margins. Before production, prove minimum-height and automatic-margin behavior with private balanced wrappers and account for their bounds, or leave those properties as an explicit next slice. No silent Core ABI work. Do not add arbitrary upstream callbacks, CSS values, a retained element tree or a new theme/style cascade. Existing typed fonts and host font provisioning remain authoritative. Full arbitrary Styled (absolute positioning, transforms, shadows, pseudo-state layout, arbitrary inherited styles) remains a separately enumerated framework gap; this bounded API must not claim it is implemented. An arbitrary custom numeric scale is best expressed as a checked public metrics record in a later metrics slice, not a second competing size enum alongside XS–9XL. ## Review boundaries and architectural decisions Implement in reviewable order within the same presentation vocabulary: 1. Text refinement + independent named text parts and custom error content; default-token opt-in with explicit property tests. No Base changes. 2. Containers/card geometry and real input paint geometry; preserve input event reduction, IME, scroll/hit-test measurements and callbacks. No fake styled wrapper that changes paint only while leaving hit geometry unchanged. 3. Action custom content/trailing layout after a separate Button seam review. Existing `cui_button_styled_ex` is **paint-only refinement**, not custom child submission. Implementing action children by recreating button internals here would duplicate reducers and is rejected. A narrowly additive Button content API/private shared seam requires explicit ownership approval; no edits to `src/components/cui_components.c` are authorized by this checkpoint. A single huge options record is an alternative, but independent records/pointers avoid resizing legacy ABI and make omissions clear. A generic callback replacing whole interactive parts is rejected: it would transfer accessibility/input duties and fail to preserve source behavior. Caller-authored ordinary layout is already valid and remains the fallback for properties awaiting implementation. No new Core, state or binding ABI is required for slices1–2 **if** the geometry feasibility check succeeds. Form role is separately unresolved. No new dispatch, observer events or model ownership is proposed. Bindings do not automatically gain presentation callbacks, records or font capability; canonical integration must record omissions, matching headers/library, module/amalgamation ordering, compiled usage and generated consumer resources. Root owns manifest/integration changes. ## Required evidence before implementation claims - Independent old body versus new-zero submissions: compare semantic members, draw values, bounds and software pixels, never padding bytes. Cover all four legacy sizes, shared XS–9XL, root inheritance, explicit per-part override and standalone parts. Preserve omission/disabled gating and begin/end balance. - Differential default token table for each text role, line box, weight, card minimum, gap and radius; custom family ID and metrics must reach both layout and paint. Multiline long labels, empty/schema fallback/custom content, missing description title gap, differing line heights and first-line adornment offsets. - Active masks: explicit zeros/transparent/normal, ignored invalid unmasked values, unknown bits, NaN/infinity/range/UTF-8/NUL errors before callbacks, resources or event consumption. Descriptor snapshot before custom callback; borrowed bytes and nested independent roots have documented lifetimes. - Actual pointer/key/AT sequences on styled choices/input/actions: same IDs, focus/checked/disabled/invalid/description and legacy callback ordering, multiplicity, synchronous callback mutation, delayed confirmation and observer payloads. Presentation alone emits nothing. Never replace reducer coverage with a paint screenshot or invoke model methods as a substitute for routed input. - Native private Release wrapper, meaningful software pixels, WASI fixture with renderer fingerprint, C11 guide and C++ header compilation, sanitizer where practical; actual pinned formatting after final edits. Browser followup after canonical integration: desktop/touch, long localized copy, no overflow, custom decorative content with one semantic control, copyable compiled sample. This checkpoint runs no production tests because it changes documentation only. No production/API/status promotion is included; the compound/button seam and geometry feasibility questions require review before those implementation slices. ## Approved first-slice contract checkpoint The proposed declarations in `include/cui/cui_questionnaire_presentation.h` narrow this implementation to independent named text parts and noninteractive Error content. No container/card/input/action changes. Legacy zero named text metrics are extracted from heading; separate wrappers do not reproduce heading's internal gap automatically. Error zero preserves its existing current-item gate and Alert name, including localized model error with decorative replacement children. Source-like standalone error visibility remains deferred. TOKEN policy uses the frozen four-size text table; shared design sizes retain CUI scaling explicitly. Existing Alert composition is a single interact+box+text seam with no reducer; it supports custom noninteractive content without an architectural change. Production and evidence remain pending at this checkpoint. Implementation checkpoint: the first slice now supplies the four named APIs in `cui_questionnaire_presentation.h`, a separate Styled implementation and one private legacy option/metrics seam. Legacy Error delegates zero options. It does not implement the earlier proposed schema-error visibility policy, container/card/ input geometry, action children or trailing anchors. No full family promotion. The worker fixture owns temporary source registration until canonical integration. --- ## Questionnaire localized progress and bounded text presentation Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/QUESTIONNAIRE_PROGRESS.md # Questionnaire localized progress and bounded text presentation Approved checkpoint with a worker implementation. The additive header and progress-only common submission seam now implement the contract below; canonical registration and gallery integration remain separately owned. Baseline CUI is `9e5ec407`; frozen upstream is `87d10ae5e1299d1be18670a37570c5402f952e34` (v0.7.1), verified in the local `/tmp/cui-upstream-reference` checkout. This is one bounded family slice, not complete Questionnaire parity. Core Form-role support is explicitly outside this slice. ## Source evidence and actual gap All upstream paths below are relative to that exact frozen checkout. | Evidence | Frozen contract | Current CUI / remaining scope | | --- | --- | --- | | `crates/base/src/questionnaire/state.rs:179-190`; `types.rs:327-342` | Current is the one-based position among enabled items, or zero without a current item; total counts enabled items. This is question position, not answered/completed fraction. | `src/base/cui_questionnaire.c:51-70` already supplies enabled total/position. Preserve these helpers and float projection into existing semantics, including large-count precision limitations. | | `crates/component/src/questionnaire/components.rs:367-431` | Progress owns optional size, style and children. Localized `Questionnaire.progress` is always the accessible label. Custom children replace the default visible label, not the numeric semantics. Root role is ProgressIndicator, min zero, max total, value current. Muted foreground is the default. | `src/components/cui_questionnaire.c:573-599` already projects role/min/max/value and muted medium text. One English stack-formatted sentence serves both paint and accessible name. No progress-specific translated label, visible override or custom child API exists. | | `components.rs:203-211,248-252` | Progress uses typography xs except Large uses sm; custom source size uses size times .75. Token size, line height and weight are applied, then progress forces medium weight. Explicit Styled refinement follows, so callers may override it. | Legacy CUI uses 12px (14px Large), or design-size font times .75, medium weight and natural line height zero. The numeric similarities do not prove token line-box equivalence. Add opt-in explicit text metrics; leave legacy paint unchanged. | | `components.rs:181-226,232-252` | Answer, secondary/description and title have distinct token mappings; answer adornments align on the first answer line box. Title forces medium. Custom source size multipliers are 1, .875, 1.125 and answer line height 1.5. | These are neighboring typography obligations, not all solved by progress typography. Current title/description/choice/error defaults and first-line alignment must stay untouched in the proposed progress slice. A later family text slice can reuse the bounded refinement vocabulary after separate audit/tests. | | `components.rs:1584-1612` | Actual source test verifies progress numeric values and separately the root Form role. | `tests/unit/test_questionnaire_styled.c:418-444` verifies actual CUI progress semantics across three current positions. It does not verify translated names, replacement child text or explicit typography. The Form-role difference remains separate. | Existing `cui_questionnaire_options` has choice-only child callbacks, three box-only slot refinements and six masked action/error labels. It explicitly does not implement a typography cascade. Descriptor values are copied at submission; string bytes are borrowed through completed-frame consumption. Existing masked invalid values reject the submission before interaction. Root publishes size, not translations or slot styles. Those contracts must not silently expand. ## Chosen additive surface The worker adds `include/cui/cui_questionnaire_progress.h`, leaving the existing public options record and state layout unchanged. It includes the legacy Questionnaire header. One new Styled entry point takes the independent record by value: ```c /* Implemented additive declarations, shown here as the contract. */ enum { CUI_QUESTIONNAIRE_TEXT_SIZE = 1u << 0, CUI_QUESTIONNAIRE_TEXT_LINE_HEIGHT = 1u << 1, CUI_QUESTIONNAIRE_TEXT_COLOR = 1u << 2, CUI_QUESTIONNAIRE_TEXT_STYLE = 1u << 3 }; typedef struct { uint32_t fields; float font_size, line_height; cui_color color; cui_text_style style; } cui_questionnaire_text_refinement; typedef struct { size_t current, total; float font_size, line_height; cui_color color; cui_text_style style; } cui_questionnaire_progress_view; typedef void (*cui_questionnaire_progress_render_fn)( cui_context *, cui_id, const cui_questionnaire_progress_view *, void *); enum { CUI_QUESTIONNAIRE_PROGRESS_LABEL = 1u << 0, CUI_QUESTIONNAIRE_PROGRESS_VISIBLE = 1u << 1 }; typedef struct { uint32_t fields; cui_str label, visible; cui_questionnaire_text_refinement text; cui_questionnaire_progress_render_fn render_child; void *render_user; } cui_questionnaire_progress_options; bool cui_questionnaire_progress_ex( cui_context *, cui_id, const cui_theme *, const cui_questionnaire_state *, cui_questionnaire_options, cui_questionnaire_progress_options); ``` The existing void helper delegates with a zero record and discards the new bool. A zero record must be draw-command, pixels, semantics and callback equivalent to the existing helper for every legacy/design size and inherited-root size. No new state field, retained callback, locale registry or dispatch route is needed. ### Content and semantics precedence 1. Snapshot enabled current/total once using the existing model helpers. Resolve inherited size exactly once on the existing path. No validator/editor flush, model mutation, event emission or keyboard capture occurs. 2. Build the existing English fallback only when needed. A masked `label` replaces the accessible name; otherwise keep the exact existing sentence. Localization and pluralization belong to the host, which has the current/total helpers. No English-format parser or interpolation language is added. 3. Semantic role, min zero, max total and current remain model-derived even if supplied text says something different. Preserve the same ID, parentage, nonfocusable/noninteractive status and absence of activation handlers. 4. A non-NULL custom child callback replaces visible default content. Otherwise masked `visible` wins; otherwise use the resolved accessible label. Thus a translated accessible label alone translates the default visible sentence too. A visible-only override intentionally keeps the legacy accessible sentence. 5. Masked empty strings are valid explicit empty values, matching existing label options. Empty visible text can hide the sentence while leaving the accessible name/numbers. Empty accessible text is deliberate and does not remove numeric semantics; applications should normally supply a meaningful translated name. Unmasked strings are ignored, including their invalid/NULL bytes. The callback runs once synchronously inside the existing full-width progress wrapper after progress semantics are submitted. Its namespace ID is derived from root ID, distinct from the progress semantic node. It must balance its own boxes, not close the wrapper, mutate Questionnaire state or change event dispatch. It receives a borrowed scalar view; copy it if retained. The callback/user are borrowed only for that call and never retained by the model. Its render primitives may borrow strings/resources through normal completed-frame draw consumption. Custom text should normally remain decorative to avoid a duplicate progress node; applications adding interactive descendants own those independent semantics. The callback receives resolved text values but there is no implicit text cascade. It chooses whether to use those values with ordinary `cui_text_ex` or compose other content. This is the explicit C composition equivalent of source children, not arbitrary source Styled inheritance or a reusable arbitrary element tree. ### Typography and validation Apply the explicit mask after legacy metrics, muted color and medium weight. `TEXT_STYLE` replaces the complete portable `cui_text_style` atomically, allowing explicit normal weight, false italic/monospace, family zero and letter spacing zero. There are no per-field zero-sentinel ambiguities. Font size and line height are separate masks: finite font size in (0,512], finite line height in [0,4096]. Explicit zero line height requests existing natural Core spacing; positive values supply the text line box directly, rather than an outer fixed-height approximation. Color accepts the complete existing color value, including transparent. Validate active style weight against the four existing weights and finite letter spacing; retain Core's shaping-capability and cluster-progression rules rather than promising unsupported host shaping. Unknown presence bits, invalid active values and invalid UTF-8/embedded NUL in masked strings reject the entire submission, with no semantic node, draw or callback. `{NULL,0}` is valid empty; nonzero length requires readable bytes. No descriptor or text-arena allocation. Font-family IDs remain application-defined, with normal host fallback behavior. The new bool reports accepted submission versus invalid arguments/options. It is not a transaction over renderer/layout failures caused by custom content; those continue through ordinary frame error reporting. Legacy void failure behavior is preserved. A custom renderer does not excuse invalid active fields: validate the whole descriptor before any user callback. Copy descriptors and resolved values at entry; strings remain borrowed through draw/semantic consumption. Do not copy string bytes into hidden retained state. No source size enum is introduced. Existing design sizes XS through 9XL and root inheritance continue unchanged. A caller can explicitly choose font/line metrics from its theme to reproduce the source token relationships; this slice does not change CUI theme defaults or falsely equate every source custom size to a design step. A later token-mapping helper would need independently verified theme data. ## Intended usage and alternatives Proposed use: before frame composition, the application computes current and total with `cui_questionnaire_position`/`cui_questionnaire_total`, formats a localized sentence into its own bounded UTF-8 buffer, and passes LABEL plus an optional shorter VISIBLE sentence. Keep that storage alive until completed-frame draw and semantic consumption. For rich content, provide `render_child`, use view.current and view.total, and render a compact count plus ordinary decorative graphics. The callback cannot return a borrowed temporary string to outlive its invocation. A borrowed formatter callback returning `cui_str` was considered and rejected for this first slice: it adds a second callback/lifetime boundary merely to implement host localization already possible with public count queries. Root-global locale or typography pointers were rejected because they would introduce retained ownership, size-cache coupling and new propagation rules. Extending the existing by-value options record was rejected to avoid another unrelated ABI enlargement. A begin/end child API is possible later, but a bounded callback matches existing choice composition and makes wrapper balancing and one-shot resolved metrics clear. ## Implementation ownership and proof before promotion Production requires the new header, a progress-only private common submission seam in `src/components/cui_questionnaire.c`, a dedicated test and guide. No Base reducer, core role, public legacy options, observer, DatePicker or bindings change is needed. Canonical module/amalgamation/SDK/skill/docs registrations follow only after production review. Bindings initially omit this record, callback and text refinements explicitly; packaged C headers alone are not a binding facade. Required strict C11 Release tests through the private headless wrapper: - Differential old/zero path draw records, software pixels and complete semantics across all legacy sizes, XS..9XL, density/root inheritance, disabled items, no current/all disabled, completion/reset and repeated submissions. - Localized UTF-8 accessible label with one progress node; visible replacement differs without changing numbers; explicit empties; ignored unmasked invalid strings; active embedded NUL/invalid UTF-8, unknown masks, nonfinite/out-of-range text values reject before callback/semantics. Caller buffers retained across frame consumption; no hidden allocation or state mutation. - Actual text command font/weight/style/color/line height plus software pixel and measured-height changes with a deterministic font/metrics fixture. Verify explicit normal weight and natural-height zero, transparent color, wrapping and long localized text. Missing host font capability is an explicit limit. - Custom child runs once, replaces default visible text, uses stable separate namespace and reports unchanged model counts; default progress semantics stay intact. Descriptor copies are unaffected by callback-side descriptor edits. - Queued pointer/key/AT input plus attached legacy/typed observers demonstrate this passive helper consumes no activation or emits model events. Existing keyboard/observer/Styled suites remain regressions; no fake dispatch assertions. - Run the focused suite under the canonical pinned WASI runner, compile the real guide and C++ header, and prove standalone/new-header plus umbrella distribution consumers when canonical registration is assigned. - A separately owned gallery follow-up should expose localized and shortened progress, custom decorative count and typography examples. Headless actual-WASM tests must inspect real semantics, number changes during navigation/disable, text draw geometry and desktop/touch containment; no browser proof is claimed by this audit or by a native-only implementation. This closes only progress content/localization and explicit progress typography. Full family token mappings, root Form semantics, broad localization, arbitrary Styled behavior and language presentation/event facades remain separate work. All 78 manifest entries and honest partial-platform statements must remain. Implementation clarification: the derived nonzero child namespace is distinct from the progress ID but is not globally collision-free. Callers avoid their other application IDs as with existing choice child composition. The focused software test uses deterministic rectangular glyph coverage, proving transport and actual software compositing rather than production font shaping. Worker verification: strict Release native progress/Styled/keyboard/observer suites 4/4; pinned WASI equivalents 4/4; ASan/UBSan progress 1/1; real guide and C++ header consumer compiled; pinned clang-format 23.1.2 check passed. Zero comparison uses an independent pre-change rendering body, not two calls through the new forwarding seam. Tests compare semantic/draw members and pixel bytes without comparing ABI padding. Completed progress is checked before reset and reset separately. No browser, production font shaping or physical AT proof is claimed; canonical generators and gallery are still pending integration. --- ## Questionnaire copy-out snapshots contract Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/QUESTIONNAIRE_SNAPSHOTS_CONTRACT.md # Questionnaire copy-out snapshots contract Design checkpoint only. No declarations or implementation in this document are available APIs. Base is CUI `206ba95c`; frozen source authority is commit `87d10ae5e1299d1be18670a37570c5402f952e34` in the local reference checkout. This slice provides immutable caller-owned copies and scalar queries. Event observers, callback mutation rules and changes to legacy reducers are separate. ## Source and existing API reconciliation Frozen `crates/base/src/questionnaire/types.rs:254–324` defines copied choices and optional freeform, excluding editor drafts, plus schema-ordered named answers. `types.rs:454–500` defines navigation visibility and confirmability. Answer-change payloads carry copied item name, answer and status (`535–566`); submission items carry the same three fields (`568–621`). Current-change events copy optional previous/current names (`623–632`). Frozen `state.rs:180–191,254–284` provides enabled progress, navigation, individual answers and all enabled answers. `state.rs:1088–1143` constructs submissions and filters effective answers: disabled items return empty answers; disabled choices and disabled input are excluded; choice order is definition order. Status can remain Skipped even when an item is disabled. `state.rs:746–767` validates enabled items, then constructs one submission before Completed(clone) and Submit. Current `cui_questionnaire.h` and Base implementation provide find, total, position, choice_selected, freeform, item_status and item_error. Freeform is a borrowed view into mutable workspace. There is no copied answer/submission or aggregate navigation query. Public structures expose schema/current state, but reading them after an edit does not preserve an earlier answer. Existing tests cover model correctness, capacities and event order; they do not establish a retained copied submission. Keyboard policy APIs do not fill this gap. The proposed copy-out submission is callable before completion. Like source's answer collection, it reports current effective data. It does not validate, submit, mark complete, flush an editor, tick a timer or invoke a callback. Its name does not certify that the data is acceptable for transport. ## Proposed portable C11 surface New header `cui_questionnaire_snapshots.h` includes the legacy model header only. Names below are proposed exact declarations for review: ```c typedef enum { CUI_QUESTIONNAIRE_SNAPSHOT_OK, CUI_QUESTIONNAIRE_SNAPSHOT_INVALID, CUI_QUESTIONNAIRE_SNAPSHOT_UNKNOWN_ITEM, CUI_QUESTIONNAIRE_SNAPSHOT_CAPACITY, CUI_QUESTIONNAIRE_SNAPSHOT_OVERFLOW } cui_questionnaire_snapshot_result; typedef struct { const cui_str *choices; /* copied values in choice-definition order */ size_t choice_count; bool has_freeform; cui_str freeform; /* copied effective answer, not editor draft */ } cui_questionnaire_answer_snapshot; typedef struct { size_t item; /* original schema index, not enabled index */ cui_str name; /* copied identity, not presentation label */ cui_questionnaire_status status; bool disabled; /* useful for an individual disabled item */ cui_questionnaire_answer_snapshot answer; } cui_questionnaire_item_snapshot; typedef struct { const cui_questionnaire_item_snapshot *items; size_t count; /* enabled items in schema order */ } cui_questionnaire_submission_snapshot; typedef struct { size_t items, choices, text_bytes; /* bytes INCLUDE all appended terminators */ } cui_questionnaire_snapshot_requirements; typedef struct { cui_questionnaire_item_snapshot *items; size_t item_capacity; cui_str *choices; size_t choice_capacity; char *text; size_t text_capacity; } cui_questionnaire_snapshot_workspace; typedef struct { size_t current_item; /* schema index, SIZE_MAX when none */ size_t position; /* enabled zero-based index, SIZE_MAX if none */ size_t current, total; /* one-based progress (or 0), enabled total */ bool previous_visible, next_visible, skip_visible, submit_visible; bool confirmable, complete; } cui_questionnaire_query_snapshot; cui_questionnaire_snapshot_result cui_questionnaire_answer_measure( const cui_questionnaire_state *, size_t item, cui_questionnaire_snapshot_requirements *required); cui_questionnaire_snapshot_result cui_questionnaire_answer_copy( const cui_questionnaire_state *, size_t item, cui_questionnaire_snapshot_workspace, cui_questionnaire_snapshot_requirements *required, cui_questionnaire_item_snapshot *out); cui_questionnaire_snapshot_result cui_questionnaire_submission_measure( const cui_questionnaire_state *, cui_questionnaire_snapshot_requirements *required); cui_questionnaire_snapshot_result cui_questionnaire_submission_copy( const cui_questionnaire_state *, cui_questionnaire_snapshot_workspace, cui_questionnaire_snapshot_requirements *required, cui_questionnaire_submission_snapshot *out); cui_questionnaire_snapshot_result cui_questionnaire_query_copy( const cui_questionnaire_state *, cui_questionnaire_query_snapshot *out); ``` An answer copy requires one workspace item record. `out` receives a by-value copy of that record; nested pointers refer only to caller snapshot workspace. Submission output refers to the first `required.items` workspace records. Both operations use the same representation so a submission's answers project directly to source's named-answer collection; no duplicate all-answers serialization API is necessary. Status/disabled/index are additional portable query information. ## Exact data rules - Individual lookup uses the existing schema index; invalid state is INVALID and an out-of-range index is UNKNOWN_ITEM. A disabled existing item still produces its copied name/status, `disabled=true`, and an empty effective answer. Disabled items are omitted entirely from a submission. Empty schemas yield a successful zero-item submission and zero requirements. Empty submissions use items=NULL; zero-choice answers use choices=NULL even if spare workspace was supplied. - All enabled items appear, including Unanswered and Skipped, in original schema order. This is not an answered-only collection. Choices contain copied values, not labels or indices; retain original definition order, deduplicated by the existing retained model, excluding disabled/unselected choices. - Freeform uses the effective retained answer. Unsynchronized editor drafts, initial-answer/reset buffers and disabled input are excluded. Existing model blank normalization determines absence; copying does not trim or normalize bytes further. `has_freeform=false` implies `{NULL,0}` and consumes no text bytes. Present freeform preserves leading/trailing whitespace around nonblank content and exact UTF-8 bytes. - Skipped means copied status Skipped and the effective answer given by the existing model; ordinary skip clears it. Copy-out must not independently invent a second status reducer. Reenabled retained choices follow existing live policy. - Each included name, choice value and present freeform is independently copied followed by one NUL. `cui_str.length` excludes that terminator. Requirements' `text_bytes` includes it, including one byte for an empty name/value. No string deduplication, interning or shared empty-string sentinel. Pack each item name, then its selected choice values, then present freeform; process items in schema order, without alignment padding in the text arena. Existing accepted embedded NUL bytes are preserved, not rejected by a new snapshot-only rule; consumers must use lengths rather than assume arbitrary values are C strings. - Labels, descriptions, validator messages, editor objects and callbacks are not copied. No platform/Clay types, heap allocation, global buffers or renderer dependencies. Definitions and model workspace must remain valid during each operation; copied names/values no longer depend on them after success. ## Measurement, bounds and transactional failure `required` is mandatory for measure and copy; `out` is mandatory for copy/query. Null required output pointers return INVALID without dereferencing them. Other provided output records are reset to their documented empty state on failure: requirements all zero, item/submission all zero; query has current_item/position SIZE_MAX and all remaining fields zero. CAPACITY is the exception for requirements: it publishes exact requirements, but leaves snapshot output empty. Measure is a pure full scan with checked additions for item/choice counts and `length+1` per string; record-array byte multiplication is checked too. Any unrepresentable count, byte extent or total returns OVERFLOW with zero requirements. A bounded fake-length test must reach the checked arithmetic without reading the fictitious bytes; this does not promise safety for arbitrary invalid C pointers. There is no saturating “successful” requirement or truncated copy. A workspace pointer may be NULL exactly when its capacity is zero. Nonzero capacity with NULL pointer is INVALID. Capacity zero with non-NULL pointer is valid but still has zero writable elements. The complete measured requirements must fit all three capacities before the first workspace write. Insufficient capacity returns CAPACITY, no partial records/bytes, no truncation and no NUL write even if text capacity is positive. Thus a failed copy preserves a previously published snapshot in those buffers; the new `out` is empty and cannot appear partially valid. This differs intentionally from a truncating text formatter. The API performs all fallible checks before committing writes. Once sufficient capacity and valid source are established, filling must not invoke fallible callbacks or allocate. State/schema/editor mutation during measure or copy is forbidden; no concurrency, generation lock or mutation detector is implied. Separate measure and copy may observe different states: copy always remeasures and reports its own requirements. Never trust a stale measured count to write. Snapshot workspace arrays/text, required and output records must be mutually disjoint and disjoint from the model, schema, editor data and model workspace. These are explicit caller preconditions, consistent with the legacy workspace; this slice does not promise arbitrary overlap detection or pointer provenance validation. In particular `out` must not be `workspace.items`. Reusing the same workspace for a successful copy invalidates its previous snapshot; reusing it for a failed copy does not. Caller copying a record alone does not clone its buffers. Existing model limits remain: at most 4096 items, answer-byte capacity defaults to 4096 and is bounded at 1 MiB per input. Choices/schema string bytes are bounded by actual caller declarations/workspaces, not an invented new fixed snapshot cap. Requirements are size_t and checked against SIZE_MAX on every accumulation and record extent. Copy iterates the validated initialized schema; forged retained structures remain outside the model contract. No dependency installation needed. ## Scalar query semantics Query does not need workspace and runs no validators. Enabled total and position match existing accessors for valid model states. No current enabled item gives SIZE_MAX item/position, progress current 0, all visibility/confirmable flags false; complete still reflects the retained complete flag. With a current enabled item: previous is position>0, next is position+1float precision, bounds/pixels, no callback writes, null-handler behavior. | | 2. Number Input aggregate numeric CHANGE | [`cui_base_number_input`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_numeric.c) has a mutable draft edit plus `double *value`; valid draft parses at the end, Enter/blur clamp, step keys/buttons can update during reduction. `step_by` in [`cui_numeric.h`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_numeric.h) is a transformation policy, not a notification. Start with one typed double before/after observer around the complete Base/Styled call, separately from draft revision. No per-event numeric CHANGE reconstructed from the final parse; no generic COMMIT/SUBMIT inferred from the aggregate boolean. | [`test_numeric.c`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_numeric.c), [`test_button_numeric.c`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_button_numeric.c): invalid editable draft, valid draft/value divergence, exponent/IME, Enter versus blur, custom stepping, clamp/format failure, multiple updates, owner-pointer compatibility and copy/lifetime limits. Exact per-event submit requires a later audited loop hook. | | 3. Rating | [`cui_base_rating`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_numeric.c) normalizes/clamps the float even before interactive reduction, then processes star/clear/key inputs. Start with aggregate applied float CHANGE including explicit normalization reason/unknown cause; alternatively introduce genuine per-event hooks only after separating normalization from input transitions. Never claim owner rejection. | [`test_numeric.c`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_numeric.c): half-step pointer position, keyboard, clear, readonly/disabled normalization, nonfinite input, repeated events with equal final value, Styled paint equivalence. | | 4. Stepper + Pagination, separately reviewable | [`cui_base_stepper` and `cui_base_pagination`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_numeric.c) mutate size_t indices and also normalize out-of-range values. Cheap aggregate typed index notifications are viable; per-event notifications require narrow reducer hooks to preserve every intermediate assignment. Pagination is one-based (zero for no pages); Stepper is zero-based, with caller-owned statuses. Do not share an ambiguous generic index meaning. | [`test_numeric.c`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_numeric.c): disabled-item suppression, empty models, normalization, several activations, keyboard/accessibility where supported, no fabricated activation for normalization, Base/Styled equivalence. | | 5. Tabs | [`cui_base_tabs`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_choice.c) combines selection, scroll/overflow and drag requests; [`cui_tabs`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_choice.c) owns Styled composition. Begin with selection-only typed ID CHANGE, distinct from drag/reorder request and overflow lifecycle. Per-event selection is viable only at actual assignment sites and any overflow path; aggregate is a smaller explicit exception. | [`test_choice.c`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_choice.c): keyboard/activation/disabled, overflow selection, drag request without selected change, scroll-only silence, callback mutation restrictions and unchanged animation/paint. Reuse metadata vocabulary from [`cui_selection_events.h`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_selection_events.h), not its payload where cause is unavailable. | | 6. List / ToggleGroup | [`cui_choice_private_list_events`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_choice.c) is a genuine ordered loop; existing on_activate/on_confirm/on_cancel in [`cui_choice.h`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h) already provide actions in event order. Add optional typed evidence at that seam if needed; selection CHANGE must be distinct from confirming the already-selected item. Multi-list/ToggleGroup need item+bool transitions, not one selected ID. | [`test_choice.c`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_choice.c): unchanged-item confirmation, multiple activations, Escape, secondary modifier, virtualization/window changes, callback order and no duplicate legacy callbacks. Do not duplicate existing List actions merely to rename them. | Styled wrappers must not reduce twice. If they contain late mutation (as Editor's completion popup does), observe the complete outer call or add the hook at each real mutation seam; do not assume all Styled controls only paint after Base. ## Subsequent interactive work The menu, picker, OTP, disclosure and Tree recommendations below describe the original audit. The implemented guides above supersede those missing-API claims; remaining work includes additional domains and explicit exceptions, rather than reimplementing those facades. - **Menu/DropdownButton:** follow the existing [menu/surface proposal](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/MENU_DIALOG_EVENTS_SLICE.md) after in-flight work settles. [`cui_choice.h`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h) and [`src/base/cui_choice.c`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_choice.c) distinguish action IDs, check/radio state, popup open/close and nested tree navigation. A final selected ID cannot represent repeated action activations. Use `test_choice.c` for legacy event-order, disabled, submenu and keep-open behavior; keep close lifecycle separate from selection or activation. - **Calendar/DatePicker, OTP, disclosure and Tree:** inspect typed result seams in [`cui_picker.h`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_picker.h), [`cui_otp.h`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_otp.h), [`cui_disclosure.h`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_disclosure.h), and [`cui_tree.h`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_tree.h). At the original audit these lacked a common typed notification facade; the guides above now define the implemented additions. Split date selection from displayed-month navigation; OTP draft CHANGE from completion; Accordion per-panel changes from final array; Tree selection from expansion/activation. An aggregate observer is compatible only if documented as losing multiplicity/cause. Dedicated existing evidence: `tests/unit/test_picker.c`, `test_otp.c`, `test_disclosure.c`, `test_tree.c`. - **DataTable/Settings/Sidebar:** preserve their existing typed results and owner decisions. Table selection/sort/column notifications require stable IDs and column/value tags, not lossy float values; use [`test_table_selection_contracts.c`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_table_selection_contracts.c). Settings on_change lacks a typed changed-value payload, and Sidebar's controlled expansion callback is a request, not proof of accepted expansion. See [`cui_settings.h`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_settings.h), [`cui_sidebar.h`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_sidebar.h), `test_settings.c`, `test_sidebar.c`. ## Existing callbacks and justified exceptions Button's old typed click callback already carries copied evidence. List actions, Command select/query/confirm/cancel, Attachment click/remove/retry, Sidebar actions, Toolbar command activation and TitleBar close already provide useful synchronous application hooks. Their result/callback coexistence should be documented and tested, not dispatched again by reading results. These callbacks satisfy their family action/request role; they do not all have shared metadata, typed values or identical ordering. Source contracts: [`cui_command.h`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_command.h), [`cui_media.h`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_media.h), [`cui_toolbar.h`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_toolbar.h), [`cui_chrome.h`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_chrome.h). Retain the contract's lifecycle exceptions: Surface close decision versus eventual close; Notification retained descriptors; Speech generation-tagged owner-thread pump; Carousel/Resizable/Root/Questionnaire/Dock retained registration; Plot/Chart layout/prepaint/paint borrowing. Omitting draw does not cancel these lifetimes. Do not replace explicit close-result latches, pump timing or retained teardown with submission-borrowed generic handlers. Scrollable/VirtualList/MessageScroller also need scroll/window timing contracts, not an invented item activation event. Alert, Avatar, Badge, Bubble, Empty, GroupBox, Kbd, Label, Marker, Message, Progress, Separator, Skeleton, Spinner, StatusBar and other composition-only entries have no intrinsic editable value/action to observe. Icon/Image loading, Theme loaders, Clipboard services and render/measurement/format/easing callbacks are separate resource/policy roles. Child controls retain their own events; a successful paint/submission boolean is not activation. See the baseline inventory for each noninteractive exception rather than adding no-op family handlers. ## Foreign-language boundary and verification limits The landed [V1 notifications](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_NOTIFICATIONS.md) and [Go/Rust views](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_NOTIFICATIONS_GO_RUST.md) cover their explicit allowlist (activation, applied boolean/table changes and surface close outcomes), preserving legacy queues/timing. They do not expose native synchronous controlled requests, Slider phases, Input per-event observers or multiline observers. The separate [opt-in C value poll](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_VALUE_NOTIFICATIONS.md) additionally classifies its explicit scalar/text/selection allowlists; Python/JS/TypeScript/Go/Rust owning value wrappers are implemented. Other payloads remain legacy; typed C facades alone do not complete Python/JS/TS/Go/Rust coverage. Do not retime queued handlers into rejectable requests. Future slices need tagged owned payloads, bounded queue/copy behavior, full-width IDs/frame values, handler retention/removal, exception/panic containment and stale-object tests. Follow [the binding audit](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_BINDINGS.md), not launcher-only examples. This audit inspected current facade headers and the reducers above against the 78-family inventory and contract. It did not rerun runtime suites or certify all 78 implementations. Production slices require strict native private-display tests, headless browser/foreign tests where applicable, exact legacy compatibility and explicit evidence/count/lifetime limits. No feature-ledger status changes follow from this document. --- ## Remaining parity: implementable work at the next39 checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/REMAINING_PARITY_AUDIT.md # Remaining parity: implementable work at the next39 checkpoint Audit baseline: `9c61c158`, `integration/next39-components`. Frozen comparison: upstream kit 0.7.1, commit `87d10ae5e1299d1be18670a37570c5402f952e34`, recorded in [the upstream baseline](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/upstream-baseline.md). This is a read-only scheduling audit, not production work, a fresh runtime verification report or a promotion of any family. All 78 manifest entries must remain. ## How to read the evidence [The manifest](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/gpui-parity.json) contains 78 families: 77 `tested`, one `implemented` (Questionnaire). Its 360 feature rows contain 315 `tested`, four `implemented` and 41 `not_started`. These are recorded classifications, not a completion percentage: `tested_partial` platforms, inherited styling limitations, provider differences and unverified host behavior still matter. Conversely, several old feature rows describe work that now has implementation and tests. This refresh inspected the public declarations, implementation seams and focused test sources cited below at the audit baseline. Earlier audit conclusions and recorded passing gates remain historical evidence; **no native, browser, binding or packaging tests were rerun for this documentation-only refresh**. Inspection is not a fresh runtime verification or a new frozen-source certification of every family. Proposed acceptance cases are future work unless explicitly identified as existing tests. Existing guides can contain chronological paragraphs superseded by later additions; follow the actual current API and implementation. ## Do not schedule these requests from stale rows | Stale shorthand | What is already present | What remains distinct | | --- | --- | --- | | Questionnaire lacks automatic root capture/cross-item focus | [Styled implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_questionnaire.c) routes through prior-frame bindings and ordered input reduction; [styled tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_questionnaire_styled.c) cover automatic routing, omission and focus. [Guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/QUESTIONNAIRE.md) ends with the newer contracts. | Bounded box-slot refinements and six localized labels landed in the follow-up below; nested roots, comprehensive callback choreography, broader styling and localization still need completion. Earlier paragraphs and manifest prose are not the final source truth. | | Icon padding/nonzero style is unsupported; no accessible API | [Icon options](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_icon.h), [resolver](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_icon_layout.h), [source-style tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_icon_style_source.c), [accessibility tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_icon_accessibility_source.c) implement numeric bounds/padding/border floors, full-box paint, explicit image labels and decorative suppression. | Ambient inheritance, generic Styled layout and SVG renderer fidelity remain limited. Do not redo numeric constraints or add guessed asset-name labels. | | Slider has no controlled value/semantics | [Base API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_base.h) and [controlled tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_slider_controlled.c) already define typed BEGIN/UPDATE/COMMIT/CANCEL requests and read-only behavior without a handler. | Typed Base/Styled facades and aggregate bridge scalar notifications now exist; foreign controlled phases remain distinct. Do not replace phased semantics with one bool change callback. | | Text gradients/tokens/tracking are wholly absent | [Tokens](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TYPOGRAPHY_TOKENS.md), [gradient implementation](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TEXT_GRADIENT.md), [native tracking](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/LETTER_SPACING.md), [real gallery gradient proof](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/web/test_gradient_gallery.py). | Canvas tracking, foreign authoring and GPU support are unfinished. Reimplementing solid/gradient paint or native tracking would duplicate completed work. | | Native SDK text is unshaped; App.run only polls a fixed-frame loop | [SDK parity guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SDK_TEXT_PARITY.md), [installed text fixture](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/packaging/test_installed_text.py), [bridge runner](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/bridge/cui_bridge.c), language run tests in bindings. | Provider coverage and style/event API gaps below remain. Launcher-only examples are not evidence about the actual bindings. | | Every native accessibility adapter is absent | [AccessKit adapter](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/backends/accesskit/cui_accessibility.c), [native guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NATIVE_ACCESSIBILITY.md), [integration test](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/integration/test_accessibility_native.c) exist. | Real assistive-technology acceptance and complete family/platform mappings must be evaluated within that adapter's documented support, not inferred from semantic snapshots. | ## Ranked production slices Priority reflects the explicit typography/event/frozen-family requests and a small reviewable implementation boundary, not a claim that lower entries are less important forever. Each slice needs a separate approved owner and generated consumer refresh by the integrator where public ABI/source changes require it. ### 1. Close Spinner proof and consumer gaps after the shipped corrections The previously scheduled finite-turn easing, reduced ease(0), and named-rem versus custom-pixel descriptor changes are implemented in [Spinner submission](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_content.c) and [public options](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_content.h). Spinner accepts finite overshoot, normalizes in double before radians, and evaluates custom easing at zero under reduction without scheduling a wake. Skeleton and the legacy shared sampler keep their bounded policy. [Contract tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_spinner_contract.c) and [motion tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_status_motion.c) contain native regression coverage; this refresh inspected rather than executed them. Next bounded slice: extend the [real WASM fixture](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/web/test_spinner_gallery.py) to negative/>1 turns, shifted reduced ease(0), nonfinite failure and named rem at multiple root scales versus fixed custom64. Separately combine caller-owned raw SVG, numeric Icon style, explicit color, rotation and source replacement while consuming retained draws before destruction. The [dedicated audit](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/audits/SPINNER_PARITY.md) retains the full proof boundary, including independent mounts/source curves. The bridge still uses legacy eight-dot Spinner; source-style bridge options need their own additive contract and tests. Neither these shipped native corrections nor old default-curve browser checks establish full Spinner parity. ### 2. Deliver browser tracking with the same declared shaping policy [Native text](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/text/cui_text.c) implements cluster tracking and advertises `CUI_TEXT_CAP_LETTER_SPACING`; [Core](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/core/cui.c) gates unsupported providers. [Gallery Canvas host](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/web/gallery.js) still measures/draws browser text without this capability. Nonzero browser tracking is unavailable, not a completed browser feature. Native tests already cover no trailing gap, ligatures, negative progression, wraps and density; preserve them. First decision: evaluate whole-context Canvas `letterSpacing` with actual cluster, ligature and bidi geometry. It cannot simply be advertised if browser spacing counts different boundaries or adds a terminal gap. If it fails the portable contract, use an optional shared WASM-shaped provider plus positioned glyph masks, with explicit font ownership/capabilities; do not draw UTF-8 characters separately or silently approximate. This is a provider decision before adding a gallery knob. Acceptance: a new real-WASM/headless browser tracking fixture, using explicit fonts and actual pixels/geometry, covering ligature/combining/Arabic/RTL/mixed runs, narrow/wide reflow, negative rejection, no final gap, selection/carets, DPR1/2 and mobile width. Compare the policy, not exact cross-platform raster bytes. Extend [native tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/integration/test_letter_spacing.c) only where new shared behavior needs regression; preserve zero-spacing exact compatibility. ### 3. Extend font selection without pretending four weights are CSS [Text style declarations](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui.h) expose family IDs, four named weights and italic/monospace flags. [Native registry](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/text/cui_text.c) selects registered faces; arbitrary numeric weight, independent same-family stretch and variable axes are not authorable. Registering a condensed static face as another family already works and should remain a documented interim solution. [Typography roadmap](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TYPOGRAPHY_ROADMAP.md) contains illustrative future types, not shipped declarations; semantic tokens themselves are already implemented. Bounded first slice: additive versioned face-selection descriptor and explicit static-face registrations for numeric weight/stretch, with exact/fallback policy and consistent measurement/raster/cache keys. Variable axes/optical sizing should follow only with identity, range/clamping, ownership and provider support defined. Preserve old enum meanings/defaults and reject unsupported combinations observably. Acceptance needs actual differing registered faces, geometry/pixels, cache invalidation, missing-face policy and installed binding consumers; font-stack CSS strings alone cannot prove equivalent native selection. ### 4. Audit uncovered C lifecycle seams instead of rebuilding shipped facades The activation proposal is no longer the implementation frontier. The current [78-family inventory and additive checkpoint](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_COVERAGE.md) records shipped Base/Styled facades for activation, boolean requests, Slider, Input, multiline observers, selections, surfaces, menus, numeric/picker controls, OTP, disclosures, List/ToggleGroup, Tree, DataTable, Attachment, TimeField, Sidebar, Command, Toolbar, InputGroup and Settings. Separate [Scroll](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SCROLL_EVENTS.md) and [Hover](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/HOVER_EVENTS.md) guides cover their newer lifecycle observers. [Public metadata](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_component_events.h) is shared infrastructure, not the only shipped event API. Focused tests such as [controls](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_control_events.c), [table](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_table_events.c), [scroll](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_scroll_events.c) and [hover](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_hover_styled_events.c) are existing source evidence. Next bounded audit: identify a genuinely uncovered lifecycle/result seam from the current inventory, specify multiplicity, snapshot point and retention, then add only that observer with meaningful headless regressions. For example DataTable viewport/load-edge completion remains result-only; do not reinterpret it as an existing notification. Render-only primitives do not need invented value events. Preserve controlled request versus applied CHANGE, aggregate versus per-event counts, callback order, secure redaction and explicit unsupported accessibility channels. No generic capture/bubble, context destruction during synchronous callbacks or universal callback mutation support is established. ### 5. Extend the bridge's remaining typed allowlist and typography authoring Versioned [V1 notifications](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_NOTIFICATIONS.md) and opt-in [value notifications](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/BRIDGE_VALUE_NOTIFICATIONS.md) are shipped in the [C bridge API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_bridge.h) and implementation. Python, JS/TypeScript, Go and Rust have owning manual views. Initial CLICK, boolean, DataTable and close payloads are followed by explicit scalar (Slider/NumberInput/Rating/Pagination), plain-text (Input/Textarea/Editor/InputGroup), and selected-handle (RadioGroup/Tabs/Select/List/Stepper) allowlists. Copied text, raw table columns, historical generations and exact uint64 identities must not be rescheduled as missing blanket features. Existing C tests cover [initial](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_bridge_notifications.c), [scalar](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_bridge_value_notifications.c), [text](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_bridge_text_notifications.c) and [selection](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_bridge_selection_notifications.c) queues. Next event slice: choose one remaining LEGACY producer, such as Questionnaire, and define an additive typed notification captured at its real enqueue seam. Questionnaire still encodes kind in `value` and completion in `checked`; Combobox/menu/picker and other unlisted producers must stay LEGACY until audited. Preserve shared-FIFO single consumption, old-poll downgrade, capacity retry, optional-symbol negotiation and owning wrapper copies. Existing manual polls do not bind direct-C facades, add per-input multiplicity, register callbacks or offer synchronous rejection; old callback conversions remain their documented legacy behavior. [Binding audit](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_BINDINGS.md) and the per-language value guides define the exact boundary, including paired static Rust SDK requirements. Separate consumer slice: expose native tracking/font/paint authoring and an explicit source-style Spinner with reduced motion. Current flat styles omit native `letter_spacing`, and bridge Spinner remains legacy. New fields need observable unsupported-provider failure and actual installed consumer tests; manual notification success cannot prove typography support. ### 6. Complete Questionnaire beyond bounded box slots and labels Follow-up `5744beb8` implements three independent masked box-slot descriptors and six localized action/error labels. [The guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/QUESTIONNAIRE.md) defines default/custom-renderer precedence, submission snapshots, borrowed text lifetime, invalid preflight and the by-value options ABI rebuild requirement. Focused native and sanitizer evidence covers all four legacy sizes, zero/transparent overrides, translated text and default compatibility. This is not browser or full-family proof. Next slices: expose and verify the remaining typography/general style refinements, audit frozen part methods, then test nested roots, subscriber-driven enabling/ navigation and callback mutation ordering against frozen Base tests. No arbitrary callback reentrancy or context destruction contract is implied. Six caller-supplied labels are not a general locale/formatting engine or automatic root inheritance. Extend [model](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_questionnaire.c) and [Styled](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_questionnaire_styled.c) coverage plus actual gallery WASM interactions for the new styles/translations, callback sequences, disabled/omitted/reintroduced parts and nested focus ownership. Do not schedule the already delivered box masks or label bundle again, or promote parity from palette screenshots or reducer tests alone. ### 7. Close the remaining Icon/Spinner inherited-style boundary deliberately Numeric sizing and explicit semantics are complete scoped work. Remaining [Icon limitations](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/ICON.md) are automatic ambient text-style inheritance, arbitrary source flex/percentage refinements and NanoSVG-versus-resvg coverage. The supported parser may accept constructs without reproducing full source SVG rendering; imported source support must not be inferred from successful parsing. Choose explicit, composable ambient typography inputs before a global style stack; add an SVG feature/capability corpus and reject/document unsupported constructs, or approve a new optional renderer dependency with licensing/resource limits. Do not fake percentages as pixels or change padding to inset SVG paint: source Icon paints full resolved bounds. Extend [Icon style browser fixture](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/web/test_icon_style.py) and native source/lifetime tests for any newly supported subset; combine custom raw-data Icon styling with animated Spinner before claiming the composition. ### 8. Finish editor navigation and performance beyond shipped visual geometry The old blanket claim that editor hit/caret geometry is absent is stale. [Input visual geometry](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/INPUT_VISUAL_GEOMETRY.md) supplies an optional host session, and [Textarea source](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_textarea.c) now uses visual geometry for row x/hit, caret affinity and selection spans, caching bounded line sessions. [Editor](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_editor.c) reuses these row helpers. The native [geometry fixture](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/integration/test_native_text_geometry.c) contains real shaped Input checks and a separate `--audit` mode; its default run must not be mistaken for proof that every multiline audit case passed. Older INPUT/TEXTAREA/EDITOR paragraphs retain superseded descriptions alongside later work. Native shaping alone still does not establish complete edit behavior. Next bounded slice: audit and test mixed-direction visual Left/Right, Home/End, preferred-x movement and multiline selection against provider geometry, including run-boundary affinities, wrapping, folds and syntax-painted segments. Existing logical grapheme movement is not visual bidi navigation. Preserve byte offsets, undo, token boundaries, optional-provider fallback and resource failure behavior; inspect actual geometry use before replacing already working hit/caret paths. Separately instrument layout/allocation work across edits and scrolls in a 200K-line document. Existing large-document correctness does not prove viewport-only layout or incremental performance. Set measurable budgets before implementation. Multicursor IME, asynchronous browser clipboard and physical OS/mobile candidate acceptance remain separate work. ### 9. Renderer and host completion follow feature delivery [Text gradients](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/TEXT_GRADIENT.md) and tracking explicitly preflight-reject unsupported Sokol/SDL_GPU commands. Implementing those GPU paths is a real feature slice: shared shaping, continuous glyph-mask paint, premultiplied color, physical-density/clip handling, negative tracking and whole-frame rejection must remain consistent. Software/SDL/Canvas success is not GPU hardware proof. [Speech](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SPEECH.md) still has injected recognizers rather than complete real capture/conversion/recognition integration. Choose one optional host, bounded PCM ownership/cancellation/wake semantics and deterministic provider tests before live-device acceptance. Existing speech controls do not prove a microphone works. [Surface](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SURFACES.md) follow-up should target body scrollbar/focus reveal and explicit Popover anchor/offset/arrow policy; Root layers and Sheet motion now exist in scoped APIs, so do not globally label all overlay management/animation absent. These are distinct owners and gates, not one giant “finish platforms” patch. Native tests must use the private-display wrapper; browser tests stay headless. Unsupported GPU/device/screen-reader checks remain explicit host acceptance work. ## Ledger reconciliation after implementation, not instead of it The 41 `not_started` features are not 41 independent missing implementations. Examples include controlled Slider, DataTable sort/virtualization, Table semantics, Sheet transitions, Theme preferences and Empty slots, all with later implementation or scoped tests. Conversely Spinner's family text needs current easing/rem evidence and the remaining browser/consumer boundary. The integrator should reconcile those rows against current source, record the exact supported subset/tested hosts and retain full-family limitations. Do not delete families or invent completion to make counts uniform. Each delivered slice needs source tests, actual relevant consumer tests, human/LLM guide examples, source metadata and regenerated distributions/SDKs through existing tooling. The optional [async-fetch example](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/examples/async_fetch/README.md) is already present and offline-tested; it is not a missing new event API. Its bounded wake retries do not guarantee recovery from persistent SDL event rejection. Preserve that exception rather than scheduling duplicate networking/Core thread-pool work. --- ## Scoped lifetime cancellation: consumer audit Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SCOPE_INPUT_CANCEL_CONSUMERS.md # Scoped lifetime cancellation: consumer audit Status: **partial source audit; no production marker API is implemented**. See [the proposed marker contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/DIALOG_BUILTIN_CANCEL_MARKER.md). The operation must preserve existing dispatch and no-helper behavior. A consumed sample, a cancelled press, value acceptance and platform default prevention are separate concepts. ## Confirmed gaps | Consumer | Current evidence | Required acceptance | | --- | --- | --- | | Base scrollbar (`src/base/cui_scroll.c`) | Actual nested close/reopen test applies old captured MOVE+UP: scroll 0 → 285.714. Reducer ignores consumed samples and retains caller-owned dragging state. | Explicit reset must clear idle/held drag and suppress cancelled samples. Prove mouse/touch, fresh DOWN recovery and unchanged no-helper trace. | | Resizable (`src/base/cui_resizable.c`) | Actual original nested reducer applies stale MOVE+UP: size 100 → 40 and spurious completion. It retains `active_handle`/`dragging` and ignores consumption. | Test nested old MOVE+UP, idle state, fresh input and callback counts/order; preserve legacy behavior when reset is unused. | | Rating (`src/base/cui_numeric.c`) | Actual queued stale arrow changes 2 → 3: direct case is already consumed; nested-modal case remains unconsumed. Target identity stays intact. Activation cancellation does not cover this raw value path. | Test direct and nested-modal arrows/Home/End/Delete during lifetime reset; preserve ordinary legacy keys. | | Basic legacy Slider (`src/base/cui_base.c`) | Actual queued stale arrow changes 2 → 3 in direct (consumed) and nested-modal (unconsumed) cases. Raw targeted processing bypasses activation cancellation. | Test direct/nested stale samples, fresh input and frozen no-helper value traces. | | Controlled legacy Slider (`src/base/cui_base.c`) | Actual idle capture-loss fixture leaves caller-owned dragging active. The declared cancellation contract restores the gesture-start value; disposition and callback ordering need an explicit reviewed fix. | Prove idle reset disposition and BEGIN/UPDATE/COMMIT/CANCEL callbacks, values and ordering; preserve no-helper behavior. | The typed Slider model already contains a snapshot-ready/pressed capture-loss cancellation path. This source observation does not prove nested lifetime reset coverage; retain it as a separate runtime acceptance case. Suppressing activation, consuming input and cancelling a proposed value remain separate operations. ## Additional retained-state counterexamples Six actual nested-owner diagnostics now produce **five failures and one pass**. Table applies stale resize (100 → 138, one width callback) and reorder ([1,2] → [2,1], one move callback); an idle reset leaves resizing active. ColorPicker applies a stale hue change and retains its drag flag on idle reset. Each test first establishes capture through a real DOWN event. The typed Slider capture-loss/fresh-gesture case passes using its existing reducer. See [the source audit](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/DIALOG_RETAINED_CONSUMER_AUDIT.md) and [the counterexample receipt](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/validation/dialog-retained-consumer-counterexamples.json). The [reviewed test-only reset plan](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/DIALOG_TABLE_COLOR_CANCEL_PROOF.md) clears only scoped pending press state, preserves changes already delivered, and emits no invented model/completion callback. Production transfer remains gated by corrected runtime and frozen legacy traces. ## Remaining audit These are inspection candidates, **not established defects or verified support**: - Table selection and other retained states beyond the confirmed resize/reorder cases. - Choice/menu/select popup pointer and keyboard reducers. - Picker, legacy numeric controls, text selection, chrome/window drag and surfaces. - Typed Slider models and other consumers that already check consumption: verify retained state also terminates correctly without replaying notifications. - Styled wrappers and independently owned nested scopes/portals. A file containing a consumption check does not establish that every mutation path honors it. Audit each reducer and meaningful callback/result path, then attach headless runtime evidence. Existing legacy entry points stay in regression tests. ## Custom reducers and completion gate Core cannot reset arbitrary application-owned state or undo earlier callbacks. Custom raw reducers need an explicit documented reset/query contract. Do not advertise automatic cancellation of all custom children from builtin tests. Before production transfer: measure the proposed storage on native and WASM, prove scope/ancestor and invalid-phase behavior, close applicable builtin gaps, retain exact target/receipt evidence, and verify uncalled-helper compatibility. Update this inventory as consumers are tested or additional paths are found. ## Current unpublished proof The copied marker/query and Scroll/Resizable candidates passed an initial 22 headless cases in `dialog-marker-first-runtime.log`: scrollbar mouse/idle/touch cancellation, Resizable stale size/completion suppression and fresh input, scope query and prior Dialog lifecycle/receipt/geometry checks. Production files remain unchanged. The final driver passes 26 checks, including Resizable idle/touch and a frozen 27-frame no-helper Scroll/Resizable trace (`dialog-marker-final-build-runtime.log`). The separate numeric trace passes, but five stale-key/idle counterexamples fail (`dialog-numeric-original-runtime.log`). Those policies and remaining consumer coverage still gate production transfer. This is not approval to publish the Core API or a claim of all-component cancellation support. ## Numeric and bare-scope candidate result The copied candidate passes 38 checks in `dialog-numeric-fallback-corrected-runtime.log` (0.24 seconds). These include the five formerly failing numeric cases, one synchronous controlled Slider CANCEL with the gesture-start value, fresh-input recovery and bare-scope Escape routing. The unrelated-input fixture uses supported Textbox accessibility FOCUS; the first run's unsupported ACTIVATE setup failure remains recorded. Existing Button ACTIVATE preservation is independently covered. Routed keys without current/prior semantics can use validated full-ID focus-scope ancestry. Where a scope ID also identifies a semantic owner, semantic ownership stays authoritative; contradictory aliases remain an explicit limitation. Capture, contact and activation ownership are unchanged. Production files remain unchanged, and remaining reducer coverage still gates transfer. ## Table/Color candidate checkpoint The copied test-only candidate passes **44 of 47 checks** (0.81 s), including the prior 38 and the five original retained-state regressions. Two touch-reorder checks and a frozen-trace bounds assertion still fail. Original-input controls and a trace target correction are prepared but unexecuted at this checkpoint; no claim that they are fixture-only failures is made. See the [partial receipt](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/validation/dialog-table-color-candidate-partial.json). Production Core/Base transfer remains gated. A later same-input control confirms that both the frozen original Table and the candidate fail initial touch reordering **before any lifetime reset**. This is an existing touch-drop defect, not evidence of a cancellation regression. The corrected trace passes its earlier bounds/model/callback comparisons but still fails a blocked-transition capture precondition. That setup remains under investigation; the assertion and original logs remain intact. --- ## Bounded current scrollbar track geometry V1 Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SCROLLBAR_TRACK_LAYOUT_V1.md # Bounded current scrollbar track geometry V1 Proposal only, based on `6c69bb1d` plus Dialog checkpoints `a90319fb`, `e0942271` and `a605a5ea`. No production, public header or vendor edits. Coordinate any implementation base with root and Stepper's current Core V2 work; this document does not authorize cherry-picking old Core implementation files. ## Decision and source seams Recommend staging real fixed no-flow **track and thumb nodes** before the existing second calculation, rather than introducing semantic-only geometry. Register a bar semantic with the SAME ID as its real track box, associated with one already registered Y clamp. Core owns current track/thumb allocation and range-derived semantic eligibility; Base continues input reduction; components own track/thumb paint and skin. No new calculation, observer, input dispatcher or callback pass. Actual Core paths: `src/core/cui_scroll_layout_internal.h` stages heights/offsets, resets scratch, calculates once more, validates all plans, then commits offsets and current viewport scroll semantics. `cui_core_prepaint_prepare` builds geometry from real Clay boxes and uses named semantic/layout matching for occlusion. End-frame tracking and semantic publication separately query real Clay bounds. A real correctly staged track therefore feeds all three existing consumers without three parallel override paths. `cui_bounds` during submission still means previous semantic bounds; no new current query promise is attached to it. Semantic-only alternative: a record would map bar semantic to owner geometry, but prepaint occlusion currently requires the semantic ID's own Clay layout element; final semantic bounds/clipping and parent/order also use the layout node. Updating only semantic.bounds is insufficient. A sidecar would need coordinated overrides in prepaint, final bounds, previous_hits, parent/layer/order, tracking and shadow ownership. This is wider and risks presenting a fake bar layout/paint owner. Reject it for V1. No general semantic rectangle setter is proposed. Fixed-decoration alternative avoids those overrides. Existing admission already permits fixed-width/fixed-height parent-attached, inherited-clip zero-flow children. The missing capability is narrowly staging submitted track/thumb fixed geometry from a registered viewport's allocated dimensions before final positioning. The box stays fixed during both calculations; it is never an unadmitted GROW floating child or a flow child that corrupts intrinsic content height. ## Exact API and shared geometry primitive ```c #define CUI_SCROLLBAR_TRACK_LAYOUT_VERSION_1 1u #define CUI_SCROLLBAR_TRACK_LAYOUT_V1_BYTES 48u #define CUI_SCROLLBAR_TRACK_VISIBLE 1u #define CUI_SCROLLBAR_TRACK_INTERACTIVE 2u typedef struct { uint32_t struct_size, version, flags, reserved; cui_id viewport, bar, thumb; float thickness, minimum_thumb; } cui_scrollbar_track_layout_v1; bool cui_layout_scrollbar_track_v1(cui_context *, const cui_scrollbar_track_layout_v1 *); /* Pure Core geometry, callable outside frames; legacy normalization preserved. */ cui_rect cui_scrollbar_thumb_geometry(cui_rect track, float scroll, float viewport, float content, bool vertical, float minimum); ``` Exact record48, IDs16/24/32, floats40/44; unknown flags/reserved/version fail. INTERACTIVE requires VISIBLE; permitted states are0, VISIBLE, or VISIBLE|INTERACTIVE. These are authoritative authored paint/input policies, not inferred from the placeholder semantic's prior-range disabled field. Both floats finite positive. Core primitive adopts the existing complete pure body of Base cui_scrollbar_thumb_ex, including finite/positive fallback12, viewport/content fallback, clamp, degenerate-length zero rectangle and operation order. Base keeps its existing symbols/signatures; cui_scrollbar_thumb_ex becomes a delegating wrapper, and cui_scrollbar_thumb still passes12. Move the formula, do not copy it in two layers. Core has no Base dependency; both Core layout and existing Base drag math call the one Core primitive. Horizontal legacy calls stay supported by that pure primitive although the new layout record is Y-only. Strict layout descriptor floats are validated separately; legacy normalization behavior is not changed to satisfy the new descriptor's stricter admission. ## Registration, failure and compatibility Ordinary frame submission only: after both boxes and the viewport/bar semantics are submitted and closed, AFTER the associated Y clamp registration. Record is copied immediately, no borrowed new pointer. Enclosing inert/layout-only may legitimately suppress current semantic submission under existing Core behavior; real boxes and correct topology remain mandatory, but absent semantics there are normal. Active ancestry requires the exact owner/bar semantics. Never synthesize input eligibility for inert or measurement-only trees. Existing Core80/32 record ABI and old public structs remain unchanged. Full/folded nonzero ID checks apply at registration AND end_frame, including cross-record and late duplicates. One bar per viewport, one record per bar;64 records maximum, no dedup/replacement. Wrong role, missing node/semantic/clamp, portal/wrong-parent topology or alias is an error. Zero-range/hidden is normal final omission, never missing-node fallback. Each bar semantic controls/parent=viewport, orientation=VERTICAL and role=SCROLLBAR. Passive thumb has no semantic of its own. Core accepts explicit IDs; components use existing public cui_scrollbar_id, no copied derivation. Allocation/capacity/topology/geometry failure opts an ordinary frame into landed Core failure semantics BEFORE scalar commit: non-OK end_frame even if caller clears its first error, empty draw, no valid prepaint/geometry/snapshot promise; no partial model commit. Wrong-phase calls retain existing lifecycle behavior. Shared failure sentinel stays immutable. Next clear/begin/rebuild recovers, with no input or observer rollback. Later downstream prepaint failure does not roll back an already successful scalar commit. References live through end_frame under existing Core lifetimes; no retained descriptor or global registration. Zero opt-in frames and legacy bars without this record keep existing behavior. ## Fixed widths and authored topology Width cannot be min(thickness,W/2,H/2) staged after first calculation, because H may depend on allocated Y and width fingerprints include all decorations. Record thickness is the already-resolved explicit fixed width of BOTH track and thumb, equal at registration and unchanged across calculations. It must fit the current independently constrained viewport width. Components may resolve thickness from the explicit horizontal constraint before composition; no allocated-height width cap. Extremely short viewports can have a track narrower or wider than their height; thumb length clamps to track height. This is an explicit new-route overlay policy, not a claim to preserve old height-based bar-thickness capping. Old bars without a record keep their current policy. bar has one direct zero-flow thumb child, no flow children or other descendants. Both boxes are FIXED in both axes, use fixed-positive1 height placeholders, inherit parent clips/layer, have no padding/aspect/percentage/portals or application prepaint callbacks. bar attaches to viewport; thumb attaches to bar. Existing public absolute-box authoring supplies the actual IDs and topology. thumb has no semantic/input identity of its own: the full track is the existing Base SCROLLBAR control. Core validates every full/folded ID and all cross-record/structural aliases; real nodes remain actual paint owners. An authored empty/disabled track still supplies both nodes/semantic so omission can be resolved from CURRENT range. Box background/border/radius and existing named box shadow APIs can paint/style each real track/thumb node. They are actual Clay fixed boxes, so ordinary culling, geometry, shadow bounds, own clipping and inherited opacity all consume the final actual dimensions. No viewport-owned paint is advertised as thumb-owned shadow. There is no production bar prepaint hook required for ordinary skins. Style is resolved before authoring these two boxes, including fade on the common track ancestor exactly once; thumb inherits it. Custom prepaint callbacks are excluded from this narrow V1 topology rather than silently invoking them with synthetic geometry or adding another observer. Existing box shadow capacity/error rules apply; they are not a second shadow ownership architecture. ## Staging and omission After all body/standalone heights and offsets are staged, take planned viewport W,H, range M and clamped offset Y. Fixed bar width B=record.thickness. For VISIBLE and M>0 and H>0, stage bar height H and attachment offset W-B,0. Compute a local thumb rectangle through the SAME Core primitive with track=(0,0,B,H), scroll=Y, viewport=H, content=H+M and minimum=minimum_thumb. Stage thumb height and attachment Y from that rectangle, fixed width B and X0. Validate finite H+M/intermediates. No width changes, new flow child, measurement callback or additional calculation. For hidden/zero-range omit both heights (zero), keeping widths unchanged. Mark bar semantic for omission before prepaint hit testing and final publication. Additionally suppress effective paint opacity on BOTH real decoration nodes for this frame, including their named shadows, so a shadow on a zero-size box cannot leave a phantom halo. This is opt-in range-derived paint eligibility, not mutation of the authored skin or persistent shadow resource. Next frame reauthors nodes and recomputes effective opacity normally. Inert preserves existing inert paint semantics (visible but noninteractive), layout-only suppresses all paint/input as usual; do not conflate inert with hidden. VISIBLE without INTERACTIVE preserves full track/thumb paint, shadows and a disabled SCROLLBAR semantic with actual bounds/range/value; it accepts no capture, focus, keyboard, pointer or touch drag. VISIBLE|INTERACTIVE permits the ordinary role behavior under existing modal, clip and enclosing inert/layout-only restrictions. flags0 hides paint and omits the semantic. Zero range/height omits both regardless of bits. Existing Core disabled-role filtering retires capture/focus through its normal publication rules; no blanket range-derived enabling may override authored noninteractive policy. Enclosing inert suppresses semantics/input but retains the same paint; layout-only suppresses both as it already does. Final actual bar/thumbnail rectangles must match the staged relation after the single second calculation. Expected clipping is the actual inherited viewport clip and ancestor clips, not a synthesized same-size viewport root. Compare nonzero scroll on owner and ancestors explicitly: owner scroll must not move its own bar; ancestor scrolling must move owner/bar together. If the pinned floating clip-childOffset behavior fails that relation, reject/prototype the narrow anchoring fix before approval. Do not compensate from old bounds or silently allow a third layout. All validation precedes all scalar model commits. Metadata updates use real nodes only: semantic value=Y, min0/maxM, controls/parent viewport, actual bar bounds for both current occlusion and completed input; thumb is passive paint. Parent/layer/order, tracking, painted bar culling and shadows remain ordinary Core paths. No per-consumer rectangle override is necessary. Projected records do not grant style access to nonexistent child parts elsewhere. Phase order is strict: ordinary input/composition once -> existing first layout -> validate every record and derive ALL planned body/clamp/track/thumb scalars -> reset existing render/wrap scratch as already audited -> existing second layout -> validate actual rectangles, topology, aliases, finite destinations and all ranges -> atomic active offset commit and current range/value metadata -> omit ineligible track semantics/effective paint -> ordinary prepaint conversion -> ordinary tracking/final semantic publication. No allocation, event consumption, application callback or model write occurs in the scalar-staging/validation steps. If final track geometry does not match, fail BEFORE any offset commit; don't use an equal width hash as a substitute for independent width admission. Current prepaint occlusion and next input must see the same eligible named track. ## Bounded storage and proof gate Private candidate per record: copied48 + staged bar rect16 + staged thumb rect16 + clamp_index4 + flags4 =88 bytes.64 entries5632; existing7216 + count/padding8 =>12856 candidate resource bytes, <=16KiB. Actual sizeof/offsets remain to measure. No new context field. Disclose +5640 lazy payload growth for layout users even without bars; no new resource allocation for zero opt-in legacy frames. Separate nullable extension allocation remains an alternative if root rejects this shared payload growth; it needs its own failure contract and cannot be added invisibly. Two Dialog owners use2 records,4 actual decoration nodes (existing max_elements), and one semantic per track. They need no extra prepaint payload or paint command reservation; ordinary background/border/shadow commands consume existing configured render capacities. Shadow layers still incur their normal bounded costs. The two-owner wheel/touch/new-route bypass contract is specified below. Existing Base overlay reducer uses previous completed track bounds, previous owner viewport/range and stable model, hence the same thumb formula used to paint that completed frame. Current staging does not replay those events or dispatch newly appeared controls. The placeholder semantic rule handles previous range0; Core final visibility/interactivity are explicit, and old helper loads/defaults remain unchanged. Required prototype adds actual box pixel/draw/shadow and current hit oracles to the earlier plan: track/thumb retained bounds, published bar bounds and next-frame pointer/touch targets agree after first-overflow/resize/shrink; actual viewport scroll childOffset does not displace its own bar; nested ancestor scrolling does; track/thumb independently painted/shadowed ownership matches the named node and clips/culling; zero/hidden leaves neither semantic nor halo; alpha under ancestor ×fade applied once. Verify the moved Core primitive against a frozen legacy Base oracle over degenerate/nonfinite/normal/both-axis cases and exact operation order, plus track page/drag and touch interactions on BOTH owners. No narrow wheel-only or decoration-only result is claimed as full visible control parity. ## Dialog input ownership and Base compatibility New Dialog composes each owner's cui_base_scrollable(hidden own bars) before its children, finish afterward, sharing one stable modelY via the local-state copies specified in a605. Inner changes consume whole scroll events; unchanged inner may defer to ancestor; outer finish handles only still-unconsumed newly targeted events once. Core touch pan produces precise scroll events through the same path; bar-role touch drag keeps its existing priority. Existing previous-frame modal, clip/parent/directional routing remains authoritative. No residual-delta replay. Call cui_base_scrollbar_overlay once per owner during ordinary input reduction, using that owner's last completed positive geometry and copied resolved skin. Its existing context-owned drag/grab resource handles capture, track click, keyboard and CANCEL. Its model update is copied back to the local wheel state before finish. This helper conditionally omits the semantic when the PREVIOUS range is0; therefore new composition privately ensures exactly one current bar semantic afterward (submit a disabled SCROLLBAR placeholder with controls/parent when absent, not a second reducer). Registered Core projection owns final range-derived omission, including first overflow. Core may clear a placeholder disabled field ONLY for explicit authored VISIBLE|INTERACTIVE with positive range and eligible ancestry. VISIBLE alone always publishes disabled=true. It never replays previous input on newly appeared controls. Components pass disabled=true to Base overlay reduction for authored noninteractive bars and preserve existing disabled skin/math/timing; hidden/zero-fade policy clears VISIBLE (and INTERACTIVE) without disabling the viewport wheel/touch owner. Core final disappearance withdraws old controls. Existing legacy Base bars do not read these new flags. New-route private surface reducer disables legacy reserved1/2/3 activation AND legacy Body6 wheel reduction; those are owned by the new action/scroll helpers. Old public surface update/begin executes its original statements/timing unchanged. Pending request_close, Escape/outside and observer/focus statements keep order. Do not execute old Body wheel then restore model: an observer could see it. This is a required explicit route selection, not approval to alter old behavior. ## Validation gate and remaining scope No runtime evidence accompanies this proposal. Prior e094 proves current public semantic-range timing and viewport-owned bar paint only. This actual fixed-node representation needs a TEST-ONLY proof before production approval. Frozen legacy thumb comparator must retain the old pre-move function body in the test oracle, compare exact float bits (with equivalent NaNs categorized explicitly), cover both axes, nonfinite/degenerate/default cases and bounded deterministic randomized inputs. Test ordinary Base wrappers as well as new Core primitive; no default or ABI drift is accepted merely because new Dialog geometry passes. Real queued wheel/touch/drag tests must cover BOTH owners: child consumes, edge defers once, direct Outer routing, hidden bars retain wheel/pan, primary track page click, thumb grab/move/outside release/CANCEL, right/middle ignore, keyboard Home/End/Page/arrow, resize/shrink while held, next snapshot has no stale bar, visible-disabled paint+semantic/no input, invalid INTERACTIVE-only flags, placeholder override only with explicit interactive policy, focus/capture retirement on omission/disable, owner removal/reuse, inert/measurement, record64/65 capacity, byte failure, malformed topology/folds/late duplicates and all-or-nothing model commit/recovery/two contexts. Layout/application/input runs once; resource/string/text scratch invariants remain checked through second calc. No bitmap/text raster or GPU claim follows from draw-command geometry tests. Full Base/Styled C composition stays gated until this architecture and its proof are reviewed. Root/native host, global Enter/source placement and all five typed foreign slot/action plans remain separately open. Foreign synchronous veto has its own lifetime/exception/reentrancy gate. Coordinate any source base with root and Stepper V2; do not edit frozen root sources or merge/push from this worker. ### First runtime admission counterexample The first test-only frame failed LAYOUT with public fixed-zero absolute track/thumb placeholders: Core maps fixed-zero to Clay PERCENT0, while csl_floating requires nonregistered floating descendants to be actual FIXED. Its ordinary-flow canonical zero exception does not extend that floating guard. The proposed representation therefore uses fixed-positive1 height placeholders, excluded from intrinsic flow; staging later writes actual current/zero heights as fixed values before second calculation. No production admission relaxation or stale geometry fallback is proposed. This correction still requires the revised runtime proof below. ### Publication eligibility review and exact input boundary INTERACTIVE does not override a submitted owner's or actual layout ancestor's `disabled` / `details.readonly`, the bar's authored readonly metadata, or inert / layout-only ancestry. The test adapter traverses bounded actual node parents and matches their current submitted semantics; eligible flag3 may clear only the bar's range-placeholder disabled state. Visible disabled owners retain ordinary track/thumb paint and disabled bar semantics. Fixed sizing admission is actual Clay FIXED with positive finite height at registration/trial; only the already staged fixed height may be zero. AUTO/PERCENT/GROW are rejected explicitly. There is no new generic disabled-scope dispatcher: a component must pass its current effective disabled/readonly policy to Base input reducers BEFORE they run. The public Base helpers do not discover arbitrary current semantic ancestors (the public parent query is completed-frame only). Publication can withdraw a future hit/capture snapshot; it cannot undo model changes already delivered by a caller that ran a reducer before learning/changing an ancestor policy. Same-frame late policy changes have the existing no-rollback boundary. If a product requires that stronger guarantee for arbitrary external semantic ancestry, this proposal does not silently provide it: use existing inert/layout-only scope policy before composition, or bring the stronger ownership rule for a separate review. The descriptor does not introduce a logical-parent graph traversal or reinterpret arbitrary unrelated semantic parent links as layout ownership. Tests isolate readonly owner with disabled=false and disabled actual ancestor with owner disabled=false, so publication tests cannot pass solely through an already-disabled owner. Separate queued Base tests supply current owner disabled, readonly or ancestor-disabled policy before reduction and assert unchanged model, retired focus/capture, retained disabled paint/semantics. Existing Base disabled math, normal wheel consumption and legacy observer timing remain unchanged. ## Test-only fixed-node proof on Core V2 Prototype source base: exact preserved Stepper `3e18bbba` (includes numeric Core `e5b64e4e`); separate branch `test/dialog-track-layout`. Prior signed contracts and the two-viewport proof stay preserved on `design/dialog-slots-v1`. No public production header, Core/Base implementation or vendor file is modified here. `embed_scrollbar_track_probe.py` creates a build-directory Core copy with four exact substitutions: bounded writable plan extension and stage/validate/publish seams. Offline tests verify every other source byte unchanged and missing/duplicate seams preserve prior output. The adapter is `scrollbar_track_probe.c`; executable fixture is `test_scrollbar_track_geometry.c`. Measured LP64 resource12856, record48, entry88, matching the budget; existing production resource remains7216. Actual fixed track/thumb bounds match their post-end tracked bounds and the bar's final semantic bounds/range/value. Core prepaint pointer_hit agrees with the next completed input target inside an ancestor clip and excludes the same bar outside it. Software RGBA tests (no fonts) produce alpha50 for one original200×ancestor.5×fade.5 layer, alpha90 for overlapping track/thumb layers, and no pixels/halo beyond ancestor clip, including named track/thumb shadows. Fully clipped track has no visible pixels. Shadow caster rectangles match the actual named paint boxes. Hidden/zero nodes may produce degenerate alpha0 commands; omission means no semantic or visible paint, not a promise of zero command records. Queued real input passes on BOTH owners: wheel, touch pan, thumb grab/move/release and resize while held. Nested child consumes48 without moving parent, then a current child edge defers once to parent finish (child240, parent48); nested touch pan changes only child. Visible-disabled paint/semantic remain while pointer/focus/ capture/model changes are refused; hidden bars preserve wheel. Isolated owner readonly with disabled=false and disabled actual ancestor with ownerdisabled=false publish a disabled bar and reject next pointer target. Separate Base-policy cases prove queued input refusal when caller supplies those current disabled policies. Inert geometry still paints while a model seed10000 remains unchanged. New-route input helpers are skipped when public frame_sequence is0; no inert setter call. All64 records commit current clamps; a65th clamp, one-byte-short resource budget, invalid flags and aliased bar/thumb fail atomically, empty draw and preserve model, including an attempted error clear within the failed frame; next plain frame recovers. Fixed-zero/PERCENT0 and GROW placeholders are rejected.40,000 exact comparisons (both axes, degenerate/nonfinite/default and deterministic random cases) match the prototype moved formula against the unchanged real Base helper. This is not a claim that production Core already exports the new pure helper or that an actual Base forwarding change has been validated. Focused warnings-as-errors Release build plus2/2 private-Xvfb CTests passed: ```sh nice -n 19 taskset -c 0 cmake --build BUILD --target test_scrollbar_track_geometry --parallel 1 nice -n 19 taskset -c 0 python scripts/test_local.py --build-dir BUILD \ -R '^(scrollbar_track_geometry_prototype|scrollbar_track_probe_generator)$' -V ``` Runtime evidence supports further review of this narrow representation; it is not production approval or full Dialog parity. Still unproved in this fixture: all late/folded alias variants, layout-only model/lifecycle cases, interactive track page-click/keyboard/right-button/CANCEL permutations and arbitrary portal/ modal/layer interactions. Those remain production test requirements above. Existing upstream Core proof covers related cases but is not substituted as new-record proof. Windows/WASM/GPU and text raster are not run or claimed. Disabled/interactivity policy blocks bar input; it does not mark an otherwise active viewport's Core clamp inert. Ordinary current-range layout clamping on content shrink can still change that viewport's offset. The disabled-input tests use a model already valid in the established completed geometry; they do not assert that a disabled bar preserves an out-of-range offset across resize. Final checkpoint checks: both focused CTests2/2 passed after final configure; Ninja dry-run reported no work for the exact target. Offline installed-skill suite18/18, canonical skill freshness, changed C/header clang-format23.1.2 and staged diff checks passed. The skill suite shared CPU0 with root's suite and finished in128.258s; future heavy skill suites must coordinate like compile slots. No full library rebuild or second build directory was used. --- ## Scroll observer checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SCROLL_EVENTS_SLICE.md # Scroll observer checkpoint Original design checkpoint `6251b9d6`; the Base and Styled pairs are now implemented, as recorded at the end. Virtual/message event proposals below remain unimplemented. This is a bounded follow-up to the [remaining audit](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_REMAINING.md) and [shared contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_CONTRACT.md), not a new manifest family or a claim of universal scroll events. Command Styled and TitleBar are separate work. ## Existing seams and meanings | API/source | Actual behavior and boundary | | --- | --- | | [`cui_base_scrollable`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_scroll.c) | Captures entry offsets, clamps nonfinite/out-of-range/disabled-axis values, reduces ordered targeted wheel events, registers owner, reduces horizontal then vertical scrollbar, updates semantic details. Bool is entry-versus-final offset inequality, including normalization; it is not submission success or input count. Hidden bars clear drag state but leave wheel support. Disabled suppresses wheel/scrollbar interaction but does not bypass normalization. | | `cui_base_scrollable_finish` in the same source | Resolves geometry, reduces still-unconsumed targeted wheel events now deferred by children and updates owner semantic details. No repeated owner registration or scrollbar pointer/key reduction. Bool compares offsets immediately before/after this finish only; it omits earlier changes. A consumed event does not replay on another finish. | | [`cui_scrollable_begin`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_scroll.c) | Returns false on null context/theme/state or zero ID, otherwise calls Base once and opens root/body/viewport/content boxes. True means caller must pair end, not that offset changed or geometry succeeded. Theme resolution and optional previous-frame content measurement precede Base. First auto-measured range may be zero. | | `cui_scrollable_end` | Const-state paint/box closure; no deferred wheel reduction. Cannot truthfully promise a final offset that includes children. | | `cui_scrollable_end_ex` | Mutable preferred end: re-resolves measured geometry, calls finish, updates current clipped viewport translation, then legacy end paints bars/closes boxes. Returns void. It must pair a successful begin with matching owner/state/options. | | Scrollbar overlay split/combined APIs | Context-owned bounded drag state, caller offsets, Base reduction followed by paint; distinct owner geometry and validation. These are not automatically covered by a Scrollable owner facade. | The [public scroll API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_scroll.h) retains style pointers only for the documented call/frame, not as listener registrations. There are no legacy Scrollable change callbacks to chain. Rendering callbacks belong to composed children. Do not retrofit handlers into `cui_scroll_state` or options layouts. Wheel reduction consumes a changed offset, or an explicit horizontal trap; at an edge it can defer routing to an ancestor. Precise deltas use logical units; nonprecise deltas use wheel step. Axis/gesture locking are existing routing policy (gesture lock is disabled on WASM), not new event phases. Scrollbar Home/End/page/ arrow keys act on the scrollbar; basic Scrollable is not the virtual owner's focusable-keyboard API. Do not add that keyboard behavior through observation. [`test_scroll.c`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_scroll.c) already contains nested deferred routing, no replay, consumed-wheel and current-frame translation assertions. These are source/test evidence, not tests rerun for this documentation checkpoint. ## Recommended first slice: one paired final-offset notification Add a new `cui_scroll_events.h`, narrow Base/Styled common seams and a dedicated unit test only after review. Keep every legacy entrypoint and layout unchanged. Proposed declarations (names/layout subject to review): ```c typedef struct { float x, y; } cui_scroll_offset; typedef struct { cui_component_event_metadata event; /* CHANGE, UNKNOWN source */ cui_scroll_offset previous, value; bool has_previous; /* false when entry contained a nonfinite coordinate */ } cui_scroll_change; typedef void (*cui_scroll_change_fn)(void *, const cui_scroll_change *); typedef struct { cui_scroll_change_fn on_change; void *user; } cui_scroll_handler; typedef struct { bool valid, changed, count_overflow; size_t change_count; /* actual observer calls: zero or one */ } cui_scroll_event_result; /* Caller-owned single-use pairing token; private implementation fields. * No handler retained in token/context. Identity, frame and entry offsets only. */ typedef struct { cui_context *private_context; cui_scroll_state *private_state; cui_id private_owner; uint64_t private_frame; cui_scroll_offset private_entry; bool private_active, private_styled; } cui_scroll_event_scope; /* Same bool meaning as cui_base_scrollable; scope records admission separately. */ bool cui_base_scrollable_events(cui_context *, cui_id, cui_scroll_state *, cui_scroll_options, cui_scroll_event_scope *); cui_scroll_event_result cui_base_scrollable_finish_events( cui_context *, cui_id, cui_scroll_state *, cui_scroll_options, cui_scroll_event_scope *, cui_scroll_handler); /* Same begin/pair contract as legacy Styled begin. */ bool cui_scrollable_begin_events(cui_context *, cui_id, const cui_theme *, cui_scroll_state *, cui_scroll_options, cui_scroll_event_scope *); cui_scroll_event_result cui_scrollable_end_events(cui_context *, cui_id, const cui_theme *, cui_scroll_state *, cui_scroll_options, cui_scroll_event_scope *, cui_scroll_handler); ``` The complete token is caller-stack allocatable and initialized to zero before first use. Its private-prefixed fields must not be read or modified by callers. The proposed frame field uses the actual public frame-sequence width (uint64_t). It contains borrowed context/state identities, no retained handler or callback user pointer, and must not be copied while active. Independent nested owners use distinct tokens. No global listener registry, heap allocation or hidden event log. Begin must reject an already-active token rather than overwrite its live pair. Capture entry offsets before the one existing reducer. Base finish invokes the legacy finish once, freezes final offsets/metadata, consumes the token, then invokes one optional observer. Styled end does the existing finish/translation/ paint/closure once, consumes token, then invokes observer after owner closure. Do not call the public Base observer from Styled end and then notify again. Handler/user borrowing lasts through end only. This explicit final-after-paint seam keeps child/paint timing intact; it is not a generic frame-end dispatch. Token checks require zero initialization before first use, correct context, owner, state address and Base/Styled layer, and single-use pairing. These identity mismatches and an already-consumed token reject before reducer/box/observer effects. An admitted token records `cui_frame_sequence(ui)`, which is zero in inert or layout-only scopes. **The current public API cannot prove same-frame identity for frame-zero work.** Do not add a Core counter or claim a runtime guarantee there. When both recorded and current frame sequences are nonzero, require equality; a zero/nonzero transition is also rejected as a changed submission scope. If both are zero, same-frame/same-scope pairing remains a caller obligation: carrying such a token across frames is unsupported misuse that cannot be detected reliably. No diagnostic promise covers that case. The same passive ancestry must surround the pair; the facade must not temporarily escape it to obtain evidence. Base begin returns the exact legacy reducer bool: false may mean valid no-change. Admission is separately recorded in the token, so callers must not use that bool to decide whether Base finish is allowed. Base null arguments/zero ID reject and leave no admitted pair; a later finish returns a zero invalid result. For Styled begin, preserve the legacy argument preflight and boolean composition contract: false means no pair was opened and end must not be called; true admits the token and requires end even when offsets did not change. An already-active token is rejected before calling legacy begin. A matching finish result is `valid=true` even when `changed=false`; invalid/mismatched finish is `valid=false` and has zero callback count. Layout/capacity errors after admitted Styled begin still require balanced box closure; `valid` is adapter admission, not transactional rendering success. Existing Core diagnostics are not erased. Passive Styled begin/end still execute the existing normalization, layout and paint policy exactly once; frame-zero is not an argument failure or permission to omit end. Base also preserves its existing maintenance behavior. A final result can report `changed=true` with `change_count=0` in these scopes, because no observer is dispatched without nonzero frame evidence. Admission and change are therefore independent of callback eligibility. The caller must use the same effective dimensions/style/options across its pair, including disabled state, enabled axes, geometry, auto-measure and style lifetime. Identity checks do not prove descriptor equality: mismatched options are unsupported caller misuse, not silently reconciled. Preserve Styled's existing remeasurement at end; the same options do not promise identical measured geometry. No hidden option snapshot or retained stack-style pointer. Do not hide a second finish in a passive getter. `changed` means the finite final offset differs from a finite entry, or a nonfinite entry was repaired to a finite result. `has_previous=false` leaves `previous` zeroed rather than presenting NaN as a usable coordinate. A malformed final nonfinite state is an adapter failure, not a fabricated CHANGE. Count is actual callbacks, missing handler zero; no callbacks for net-zero changes or pure drag-state/opacity changes. One aggregate may represent several wheel/key/ drag operations, including a return to entry that is intentionally silent. **Normalization decision for review:** recommend including observed entry-to-final clamping/axis-disable/range-shrink repair in this aggregate, because it is an actual applied offset change and matches Base's old bool comparison. It is explicitly not a user-input notification. Disabled ordinary submission may normalize caller state and yield a final-offset CHANGE with genuine nonzero frame and UNKNOWN source. Inert/layout-only frame-zero work may normalize state and report maintenance `changed`, but dispatches no observer. Neither implies a user activation/request. Preserve legacy reducer behavior; do not gate away its normalization to satisfy a blanket disabled-event slogan. If user-only events are required, that is a separate instrumented reducer design, not an inference from this aggregate. External assignment before begin is the baseline and silent; arbitrary external scroll-state mutation between begin/end is unsupported. Metadata target is the public scroll owner, kind CHANGE, source UNKNOWN. Dispatch only when the pair has matching genuine nonzero frame evidence; retain that frame, omit event index/HAS_ACTIVATION. Frame-zero pairs emit no callback; several inputs, range reconciliation or children can contribute. Do not select a last wheel event and pretend it caused the final offset. Payload is pointer-free and copyable; callback cannot mutate active scroll state/options/input, recursively compose, destroy context or free active owner resources. Defer teardown until the outer call/frame obligations finish. This is notification, never controlled veto, scroll acceptance, gesture BEGIN/COMMIT/CANCEL or an animation-complete signal. ## VirtualScroll/VirtualList: preserve result-only window state The [Base virtual adapter](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_virtual_scroll.c) resolves finite model extents, calls Base Scrollable, then processes focusable-owner main-axis keys, updates semantics/last viewport and computes its typed view. Its `scroll_changed` includes initial normalization and final Base/key offset changes. It does not execute child render callbacks or finish after them. The [Styled adapter](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_virtual.c) may first invoke intrinsic measurement, runs Base, then renders visible/overscan items from that computed view. After callbacks it calls scroll finish, adjusts viewport translation, marks `scroll_changed`, and sets `window_pending` only if deferred main-axis scrolling changed the rendered window's offset. It invalidates for a subsequent frame. The returned `view` remains the one used for row callbacks, not a recomputed claim that newly visible rows were rendered. Cross-axis finish can change offsets without main-axis `window_pending`. [Existing deferred-window assertions](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_virtual_styled.c) prove pending on the first call and no pending on the next stable call. Recommend **no window-completion observer**. `window_pending=false` means no new pending deferred change in this call; it does not prove rendering/GPU presentation, async data arrival or completion of a previously retained request. There is no retained request generation to complete. A callback would duplicate a useful result and encourage side effects during rendering. Applications can inspect results and invalidate as already implemented. Never rerender the new window in the same call or fire a callback for each row as a proxy for completion. A later virtual final-offset facade, if requested, can wrap the entire existing Base or Styled call with one entry/final comparison and preserve the original `cui_virtual_widget_result` separately. It must not reuse the internal Base event pair in a way that misses owner keys or double-delivers after finish. Measurement and row callback users/models are borrowed through their existing composition boundary; keys/heights must remain unchanged during row callbacks. No new retained subscription or item selection ownership is appropriate. ## MessageScroller is a distinct double-precision model [Public contracts](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_message.h), [Base reducer](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_message.c), [Styled composition](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_message.c), and [tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_message.c) establish opaque caller-owned bookkeeping, explicit append/prepend/splice/measure/navigation operations, double offsets and stable row tracking through `cui_end_frame`. State/collection mutation during row rendering is prohibited until end_frame, stronger than callback-only borrowing. Base first applies previous rendered-row bounds as measurements, performs layout (which can anchor/follow/clamp offsets), then captures its local `old` scroll. Wheel/owner keyboard/scrollbar updates and jump action follow. Its `changed` also includes measurement and jump/fade opacity changes; `jumped` is an action result. Neither is equivalent to entry-versus-final scroll change. Styled width changes can remeasure before Base; rows render after Base, and tracked bounds become measurement input on a later call. There is no Styled Scrollable finish call here and no virtual `window_pending` contract to forward. Do not adapt MessageScroller by float-casting `view.scroll`, treating `changed` as an offset event, or retaining row callbacks until a fictional completion. Keep its existing typed result for now. If demanded later, propose a separate double `previous/value` observation around the whole call, with pre-layout entry access inside the model and exact normalization/anchor/tail semantics; use distinct payload names or double offsets rather than weakening this model's precision. Append/splice and measure operations are not message-received/read notifications. ## Verification and alternatives First implementation ownership should be new events header, narrow Base/Styled scroll files, focused test and guide only; root owns build/export/binding wiring. Before implementation review the proposed complete token and normalization policy. Required headless assertions: - Exact legacy state, consumption, semantics, layout/paint and bool meanings for old/new paths; no-op, repeated input and net-zero aggregate; handler absent. - Child-deferred nested wheel delivery at finish, correct current translation, one observer after child/paint closure, no replay and no duplicate dispatch. - Horizontal/vertical/two-axis ranges, precise/nonprecise wheel, edge trapping, axis locking, scrollbar pointer drag/page/key and hidden/auto-hidden bars. - Range shrink, disabled-axis/disabled-owner, nonfinite entry repair, prior-frame auto-measure normalization; distinguish these from user input explicitly. - Inert/layout-only normalization/layout preserved with frame-zero maintenance results and no callbacks; omitted owner has no callback. Token identity/layer/ reuse errors and differing nonzero frames reject atomically. A frame-zero cross-frame test cannot assert a diagnostic that the API cannot establish; document that misuse and test suppression instead. - Base false/no-change still admits finish; Base invalid begin does not. Styled false begin requires no end; successful no-change/passive begin requires end. Check `valid`, `changed` and callback count independently, including normalized disabled ordinary work versus frame-zero maintenance. - Nested tokens, frozen copied payload after context destruction, callback timing and unsupported mutation documented; strict C11/C++ header construction. - Preserve virtual deferred-window/result tests and MessageScroller double/tail/ measurement regressions without adding their production facades in this slice. An alternative first API could take a whole-call content callback instead of a public begin/end token. It would execute begin, invoke borrowed content, then mutable end and notify in one stack frame, avoiding unprovable cross-frame token identity. Costs: a new callback composition convention, user lifetime through the whole call, inability to interleave arbitrary caller begin/end control flow, and an additional failure/early-return contract for content. It still needs passive callback suppression and normalization rules; it does not create input evidence. Recommend the compatible paired form with the explicitly limited checks above, not a hidden Core architecture change. A whole-call convenience wrapper can be reviewed independently if applications prefer that tradeoff. Callbacks at begin miss deferred work; callbacks at both phases double-deliver; per-input notifications need internal mutation instrumentation and different semantics. A context-retained listener unnecessarily extends userdata lifetime. Frame-end hooks retime side effects. Recomputing virtual rows in finish changes render callbacks and layout. None is part of the recommended bounded slice. Run warnings-enabled isolated tests through `python scripts/test_local.py --build-dir ` (private Xvfb), never a desktop session. Browser tests remain headless. No runtime tests/builds were run for this documentation-only proposal. Bindings retain existing notification allowlists; no shared queue producer, synchronous foreign veto or foreign scroll callback is proposed here. ## Implemented Base slice The first implementation exposes only the Base pair and shared types described in [SCROLL_EVENTS](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SCROLL_EVENTS.md). The complete Base-only scope has no Styled layer field because there is no Styled facade yet. Finish consumes the token before observer dispatch; typed count is bounded to one and overflow remains false. Frame-zero maintenance and normalization policy follow the approved refinement. The focused fixture plus legacy scroll/virtual/message and strict C++ header checks verify this slice independently. Styled declarations above remain proposals, not public symbols. No virtual/window/MessageScroller event implementation is included. ## Implemented Styled slice `cui_scrollable_begin_events` / `cui_scrollable_end_events` now use the same aggregate policy after exactly one legacy mutable end/translation/paint/closure. The unreleased token appends `private_styled`, checked by both finalizers before any work; consumers must rebuild. Each layer freezes final payload and consumes its token without calling the other layer's observer/finalizer. Callback borrowing is through the matching end only. There is still no virtual-window completion or MessageScroller event facade. See the guide for begin admission versus change and frame-zero limitations. Native strict Release and ASan/UBSan bounded regressions include old/new Styled paint/geometry and layer rejection tests. --- ## SDL3 analytic mesh: current adapter contract Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SDL3_MESH.md # SDL3 analytic mesh: current adapter contract Current implemented adapter slice, based on signed extraction `d4ca8c15` and reviewed design `9e7ce80f`. No opaque-only/uniform-only restriction applies. The validation section distinguishes actual software-SDL proof from remaining driver/integration work. ## Existing behavior and source authority Core (`include/cui/cui.h`, mesh declarations; `src/core/cui.c`, `cui_mesh_valid`) provides borrowed triangle vertices, finite XY/ST, positive scalar placement, linear premultiplied color and alpha in [0,1]. Degenerate triangles are empty. Borrowed vertices live through rendering; no renderer may retain a pointer as cross-frame content identity. Core validity is separate from adapter capacity. `backends/software/cui_mesh.h` now owns private CPU traversal/color conversion; software retains its original ordered RGBA8 destination blending. Coverage uses double XY, normalized winding, pixel-center top-left edges, interpolated ST and `S*S-T` with screen-space derivatives, the existing 0.001 solid-S threshold and explicit zero-gradient outcomes. Color unpremultiplies linear RGB, clamps SDR, encodes sRGB and rounds; coverage scales alpha. SDL_RenderGeometry alone cannot evaluate that analytic fragment coverage. Before this slice SDL had no mesh switch case and rejected it after clear. The new `cui_sdl3_render_capture` path prepares mesh resources before clear and advertises its implemented mesh capability. Existing shadow preparation owns copied commands/pixels and pins resources before clear, but its uniform-scale condition is a shadow limitation, not a mesh requirement. ## Actual host surface and target contract `include/cui/cui_sdl3.h` exposes an opaque backend, create/destroy, size, render, render_capture and BMP capture. All operations run on the main thread. There is no borrowed renderer constructor, raw SDL renderer getter or public target, viewport, clip, scale or presentation setter. `cui_sdl3_create` creates an owned resizable high-pixel-density window and default SDL renderer; it selects standard SDL_BLENDMODE_BLEND. `cui_sdl3_size` queries logical window size and selects SDL_LOGICAL_PRESENTATION_STRETCH at that size. No production path sets a texture render target. Thus the supported public path is the owned window target, whose physical resolution/presentation can change on resize/display migration; it is not a user-configurable offscreen-renderer API. Do not add such an API here. Mesh supports the same host target/compositing behavior as existing images and shapes, including transparent clear values. Use straight sRGB texture RGB and coverage alpha with SDL_BLENDMODE_BLEND. Do not require clear alpha 255. SDL's encoded target storage/compositing can differ from software's straight-RGBA8 storage on transparent destinations: compare visible composites or an independent SDL blend reference, not an invalid raw-storage equality assertion. Preserve alpha and command/triangle order; do not normalize away a genuine blend error. Linear mesh color conversion remains the existing SDR conversion, not new HDR or linear-light target blending support. For robustness and tests, a private fixture can configure viewport/presentation/ scale on the owned renderer. Do not reject positive nonuniform mappings: stretch and scale are axis-specific. Respect existing render_density admission (finite, positive effective axis scales <=16), target/resource size bounds and real query failures. Texture-target injection may test the preparation mechanism privately; it does not create a public offscreen support promise. No new target-kind rejection should be introduced without a concrete unsupported operation. ## Coordinate mapping and restoration The cached archive `/tmp/cui-deps-SDL.tar.gz` names pinned SDL revision `7f3ae3d57459e59943a4ecfefc8f6277ec6bf540`. Its `src/render/SDL_render.c` functions `UpdatePixelViewport`, `UpdatePixelClipRect` and `UpdateLogicalPresentation` establish the mapping, rather than the shadow approximation: - Effective axis scales are SDL render scale times presentation rectangle size divided by logical size (or render scale alone when presentation is disabled). - Physical viewport origin is **floor(viewport origin * effective scale + logical presentation offset)** independently on X/Y; explicit viewport extents use ceil(extent * effective scale). Default viewport uses the active pixel extent. - SDL clip is relative to that viewport; its physical origin uses floor(clip origin * scale), and its extent uses ceil(clip extent * scale), not a substituted ceil(right)-floor(left) rule. Preserve the current adapter's logical clip-stack rounding before applying this mapping. Snapshot presentation dimensions/mode/rectangle, axis scales, viewport and its explicit-set flag, active target and physical target extent. Query the window's true output size for the public window target; SDL_GetCurrentRenderOutputSize is presentation-adjusted and alone is not the full physical target extent. Bake device clipping against target/viewport and the current CUI clip stack. The adapter currently clears incoming SDL clip state at frame start; preserve that existing contract, not a newly invented external-clip intersection. Project XY into physical coordinates in double precision **before** calculating S/T derivatives. Keep ST unchanged. The private device-triangle entry point provides that projection seam; keep the existing software scalar path/arithmetic unchanged. Do not round transformed mesh vertices through an intermediate float payload. Anisotropic scale changes both derivatives and coverage; scaling a uniform-resolution coverage bitmap is insufficient. Draw prepared rasters in integer physical coordinates with presentation disabled, scale one, viewport/clip reset after clipping is baked. Restore presentation, scale, viewport-set state and the command-stream clip after each mesh draw so following commands observe their original state. Restore every property even if another restoration fails. Do not change target ownership or leave a different active target. Query/set failures return false. Verify the pinned mapping against actual SDL readback, including fractional presentation offsets, before claiming it implemented; source arithmetic is evidence for a testable design, not proof of every renderer driver's rasterization. ## Bounded preparation and failure boundary Prepare one transparent raster per visible triangle and submit in original order; flattening an overlapping command can change intermediate quantization. Initially no cross-frame mesh cache: copied RGBA and owned textures remove borrowed-payload lifetime hazards. Implemented fixed limits: 256 triangles/frame, 16384 pixels/axis, 8,388,608 total clipped raster texels (32 MiB uploaded RGBA payload). Direct read-only audit of `src/components/cui_popover_paint.h` at integration commit `b0101a389d7475b1f081db755be9ccd890f5f873` confirms fill[15] plus outline[60] vertices: at most 25 triangles/arrow. Ten worst-case arrow payloads fit (250 triangles), not eleven. This is a bounded admission choice, not an optimal budget or unlimited-popup claim; other producers share the same frame budget. Check counts, coordinates and byte arithmetic before allocation/casts. Degenerate or fully clipped triangles need no texture. CPU scratch is reused one triangle at a time; SDL surface wrappers borrow it only until synchronous texture creation completes. Free wrappers before scratch reuse. Retain textures through draw/present completion and release previous frame resources before preparing another. Application-owned budgets exclude SDL/driver internal staging; no hard-real-time claim. Before clear, validate the entire mesh-bearing list's payloads, supported command kinds/bounds and balanced clip stack, snapshot mapping, enforce budgets and create/ configure all mesh resources. Prepare images/shadows in such frames regardless of shadow presence; frame-pin them against eviction during preparation. An invalid last mesh or failed last mesh upload must not clear earlier contents. Failure cleans all partial mesh resources; next valid frame retries. Do not claim whole frame transactionality: late SDL draw failures or unprepared glyph allocation can still fail after clear. Return false without presenting on such failure, restore state, clean resources and permit recovery. Extending resource preflight to all glyphs requires a separately reviewed phase. ## Implementation gates and meaningful proof 1. Completed extraction: frozen independent pre-change raster/color/blend oracle in `tests/unit/mesh_oracle.h`; 171 exact full-buffer comparisons plus known gradient-zero/shared-edge/overlap assertions. Strict Release and Debug ASan/UBSan each pass new `mesh_cpu` plus existing `render` (2/2) through the native wrapper. This is software proof only. 2. Implemented adapter slice: bounded preparation plus private axis projection seam, no public ABI/Core/component changes. Private linker wrapping supplies deterministic allocator/upload/configuration failure injection. 3. Actual SDL readback through `scripts/test_local.py` private Xvfb: DPI 1/2, positive nonuniform scale, stretch/letterbox/integer/overscan presentation, fractional offsets, explicit/default viewport, nested clips, resize and transparent/opaque clears. Compare analytic coverage/top-left ownership to software at device coordinates. Compare SDL compositing to independently rasterized full-target SDL textures; actual fixture comparisons are exact, with no broad image tolerance. Include winding/degenerate/zero-gradient/overlap, alpha 0/0.5/1, sRGB threshold and out-of-gamut clamp, and mixed mesh/image/text/shape command ordering. 4. Sentinel readback before Present for malformed-last-payload, clip imbalance, capacities and each injected resource failure; target unchanged on preparation failure. Check partial cleanup, same-pointer mutation, destroy after failure, state restoration on every exit and next-frame recovery. Strict warnings and ASan/UBSan; compare owned resource counters with zero outstanding frame leases. Hardware GPU and non-Linux driver proof remain separate gates. Reproduce extraction only with `cmake -S tests/fixtures/mesh_cpu -B build-mesh -G Ninja`, build targets `test_mesh_cpu test_render`, then `python scripts/test_local.py --build-dir build-mesh -R '^(mesh_cpu|render)$' --output-on-failure`. Use a separate Debug build with `-DCUI_SANITIZE=ON`. Existing rounded-geometry and shadow adapter fixtures demonstrate actual SDL capture/fault-injection patterns, not mesh correctness. No dependency was fetched or installed. CMake accepts system SDL >=3.2 or its pinned fallback above; local system headers are SDL 3.4.18. Check the pinned fallback and selected CI SDL version during production validation. No gallery, Core, public capability or generated consumer guidance is changed by this design. ## Actual adapter verification and integration limits The private `tests/fixtures/sdl3_mesh` fixture builds only the adapter, new tests and selected existing render/rounded-geometry targets. Strict Release and Debug ASan/UBSan checks use the repository wrapper/private Xvfb. It compares cropped preparation to full-target textures made by the independent device-space oracle, **exactly**, with no pixel tolerance. Both use the existing SDL texture BLEND equation. Point drawing was rejected as an invalid reference after actual window-target readback showed different stored alpha; no opaque-only rejection was substituted. Actual vectors cover five presentation modes, DPI1/2/nonuniform axes, explicit viewport and fractional offsets, transparent/opaque clears, a real RGBA texture target, resize, shared edges/winding/gradient zero/SDR conversion, mixed ordered rect/mesh draws, and following image/text mapping. Preparation failures cover allocation, surface, upload, blend/scale configuration, malformed/unknown final command, invalid image, 257 triangles and 8M-texel exhaustion. Sentinel readback is unchanged; partial frame textures are released and a later valid frame works. Post-clear submission/state failures return false, release frame textures and attempt each restoration. A failed SDL restoration itself cannot guarantee that property was restored. No whole-frame transaction, hard realtime, hardware GPU or cross-platform driver proof is claimed. The separate cached-prefix build compiles against SDL3.2.28 headers/library in `/tmp/cui-deps-prefix`; its SDL_render.h SHA256 equals the header in the exact pinned archive above (`e32fcbc32e80d06bd69a3d36855bdac412b2d00195b83a5181458ced4cd317bf`). No dependency fetch/install occurred. The fixture README gives reproduction and integration responsibilities. Existing image/glyph caches keep their existing budgets; mesh resources have no cross-frame payload retention. Canonical CI, metadata and generated consumer resources remain the integrator's follow-up. Final local results: strict system-SDL Release 4/4 (mesh, CPU oracle, software render and existing SDL rounded geometry), system-SDL Debug ASan/UBSan 3/3, and cached SDL3.2.28 Release 3/3. The mesh fixture reports 108 exact readback comparisons plus preparation-failure/recovery assertions and a real final Present call. All use the private wrapper. Concurrent Xvfb startup initially failed; final runs were sequential and passed. Runtime linkage for the cached-prefix executable resolves SDL/FreeType/HarfBuzz under that existing prefix. Build logs live under `/home/matteo/.cache/cui-validation/sdl3-mesh*`; no other worker artifacts were modified or removed. --- ## SDL3 initial window visibility Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SDL3_WINDOW_VISIBILITY.md # SDL3 initial window visibility Add `cui_sdl3_create_with_options` and a new `cui_sdl3_window_options` value containing `bool initially_hidden`. Zero preserves visible creation. Keep the existing constructor and its ABI unchanged as a wrapper. Set SDL_WINDOW_HIDDEN in SDL_CreateWindow itself; never create visible then hide. Add main-thread visibility query and explicit show/hide operations with null-safe failure. SDL3 owns the window. Sokol and SDL_GPU adapters borrow host resources, so their callers control initial visibility. Bridge/language native runners keep visible creation for now; this additive C host API does not imply binding parity. Test real hidden creation, explicit show/hide, zero defaults and legacy creation under private Xvfb using the local wrapper. No desktop windows. Other window systems remain unverified. No existing by-value options structure changes. The bridge currently receives `cui_bridge_options` by pointer, with its fields mirrored by multiple FFI declarations. The existing record requires exact struct size and ABI version. A compatible future extension can add a separate `cui_bridge_create_with_window_options` entry point and a fixed-width, versioned options record, retaining existing options layout and create behavior. A post-create setter alone cannot prevent the initial flash. Builders must pass that option before the bridge native constructor and expose explicit visibility controls before hidden authoring can be claimed. That work is deferred here. Validation: warning-clean focused C11 build on Linux with SDL 3.4.18. Private-Xvfb CTest passed `sdl3_window_visibility`, `sdl3_system_appearance`, and `sdl3_services`. The visibility test checks the actual SDL hidden flag before any explicit show, show/hide transitions, null controls, zero options and the legacy visible constructor. The constructor source passes SDL_WINDOW_HIDDEN at creation. Other native window systems and GPU hardware are not validated. The subsequent bridge/builder implementation supersedes the original deferral above; see [its independent ABI contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/BRIDGE_WINDOW_VISIBILITY.md). --- ## SDL_Renderer V2: source audit and proposed owned-frame route Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SDL_RENDERER_V2.md # SDL_Renderer V2: source audit and proposed owned-frame route Design only, after software public 8671fa89; no SDL public symbols, production edits, compiler run, dependency install or support claim. SDL_GPU, Sokol GLCORE and Canvas remain required after SDL_Renderer; foreign bindings and all 78 parts remain pending. The audited SDL blob `aeb9b7d43098605e12c8435f15d34b690ff1551d` equals current root 479f3908 and this worker. System headers report SDL 3.4.18; CMake also accepts SDL >= 3.2 or pinned fallback 7f3ae3d57459e59943a4ecfefc8f6277ec6bf540. ## Existing behavior and consequential choices `backends/sdl3/cui_sdl3.c` owns window/renderer, borrows font and presents in V1 render. `cui_sdl3_size` sets STRETCH logical presentation; `render_density` combines presentation/render scales, rejects axes > 16 and chooses max-axis glyph density. Image rounding uses ceil-sized device textures and min-axis radii. Shadows are prepared before clear, with physical bypass/restoration; ordinary glyph resources and some validation can occur after clear. Mesh tickets have separate 256-triangle/ 8M-texel budgets. V1 glyph/bitmap/shadow caches, table, callbacks and pixels must remain untouched, including high-DPI behavior. README's final image-command exclusion is stale: IMAGE is implemented and advertised; correct only with evidence. Proposed V2 consumes every current kind through the proven CPU pixel policy, then copies the completed physical RGBA image once through SDL. Replaying V1 SDL draws with new backgrounds is insufficient: SDL BLEND does not normalize straight RGB by destination alpha as the CPU painter does. Old float strip/clip/image mapping also cannot establish the V2 fractional/anisotropic contract. This choice changes V2's native internal rasterization, never V1; it does not claim universal V1/V2 native unit-pixel equivalence. CPU glyph/shadow/background ordering and coverage are shared, not five new shaders; native acceleration covers transfer/presentation. | Alternative | Measurable owned footprint and limitation | | --- | --- | | Public software adapter forwarding | Rejected dependency: SDL must not link `cui_software`. Its separate target plus scratch also costs `2P+resources`, rejecting Retina 4K at 32 MiB before useful work. | | Shared painter into locked, unpublished back texture | CUI scratch can stay `P`; SDL lock pitch/span and nominal front/back textures need separate bounds. Lock failure is visible, unlock is void and can hide native-lock/upload failure; front/back ownership cannot make that failure detectable. Not recommended for a checked-upload contract. | | Explicit opt-in persistent CPU target | Could move one `P` into separately documented retained storage. Adds a new initialization/resizing/high-water lifetime and up to 32 MiB retained CPU plus transient work/texture; cannot call it a 32 MiB total. Not the smallest ownership model. | | **Owned prepared frame (recommended)** | One scratch `P` already in the counted transaction; no second destination plane, persistent CPU target or renderer-to-renderer dependency. Needs the precise private extraction below before SDL production. | `P = 4 * physical_width * physical_height`, checked. At 3840x2160, `P=33,177,600` bytes, versus `2P=66,355,200`; 32 MiB is 33,554,432. Thus extraction leaves 376,832 counted CPU bytes for command/resources at that size; it does NOT promise every 4K scene fits. Existing per-background 4M and aggregate 8M/work/font limits still apply. ## Private extraction checkpoint requiring review before code Move allocation-free/CPU transaction helpers to `backends/common/`, not Core and not a dependency on another adapter target. Proposed names `cui_cpu_v2_internal.h`, `cui_cpu_v2_frame_internal.h`, `cui_cpu_v2_text_internal.h`, `cui_cpu_v2_shadow_internal.h`; private static identifiers become `cui_cpu_v2_*`. Pure bitmap/shape/mesh/shadow utility headers currently housed under software must move mechanically or have explicitly reviewed private forwarding includes. SDL already includes those pure headers; this is source ownership, not library linkage. Update canonical SDK discovery to copy `backends/common/`; no hand-edited SDK. First prove mechanical move/rename with all frozen source/pixel/allocation oracles. Exact private lifecycle sketch (names/types are proposals): ```c typedef struct { const void *data; size_t bytes; } cui_cpu_v2_exclusion; typedef struct { unsigned width, height; cui_cpu_v2_exclusion excluded[3]; /* owner, published pixels, old target view */ size_t exclusion_count; /* <= 3, checked; no registry */ bool *owner_busy; /* optional; caller clears after all cleanup */ } cui_cpu_v2_frame_request; /* Private frame embeds workspace, counted text owner/session and an EMPTY / * PREPARING / READY / RELEASING state; pixels point INTO its one CPU workspace. */ void cui_cpu_v2_frame_init(cui_cpu_v2_frame *); cui_error cui_cpu_v2_frame_prepare(cui_cpu_v2_frame *, const cui_cpu_v2_frame_request *, const cui_draw_list_v2 *, cui_color, const cui_render_v2_options *, cui_font *, alloc_fn, free_fn, void *); void cui_cpu_v2_frame_release(cui_cpu_v2_frame *); ``` Init allocates nothing. A frame is address-stable/noncopyable private ownership, not a restriction on portable draw-list copying. Prepare requires EMPTY; READY or reentrant use rejects untouched. Exclude frame/request records automatically, plus supplied owner/published-target ranges, before source traversal or record mutation. Preserve current early no-font/no-Bidi rejection, stop-before-dereference checks, all checked active resource extents, capacities and current numeric policy. All capability/geometry/source preflight remains callback-free; claim owner busy at the current first-allocation boundary. Validate every workspace take. After exact planning, allocate existing CPU/metadata blocks, record owned text, prepare resources, clear scratch and paint the complete list in original order. There is no external target or publication during prepare. READY exposes tight RGBA rows/stride/span; no post-READY shaping or painting remains. Keep workspace, text owner and session embedded at their final addresses (session.owner points inside the same frame); never return pointers into a temporary copied session. Release on EMPTY is harmless. Release during PREPARING or RELEASING is a no-op: it neither cancels preparation nor clears the outer owner busy flag. Prepare on any non-EMPTY state returns LIFECYCLE without callbacks. READY -> RELEASING happens before the first text/free callback; only the outer release owns teardown. Internal preparation failure likewise claims RELEASING before cleanup (the public release entry cannot cancel PREPARING). Teardown ends text session, then frees workspace, then canonicalizes EMPTY, while the outer adapter keeps owner busy through its remaining native cleanup. Recursive release/free callbacks observe RELEASING and cannot double-free; callbacks cannot mutate/retire the frame or borrowed owner. A release request from an allocation callback is deliberately not queued: successful preparation still returns READY to its outer caller. Every failure returns EMPTY, never a partial READY handle or expired resource. Allocation/provider side effects are not rollbackable. Frame control is fixed stack storage, separate from the CPU/metadata heap quotas: `sizeof(frame) = aligned(state/self/ownership fields + workspace + output view + optional counted_text_owner + text_session)`. The existing 64-face owner table is embedded once, not duplicated in a temporary later copied into the frame. Require `sizeof(frame) <= 2048` as an engineering guard (not measured yet), report actual native/WASM text/no-text size/alignment before code approval, and account one frame plus request, existing 64-entry clip stacks/validator plan and scalar locals. Compiler spills/call frames and dependency stacks are additional; no total-stack byte claim follows. No stack storage scales with viewport or command count. Mechanical namespace proof first freezes the four original8671 private V2 header bytes/hashes. Normalize only identifier prefixes and include paths; demand exact remaining source equality. Leave existing frozen V1 source, pixels, ABI, original Effects/text and `cui_shadow.h` authority hashes unchanged. Old software header paths forward with exact private type/function/constant aliases, including the pre-include shadow sample hook. Test new-first/old-first/selective/all-header orders and real calls, separately prefixed frozen old sizeof/alignment/active outputs and exact allocation requests. Namespace work adds no frame state or allocation; extraction must independently retain those compatibility oracles. The existing software helper becomes prepare -> active-row memcpy -> release, with existing published target/view exclusions and busy timing preserved. Its public/old private signatures remain; exact allocation request/count/padding/ callback-order oracles must pass before SDL uses the new seam. SDL omits a CPU published-target range and supplies its entire backend object exclusion. No public frame handle, Core renderer architecture or input-dispatch change follows. ## Proposed SDL-specific API, target and admission Add `cui_sdl3_v2_info { uint32_t size; cui_draw_v2_support draw; uint32_t text_features; cui_render_v2_options defaults; }` and typed `cui_sdl3_query_v2(const cui_sdl3 *, cui_sdl3_v2_info *)` / `cui_sdl3_render_v2(cui_sdl3 *, const cui_draw_list_v2 *, cui_color, const cui_render_v2_options *)`. SDL-specific A8/CONTEXT/TRACKING constants avoid including the software public header. V1 function table/capabilities stay intact. Query actual owned window backbuffer only: non-NULL SDL render targets are unsupported, not silently presented. Query current logical window size and render output size without calling mutating `cui_sdl3_size`. Defaults use output/logical axis ratios and origin 0; explicit options retain independent axes 1/65536..64 and origins +/-1e6, with physical viewport exactly current output. Do not inherit V1 scale <= 16, clip rounding or cached text density. Requery after size/DPI changes; explicit options are intentional physical transforms, not a resize reservation. Query checks positive sides<= 16384, native RGBA32 texture availability/size limit and sRGB output; reject unsupported HDR/conversion routes before composition. Use software's actual `min(16384,(B-P)/C,M/D)` command ceiling and background min(4096,count), defaults B = 32 MiB / M = 1 MiB. Retain common CPU/metadata/work quotas; final resource plans may reject. Texture and transfer ceilings additionally admit one physical RGBA upload `P`, not just individual background planes. CPU background planes remain CPU resources, not additional native uploads. One application-live SDL texture with nominal bytes `P`; no V2 LRU or pointer/revision cache. Existing V1 cache/font state is class 1; counted common transaction is class 2; opaque SDL/ FT/HB/Bidi/provider and driver allocations are separate class 3. Driver-deferred storage is inflight/opaque, not falsely relabeled retained or synchronously freed. Query/output and original options/list aliases reject before copying; prepared frame exclusions cover all active known ranges. Entire opaque SDL/font graphs must remain stable/disjoint, main-thread confined, without same-font recursion. Guard any SDL query calls that can invoke installed SDL allocation hooks; restore that temporary guard before pure source validation, and do not read input bytes while it changes owner state. Prepare then holds busy from allocation through native cleanup. Busy V2 query/render rejects LIFECYCLE; V1 render/size and native mutators must refuse before changing state; void destroy is no-op/retry. Poll/wait must not dispatch nested events during a V2 call. Measure private layout/counts before adding guard/fault state; no assumed padding or silent V1 allocation changes. ## Native commit, failure and lifetime boundary Snapshot presentation mode/dimensions, scale, viewport/clip enable and rectangles, draw blend/color before changing SDL state. Complete CPU preparation, native RGBA32 texture creation/checked update and property setup before any backbuffer clear/draw. Require native format rather than hidden conversion fallback; use NEAREST, BLEND_NONE, white modulation and alpha 1. Submit the entire texture at integer physical (0, 0, width, height) with presentation disabled, scale 1, no viewport/ clip. This is one-to-one final-byte transport, never IMAGE radius remasking, opacity multiplication, fractional resampling or another blend of the frame. Original clips/radii/phase/text alpha were already resolved once on the CPU. An unpublished new texture is the back resource. Failure before native drawing never replaces the old displayed frame; release it and READY frame. After clear/ draw, failure may have partially changed the backbuffer: no GPU rollback claim. Explicitly check `SDL_FlushRenderer` before the single presentation attempt; restore every snapshotted property even after another restoration fails. Failed restoration poisons further render/query until backend destruction/recreation, rather than claiming a safe retry on unknown state. Other failures with successful restoration allow fresh preparation/retry; never replay Core/input callbacks. No extra retained front texture is needed for this full-frame path; the previous visible presentation is not an owned texture or a rollback guarantee. CUI allocator/work failures are CAPACITY; unavailable target/busy is LIFECYCLE; malformed/unsupported data and checked SDL API failures are INVALID_ACTION with `cui_sdl3_error()` detail. Success means checked preparation/upload/draw/flush and **presentation attempted**. It cannot promise physical presentation or detect all native presentation failures in the pinned SDL. Destroy new texture through SDL after last queued use and release frame through the same busy scope; no fake GPU wait/fence. Destruction does not prove immediate driver storage reclamation. Window stored alpha/precision can differ from the exact CPU RGBA image; document native output-format limits and test an RGBA target transport seam independently. ## Evidence and independently reviewable production gates 1. Mechanical common-helper relocation, then owned-frame extraction only: immutable original V1 software/Effects/text, public software 12 checks and exact allocation request formulas; prepare/release/reentry/allocation failures, READY lifetime, aliases, negative strides/overflow and repeated EMPTY cleanup. No SDL query yet. 2. Freeze actual old SDL V1 outputs/cache/allocation/ABI and high-DPI state; measure guard bytes. Implement full SDL query/all-kind route, not a background-only success. Use real query -> Core begin/end -> SDL render; include both brush models/spaces, DROP/INSET, images/meshes, contextual/styled/span/gradient text, transparent/opaque clears, fractional/unequal/min/max scales and huge origins. 3. Compare CPU READY bytes to existing independent references; native BLEND_NONE transport to separately generated whole-frame SDL textures, exact RGB and all RGBA channels where the actual target preserves alpha. Do not substitute SDL point primitives as the blend oracle. Native format limitations stay explicit. 4. Hidden-at-creation private-Xvfb software/available accelerated-driver readback before Present, plus native-format rejection, query/output aliases, stale DPI/ resize, budgets, late invalid command, every CUI allocation and SDL create/update/ setup/draw/flush/present/restore failure. Assert no early clear, no replacement on preparation failure, cleanup/known-state retry and poisoned-state refusal. Test masked pinned Present failure as submission-only, not false detection. 5. Root actual CMake/selective/C++/SDK/skill freshness and no adapter cross-link. Hardware GPU, real mixed-DPI monitor migration and untested OS/Wayland remain explicit deferrals; SDL_GPU/Sokol/Canvas and foreign bindings stay unfinished. Primary SDL evidence (pinned source, independently inspected; no copied code): [renderer implementation](https://github.com/libsdl-org/SDL/blob/7f3ae3d57459e59943a4ecfefc8f6277ec6bf540/src/render/SDL_render.c) `SDL_UpdateTexture`1921-1955, unlock2277-2315, checked flush310-316, present4675-4708, destruction4710-4761: conversion can hide errors, unlock has no status, Present masks backend/flush failure, destroy flushes queued texture use. [public renderer header](https://github.com/libsdl-org/SDL/blob/7f3ae3d57459e59943a4ecfefc8f6277ec6bf540/include/SDL3/SDL_render.h) properties364-371 and readback/presentation2205-2279 describe format/size/colorspace, main-thread use and invalidated post-Present backbuffer. Selected installed/CI SDL versions must be verified during production, not inferred from their numbers. --- ## SDL V2 baseline and API review checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SDL_V2_BASELINE_CHECKPOINT.md # SDL V2 baseline and API review checkpoint Source-only followup to `SDL_RENDERER_V2.md`, based on signed `b386ec55`. No SDL production/header change, compile, output capture or new support claim is included. The owned CPU frame remains subject to root integration acceptance. ## Frozen original and actual dependencies `tests/fixtures/sdl_v1_reference` freezes the exact original CUI SDL implementation, mesh helper and public header (about 65 KiB), independently pinned by Python hash constants and receipt. Original source blob is `aeb9b7d43098605e12c8435f15d34b690ff1551d`. Pure bitmap/shape/mesh/shadow dependencies and generic renderer header are hash-pinned without duplicate copies. The frozen source will be compiled in its own prefixed TU; it must never be reconstructed from the future candidate. Existing archive hash is recorded read-only. Installed header/pkg-config/runtime and cached native CMake agree on SDL 3.4.18; `SDL_GetVersion` returned 3004018 and revision `SDL-release-3.4.18-0-g829a65d76`. Those version-only calls initialize no video or windows. Repository fallback is commit `7f3ae3d57459e59943a4ecfefc8f6277ec6bf540`; system SDL >=3.2 is also accepted. Only two needed upstream renderer files were fetched into the existing builddir, with URLs/hashes in the receipt; no checkout, installation or library rebuild. Installed library identity does not prove absence of vendor patches. Both audited revisions keep Unlock void and can hide nested conversion-update failure. Both Present implementations ignore implicit-flush/backend failure before returning success. Explicit Flush reports its command-queue error. Therefore keep native advertised RGBA32 admission and checked Update/Flush, and describe success as submission checked and presentation attempted, never physical display success. Returned public texture format alone cannot rule out SDL conversion wrappers; advertised native support selects the direct texture-creation branch. Primary source: [fallback renderer](https://github.com/libsdl-org/SDL/blob/7f3ae3d57459e59943a4ecfefc8f6277ec6bf540/src/render/SDL_render.c) UpdateNative2042, Unlock2484, Flush347, Present5040, native creation1422; [installed-release renderer](https://github.com/libsdl-org/SDL/blob/release-3.4.18/src/render/SDL_render.c) UpdateNative2291, Unlock2753, Flush375, Present5517. These exact downloaded-source line numbers supersede the earlier checkpoint's inaccurate line references. ## Existing V1 behavior to preserve The generic function table is unchanged: user/name/capabilities/render/destroy. Public cache stats, hidden-window options, callback-app records and all25 function signatures are frozen in the C11 compile-only `sdl_v1_api.c` fixture. Its assertions use explicit old records/offsets and function-pointer types, never struct padding. No platform/SDL types appear in those public records. Constructor performs one CUI calloc for the opaque object, creates a resizable, high-density window (hidden at creation when requested), then an SDL renderer. V1 glyph cache: 256 entries, 4 MiB coverage, coverage bytes/hash/w/h key with exact byte collision check, LRU hit/miss counters; color modulation does not rekey. Gradient glyphs use their existing uncached surface/texture path. Bitmap cache: 64 slots/64 MiB RGBA; shadows additionally use the unchanged 32 MiB uploaded subbudget plus the pure CPU shadow cache. Mesh tickets cap 256 triangles/8M texels. Keep exact cache/request/eviction/revision behavior on the V1 route. V1 is not generally transactional: some invalid non-mesh commands are discovered after clear/earlier draws, and density/cache state can already change. Record and compare those original failure effects; do not impose V2 atomicity on V1. `size()` mutates logical presentation to STRETCH using current window size. `render_density()` re-queries logical presentation rectangle and renderer scale on every render, computes independent densities <=16 and max-axis text density. Do not replace it or borrow it for V2's <=64 independent transform. V1 shapes use device row spans, images ceil device dimensions and min-axis radius density, shadows retain their old raster/rounding path, meshes retain their physical view. Original clip rounding and all painter order stay exact. V2 must not populate, evict or reset these caches, call size(), or overwrite these density fields. ## Baseline proof preparation, not yet executed Compile original and candidate in distinct TUs with separate opaque types/backends and independent identical real-font/fallback graphs. Capture readback before Present, normalize actual surface format to owned RGBA rows, compare complete pixels and active state/flags; never hash-only/padding/pointer-address equality. Capture cold/warm/revised IMAGE and glyphs, contextual/gradient text, drop/inset, mesh, asymmetric shape/clip and rejected late input, at logical STRETCH, disabled presentation, unequal renderer scales, nonzero viewport/clip and simulated 2x/3x output targets. Preserve actual target state; modern SDL refuses Present on a texture target, so use original pre-Present capture instrumentation for that Retina simulation rather than weakening a failed render assertion. Count CUI-owned calloc/malloc/free requests separately from opaque SDL/font work; trace native texture create/update/destroy and submission calls without treating SDL allocator traffic as CUI bytes. Freeze constructor/object layout plus cache requests, counts, lifecycle failures, cached entries/bytes/hits/misses and exact V1 pixels. Real monitor migration/Retina hardware remains deferred. All native execution uses hidden-at-creation private-Xvfb wrapper, never the desktop. `layout_source()` prepares compact compile-only constants from the exact frozen private struct prefix. Candidate only appends `bool v2_busy, v2_faulted`; no field is inserted or reordered. Measure native size/alignment/all old offsets and guard offsets first; wasm32 is a pointer-width diagnostic, not SDL/WASI support. No opaque-layout growth or constructor-byte exception is yet approved: report actual old/new before choosing. No new retained texture/frame/cache ownership is proposed. ## Exact public API proposal and ordering decision Retain the previously proposed `cui_sdl3_v2_info` (size/draw/text_features/defaults), SDL-specific A8/CONTEXT/TRACKING bits and typed `cui_error` query/render signatures. Exact query out->size; errors preserve output. NULL render options use fresh query defaults. Same default CPU 32 MiB/metadata 1 MiB and common work ceilings as software; command ceiling uses physical P, command stride and descriptor size. Native texture/transfer admission independently requires P within its ceiling. One CPU image, not 2P: 3840x2160 P=33,177,600 fits 32 MiB before commands/resources. CPU background planes are not extra native uploads; common producer limits still apply. Opaque SDL/driver/font allocations remain separate class 3, not jointly bounded. Query current owned window/output, reject non-NULL native render targets, unknown or unsupported format/colorspace/size, and refuse busy/faulted backend. Temporary guard protects SDL property/size queries that may invoke allocator hooks; restore it before pure frame preflight. Fresh framebuffer ratios provide defaults, not V1 cached density. Requery after resize; no stale-dimension reservation. **Review needed before production:** NULL defaults require native queries before full common geometry preflight, but active source aliases must reject before changing owner busy. Checking only list/options/command arrays misses borrowed image/mesh/text/span/stop ranges. Do not silently mutate aliased input bytes during the query guard, duplicate the resource parser, or cache old dimensions to evade it. Recommend a small pure common active-source-range preflight, reviewed separately: `cui_error cui_cpu_v2_sources_exclude(list, ranges, count)` with bounded command/ span/stop/vertex counts and checked byte extents, no pointed-data/geometry/font/ SDL calls. It rejects known owner/control ranges before native callbacks. The full validator must reuse that same field-selection authority, retaining actual geometry/UTF8/resource validation and error/budget tests. Whole opaque SDL/font storage remains explicitly caller-disjoint/stable, not falsely fully validated. No common code change is included here; root owns that approval. After preparation, snapshot logical/scale/viewport/clip/color-scale state; disable logical presentation, use scale 1/full viewport/no clip/color-scale 1, upload tight RGBA32, NEAREST, white texture modulation and BLEND_NONE. A single full-output copy already carries clear pixels; native clear is unnecessary. Check draw/flush, attempt Present, then restore every changed property even after failure. Failed restoration poisons future render/query; destroy stays available when not busy. No rollback after native drawing. Release native texture then frame while busy; ordinary SDL destruction is not synchronous driver-memory reclamation. Lifecycle and typed-error details need final API review before implementation. All other three adapters after SDL, bindings and remaining 78-part coverage stay pending. --- ## SDL_Renderer V2 public entry: next review checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SDL_V2_PUBLIC_ENTRY_CHECKPOINT.md # SDL_Renderer V2 public entry: next review checkpoint Proposal only, following `SDL_V2_BASELINE_CHECKPOINT.md`, signed range checkpoint 4ca5bbe3 and accepted private owned-frame extraction. No SDL API, object change, native measurement or renderer support is implemented here. The private range extractor is integrated (`16827ec9`); its exact-boundary and frozen-validator checks pass on the combined source (three tests, 0.16 seconds; see `docs/validation/cpu-v2-source-ranges-worker.json`). Broader rendering regression acceptance remains pending. Preserve the frozen SDL baseline and all V1 function signatures/table/cache/density behavior. ## Minimal additive header ```c enum { CUI_SDL3_V2_TEXT_A8 = 1u << 0, CUI_SDL3_V2_TEXT_CONTEXT = 1u << 1, CUI_SDL3_V2_TEXT_TRACKING = 1u << 2 }; typedef struct { uint32_t size; cui_draw_v2_support draw; uint32_t text_features; cui_render_v2_options defaults; } cui_sdl3_v2_info; cui_error cui_sdl3_query_v2(const cui_sdl3 *, cui_sdl3_v2_info *out); cui_error cui_sdl3_render_v2(cui_sdl3 *, const cui_draw_list_v2 *, cui_color clear, const cui_render_v2_options *options); ``` Include public `cui_draw_v2.h`; no software header, SDL type, generic registry or V1 capability/table extension. Query requires exact `out->size`, known range disjointness before reading/writing output and unchanged output on error. Output and all inputs must remain disjoint from the opaque SDL/font graphs. Query can invoke SDL allocation hooks; it is not advertised as allocation-free. ## Guard measurement before implementation Use the existing frozen-source `layout_source()` fixture to measure original and candidate `sizeof`, alignment, every old offset and appended `v2_busy/v2_faulted` offsets. Compile native and wasm32 constants only; wasm32 is a layout diagnostic, not SDL browser/WASI support. Report exact compiler/settings and constructor allocation request delta before approval. No assumed padding, approved growth bound or retained texture/frame/cache is inferred from the software guard proof. V1 callback/cache/pixel and allocation-count comparisons use separately compiled original SDL source; object-byte change must be explicit if approved. ## Query and render ordering Refuse busy/faulted owner before native calls. Query validates output alias first. Render uses the shared pure range walker with owner/control exclusions before any busy mutation or SDL call, including NULL options. Then temporarily claim busy, query fresh owned-window logical/output sizes, target, texture-format list and colorspace/limits; restore guard before full common preparation. No dimension query through mutating `cui_sdl3_size`, cached-DPI reservation or duplicate active pointer parser. Borrowed metadata/resources remain stable throughout synchronous return; callback side effects cannot be rolled back. Only the owned window backbuffer, positive dimensions <=16384, native advertised RGBA32 and supported sRGB output qualify. Reject texture targets/HDR/conversion routes clearly. Defaults use independent output/logical ratios and origin zero; explicit options use the common independent-axis domain and exact current physical viewport. Ceilings/defaults match software/common planning, including physical P=4wh, metadata and command descriptor admission; transfer/texture P has a separate explicit ceiling. One counted CPU plane permits 4K P=33,177,600 within 32 MiB before resources. This does not guarantee every 4K list fits. Opaque SDL/driver/font allocations remain separately documented class 3. The common frame prepares every command and resource before native mutation. Claim owner busy at its first allocation boundary through native cleanup. Snapshot SDL logical/scale/viewport/clip/color-scale state, establish physical 1:1 state, create transient native RGBA32 texture, checked tight upload, NEAREST/white modulation/BLEND_NONE, full-output copy and explicit Flush. No second CPU plane, V1 draw replay or software-adapter linkage. Restore every changed property after any failure; release texture and frame while busy. Restore failure sets faulted; future query/render refuses until destruction/recreation. No native rollback or synchronous driver-memory reclamation guarantee. Present is an attempt after checked submission, not proof of physical presentation or even backend-present error reporting (both audited SDL implementations hide that result). Busy V2 query/render returns LIFECYCLE; V1 render returns false, mutating size/native access routes must refuse as individually audited, and void destroy is a no-op requiring retry. Faulted idle owner remains destroyable. ## Gates and metadata First approve measured guard growth and exact native failure/error mapping. Then implement all-command V2 query/render together with hidden-at-creation tests: query-to-Core composition; original V1 pixel/cache/allocation differential; Retina/fractional/anisotropic resize; all source aliases before native hooks; reentry in allocation/free; native format refusal; upload/draw/flush/restoration failure and retry/fault behavior. Capture before Present where needed; compare CPU expected pixels independently, not native V1 equivalence assumptions. Only passing actual gates permits public metadata/guide/software-exception updates. SDL_GPU, Sokol GLCORE, Canvas and foreign bindings remain required followups; this proposal changes no 78-component status. ## Proposed exhaustive V1 busy-access matrix (review before guard edit) Read the owner busy flag before other owner fields, input/output arguments, SDL, allocation or callbacks. These are only nested-V2 rules; idle V1 behavior remains exact. Guard internal call sites too: previously obtained platform/window/renderer function tables remain callable during a callback and cannot bypass the guard. | Public entry / retained callback | While owner busy | Idle owner faulted | | --- | --- | --- | | render, render_capture, save_bmp; renderer render callback | false, no reads/native calls | false (renderer state untrustworthy) | | destroy; renderer destroy callback | no-op; caller retries | destroy normally | | set_visible, is_visible, set_cursor, poll, accessibility_window, set_decorated, wait_events | false; output/state unchanged | false (conservative refusal of native access) | | size | no-op; both outputs unchanged | no-op; outputs unchanged | | driver | constant `"unavailable"`, no SDL call | same | | appearance | false; output unchanged | copied snapshot allowed (no SDL call) | | glyph_cache_stats | all-zero value | copied existing stats allowed | | frame_delta | zero; clock unchanged | zero; clock unchanged | | clipboard_interface | zero record | zero record | | retained clipboard_set / clipboard_get | false / empty string; no free/native call | same | | window_interface | zero record | zero record | | retained window query / perform | zero info / false | same | | interface | zero record; no driver query | zero record | Constructors create independent owners and retain their existing main-thread contract; they do not inspect another owner's busy flag. `run` retains its existing no-nesting contract rather than adding a global owner registry. Ownerless video_driver/error/wait keep existing behavior; they expose no owner resource or render permission (the error string remains SDL's transient diagnostic). New V2 query/render returns LIFECYCLE for busy/faulted owners. No public raw SDL handle accessor exists. This matrix is proposed, not a claim of implemented guards. ## Measurement fixture prepared, not executed `tests/distribution/sdl_v2_guard_layout.py` emits either immutable old declarations or exactly the two appended booleans, compact size/alignment/constructor-byte and **every** old-field offset constant. No renderer/window/init function is included. Use native strict C11 and pinned wasm32 clang object/assembly constants under the next explicit lease; installed SDL headers supply actual SDL type layouts. The wasm32 compile is diagnostic and may need reviewed target-header accommodation; do not misreport host-configured SDL headers as a supported WASM adapter. Constructor-byte measurement is exactly the frozen one `calloc(1,sizeof(*s))` request; SDL's separately owned allocations are not counted as this object. Report old/new bytes and actual old-offset equality before choosing growth. ## Exact lease-only microgate command Prepared runner (not executed) compiles four small assembly-only TUs serially, parses unsigned constants and writes `commands.log` plus `receipt.json`. It verifies all 37 old offsets, alignment, exact constructor-byte=object-size correspondence, and guards beyond the complete old cursor-array extent. It reports growth rather than assuming a permissible bound. It never links or initializes SDL. ```sh python tests/distribution/measure_sdl_v2_guard.py \ --output-dir build-shadow/sdl-guard-layout \ --zig /home/matteo/.cache/uv/archive-v0/Owlnrxx9q6JToEVIXt6mk/ziglang/zig \ --cpu 1 ``` The runner pins itself to CPU1/nice19, records exact compiler versions/flags, verifies frozen source hashes before compilation and hashes generated TUs. Native uses strict C11/O1/Werror. WASM uses pinned Zig clang/no-default-config, explicit WASI libc roots plus SDL public headers from `/usr/include`; no link or host libc is intended. Cross-target SDL public-header compatibility is unproven: if headers reject WASI or select incompatible system definitions, retain failure and review accommodation rather than silently replacing SDL types/weakening warnings. This diagnostic is distinct from an actual Emscripten/SDL ABI claim. The constructor-byte result concerns CUI's sole opaque-object calloc request; SDL/runtime allocation behavior still requires the frozen paired runtime gate. No microgate execution occurred while root held the browser/heavy lease. ## Measured guard layout (2026-11-01) The four compile-only original/candidate probes pass on native and wasm32. All 37 existing offsets and alignment8 are unchanged. Native size/constructor request grows27384→27392 bytes (+8); wasm32 remains24192 bytes (+0). Exact commands, frozen authority and all constants are recorded in `docs/validation/sdl-v2-guard-layout.json`. No SDL function was invoked. This supplies the requested measurement, not approval or implementation of the proposed public entry points. Native failure mapping, guard behavior and original V1 runtime differential acceptance remain required. ## Integrator implementation decision (2026-11-01) Approve the additive SDL-specific query/render slice above, including the measured native opaque-object increase of eight bytes (WASM zero). Keep the constructor's single allocation count and every old field offset; no new V1 cache or allocation path is approved. This private object cost is explicit, not a public ABI change. Use existing typed errors: busy/faulted owner → `CUI_ERROR_LIFECYCLE`; invalid arguments/aliases or unsupported native target/format/colorspace → `CUI_ERROR_INVALID_ACTION`; explicit limits or counted allocation failure → `CUI_ERROR_CAPACITY`. Preserve common preparation errors. Native query/create/ upload/draw/Flush failure → `CUI_ERROR_INVALID_ACTION`. A restoration failure also poisons the owner; idle destruction must remain possible. Keep the exhaustive busy-access matrix, pure exclusion checks before mutation/native calls, and busy ownership through cleanup. Present remains an attempt, not a display guarantee. Implementation may proceed in isolation. Public support stays unadvertised until frozen V1 runtime differentials, all-command V2 output, native failure injection, reentry/aliasing and state restoration checks pass. This decision introduces no new input dispatch or application state-ownership architecture. ## Runtime-informed transfer amendment (2026-11-01) The first strict source/legacy-ABI compilation passed, but the first real private- Xvfb software-renderer query failed. Preserved diagnostics identify SDL 3.4.18 software formats ARGB8888/XRGB8888/INDEX8 (BGRA32 on this host), no native RGBA32, and an absent maximum-texture-size property. This evidence supersedes the RGBA32-only admission above; it does not establish rendering support yet. Integrator approves this bounded implementation slice: - Prefer advertised RGBA32; otherwise accept advertised BGRA32. Reject all other formats. No implicit SDL format conversion or color-space conversion is admitted. - For BGRA32, swap red/blue bytes in the already owned, fully painted CPU plane immediately before upload. Preserve green/alpha exactly. No additional pixel plane, retained image, allocation category or public ownership change. - SDL maximum texture size zero means no reported limit (including an absent property), following SDL's own checked-creation behavior. Continue enforcing CUI's 16384 dimension ceiling and all byte/pixel budgets. A positive reported maximum additionally bounds dimensions; reject a negative value. Texture creation failure remains a checked error, not proof of supported dimensions. - Use SDL's documented sRGB default for an absent output-colorspace property; explicitly non-sRGB/HDR output remains rejected. - Prove the channel permutation with independent pixel/alpha oracles and real software-renderer upload/readback. Cover both format-selection branches and rejected formats, missing/zero/positive/negative limits, native failures and immutable V1 compatibility. Keep original failed logs and distinguish source, compile and runtime outcomes. No physical GPU or cross-platform claim. This amendment changes only native transfer admission. Shared composition, layout, input, common painting, state restoration and bounded frame ownership remain under their previously reviewed contracts. Public support stays unfinished until the implementation and integrated verification pass. --- ## Pure source-range seam before SDL native query Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SDL_V2_SOURCE_RANGES.md # Pure source-range seam before SDL native query Proposal only, against accepted owned-frame code. No common/SDL production code is changed. This resolves the ordering issue in `SDL_V2_BASELINE_CHECKPOINT.md`. The SDL renderer may need native size/property queries to construct NULL-option defaults. Those calls may invoke allocator callbacks, so known input aliases to its busy byte/owner object must reject before temporarily claiming that guard. ## One active pointer grammar, two traversal policies Proposed private common records/functions (no public types/platform dependency): ```c typedef enum { CUI_CPU_SOURCE_IMAGE, CUI_CPU_SOURCE_MESH, CUI_CPU_SOURCE_TEXT_BYTES, CUI_CPU_SOURCE_TEXT_SPANS, CUI_CPU_SOURCE_TEXT_STOPS } cui_cpu_v2_source_part; /* Read only tag/scalar/pointer fields of an already accessible command record. * Inactive selector -> canonical NULL/0; failure leaves out untouched. */ cui_error cui_cpu_v2_source_range(const cui_draw_command_v2 *, cui_cpu_v2_source_part, cui_cpu_v2_exclusion *out); /* NULL options means no options record; not fabricated dimensions/defaults. * No source bytes, vertex values, stops or spans are dereferenced. */ cui_error cui_cpu_v2_sources_exclude(const cui_draw_list_v2 *, const cui_render_v2_options *, const cui_cpu_v2_exclusion *, size_t count); ``` Range extraction is the sole authority for these pointer/extent selections: | Selector | Active condition | Pointer / byte extent | | --- | --- | --- | | IMAGE | IMAGE tag and matching legacy type | bitmap pixels / stride * height | | MESH | MESH tag and matching legacy type | vertices / vertex_count * sizeof(vertex) | | TEXT_BYTES | TEXT | non-NULL paragraph.data selects entire paragraph, including length 0; otherwise raw text | | TEXT_SPANS | TEXT with paragraph.data | text_colors / count * sizeof(span) | | TEXT_STOPS | TEXT with LINEAR paint | stops / count * sizeof(stop) | Other selectors return NULL/0 without reading inactive payload fields. BACKGROUND is entirely owned by value; it must not be interpreted as legacy payload. POP has no active borrowed fields. SOLID text paint ignores poisoned stop fields; contextual source ignores poisoned raw text. Unsupported command kind or legacy tag mismatch fails without inspecting inactive unions. This is finite typed extraction, not a callback visitor or a generic renderer registry. Range multiplication is checked against SIZE_MAX before forming a byte extent. The extractor checks arithmetic, not font availability, UTF8, geometry, sampler limits, source contents or aggregate work policy. It never reads pointees or calls an allocator/provider. Its output is a caller-local scalar record, not retained metadata. Pointer validity/accessibility is a caller precondition; this is not a memory probing facility. Known overlap and address-end overflow reject through the existing private disjoint primitive; whole opaque font/SDL graphs remain an explicit disjoint/stable caller precondition. ## SDL-only prequery traversal and bounds `sources_exclude` first rejects NULL list and invalid exclusion count/pointer (max 7), then checks list record and optional options record against every owner range **before reading either record**. No options fields/dimensions are needed. It checks exact V2 header/stride/tag/error/output policy and count <= 16384, then checked count*sizeof(command), NULL/count consistency and command-array overlap before reading commands. Source records are borrowed and stable throughout. It visits all five selectors per command (at most 81,920 constant-time extractions), checking returned extents against bounded owner ranges. The SDL initial call needs only its enclosing object range. At max 7 exclusions the conservative upper bound is 573,440 nested range comparisons plus fixed top-level checks; no iteration over resource bytes/vertices/spans/stops is performed. O(1) local storage, no heap, font capability/shape/layout calls, SDL calls, input dispatch or numeric geometry. Before native callbacks the new SDL traversal also rejects source-metadata work that cannot be admitted: LINEAR stops 2..8, spans <= 4096 (only contextual text), text <= 65536 bytes per command and 256 KiB aggregate, image stride*height overflow, mesh vertex byte overflow and32 MiB inspected-work envelope. For contextual text, compute text_bytes*(1+span_count) with checked arithmetic for the existing 32 MiB repeated-paragraph inspection envelope; do not scan span contents or perform 4096 iterations merely to compute this admission. NULL/nonzero source mismatches and malformed absent-paragraph metadata reject. Counts/extents are bounded before aliases are traversed. Numeric/style/resource validity still belongs to full validation after query; prequery success is not render support or a valid frame. Failures precede any owner flag mutation, SDL allocation/query callback or output write. Structural/tag/NULL/count-shape/overlap errors are INVALID_ACTION; exceeded count/byte/work ceilings and byte arithmetic overflow are CAPACITY. Multiple invalid fields have this new entry's explicit top-level/command/selector order; that policy must not be retroactively imposed on the existing validator. ## Preserve old validator precedence exactly Do **not** call the new whole-list `sources_exclude` entry at the start of the old validator. Keep every existing geometry/style/font/capacity predicate, sequence, short-circuit and error return at its original location. Replace only pointer/ extent extraction at each existing alias-check site with `source_range` for the corresponding selector. In particular: - Bitmap validity/crop/opacity checks still precede IMAGE alias checks. - Mesh multiply/aggregate CAPACITY checks still precede mesh alias and vertex reads. - TEXT font/context/style/count checks keep their order; the early stop-owner check remains before paint validation can read stops. - Text byte/work checks still precede contextual source validation; span overlap stays before span contents; the raw metadata branch retains its short-circuit. - Final stops/output-plan alias checks and final budget/output publication retain their current positions. The extractor cannot turn a prior INVALID into CAPACITY: at these sites its checked arithmetic has already passed the original guards. The top-level list/options/array checks retain their existing sizes/order, using the same disjoint primitive and unchanged pre-count/multiply guards. This shares one active pointer grammar without sharing/reordering aggregate validation policy. No legacy caller sees a native/provider callback or a new mutation point. If any replacement cannot retain that precise ordering, stop and review that specific case rather than widening the old validator's accepted inputs/errors. ## Alternatives and required proof An external stack lock cannot be consulted by reentrant backend calls without a new registry/owner indirection; storing its pointer in the backend merely moves the same alias problem. A separately allocated lock adds default allocation and ownership and still needs graph-disjoint preconditions. Caller-only nonreentry weakens the reviewed runtime contract. Requiring explicit options/full preflight first drops approved NULL defaults and does not prove fresh target dimensions. Caching dimensions is stale after resize. None is preferable to the bounded seam. Freeze old validator TU independently (already available), compare exact error/ output bytes for multi-invalid combinations at every ordering boundary, including bad geometry plus aliased sources, invalid style plus overflow counts and malformed context plus poisoned inactive raw text. Test zero-length active context, every selector inactive poison, max/exceeded counts, SIZE_MAX/uintptr wrap, options/list/ array/nested owner aliases, unchanged flags/control/output and zero callbacks. With a fake native-query hook, prove every owner alias rejects before its first invocation; valid inputs reach it exactly once, guard is active during callbacks, and a distinct-frame/same-owner attempt refuses. Then test full SDL/private-Xvfb output/Retina/cache/ABI gates. No production implementation before root review. ## Private implementation checkpoint The private extractor and prequery walker now share the five active-range selectors. Existing full validation uses selectors only at its original alias checks; it does not invoke the aggregate prequery policy. The standalone test links without Core, text or SDL, and a separate TU compiles the immutable pre-extraction validator for error/output comparison. This adds no SDL entry point, native query, support advertisement or public ABI. The first strict build and private-Xvfb run passed both executables, including 216 original-validator comparisons. Additional exact maximum-boundary fixtures are prepared but await the compiler lease; their acceptance is not yet claimed. --- ## Single-selection event facade checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SELECTION_EVENTS_SLICE.md # Single-selection event facade checkpoint Status: reviewed checkpoint. The RadioGroup-only subset is implemented in [SELECTION_EVENTS.md](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SELECTION_EVENTS.md); Select/Combobox and the broader declarations below remain proposals. Audited at `b61a14d0` against the [contract](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_CONTRACT.md), [coverage](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_COVERAGE.md), [bindings](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/COMPONENT_EVENTS_BINDINGS.md), and implemented [metadata](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/COMPONENT_EVENTS.md). Scope is RadioGroup, Select and single-selection Combobox, without changing their reducers, ownership, popup timing or legacy results. No family parity promotion follows from this proposal. ## Source findings | Family | Ownership and dispatch actually implemented | Result/multiplicity evidence | | --- | --- | --- | | RadioGroup Base/Styled | Caller owns `cui_id *selected` and focus state. Without `options.on_change`, reducer writes selection. With it, synchronous callback requests an item; owner accepts by writing `*selected`, or rejects. Later input reads the current owner value, not an immutable entry snapshot. Focus moves even on rejection; semantics/paint use the value after callbacks. | `valid/requested/changed/tab_stop` aggregate one call. Already-selected items do not request. Each eligible event can request; navigation advances from current focus. [header](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_radio_group.h), [Base event loop](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_radio_group.c), [Styled forwarding/paint](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_radio_group.c), [Base tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_radio_group_base.c), [Styled tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_radio_group.c). | | Select | Caller owns selected ID and popup/list state; direct mutation. Public Select has render slots but no value callback. Internal list callbacks exist on `cui_list_options`, which Select constructs privately without activation callbacks. | List returns activation including same-item confirmation; Select closes popup on activation but returns `old != *selected` after the entire list pass. Several list activations can occur before that close; final bool cannot reconstruct transitions or same-item confirmations. [API](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_choice.h), [list reducer](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_choice.c), [popup renderer](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_choice.c), `test_lists_and_popups`, `test_choice_scrolling` and related cases in [choice tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_choice.c). | | Combobox | Caller owns selected ID, query editor, filtered scratch and popup. Query changes independently of committed selection. Base processes query input, computes matching items, then handles Enter; Styled additionally runs a list pass for popup option activation. No public selection callback. | Result contains `changed/query_changed/scrolled/matching_count/error`, without per-transition history. Single Base Enter commit breaks its commit loop. Styled list can process multiple activations. Filtering leaves committed IDs intact. `test_combobox` and `test_combobox_text_enter_order` in [choice tests](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_choice.c) prove query/Enter order and popup state, including Enter followed by text selecting the previous active item. [Base](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/base/cui_choice.c), [Styled](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/components/cui_choice.c). | RadioGroup consumes/cancels accepted item activation before its old callback. Its arrow/Home/End path consumes key-down directly; these are selection navigation, not Core activation. List invokes `on_activate` then `on_confirm` after assigning selection. Navigation/typeahead changes active focus without selection. Combobox Enter is a direct key path, not an activation snapshot. None of these facts permits synthesizing pointer evidence from current pointer position. Existing tests prove legacy behavior, not the proposed facade. They do not yet prove typed evidence copying, callback mutation/consumption, saturated per-event counts, all passive modes, or cross-phase notification ordering. Exact named tests/source above establish those boundaries rather than a claim that bool results uniformly mean CHANGE. ## Recommended smallest compatible slice Add **notification-only** single-selection observers. Keep RadioGroup's old request callback intact, and observe only actual transitions after it returns. Preserve direct mutation for Select/Combobox. A missing observer continues normal behavior; it is not read-only. This differs deliberately from the by-value controlled Check API. Uniform owner-rejectable Select/Combobox requests require a later reviewed controlled entry point; wrapping a local `selected` copy would break same-call focus, popup, semantics and query contracts. Proposed new Base-dependent header `cui_selection_events.h` contains only metadata and pointer-free payload/result types; existing family headers declare forwarding functions. No Components dependency in the common header: ```c typedef enum { CUI_SELECTION_REASON_ACTIVATION, CUI_SELECTION_REASON_NAVIGATION, CUI_SELECTION_REASON_CONFIRM } cui_selection_reason; typedef struct { cui_component_event_metadata event; /* CHANGE only */ cui_id previous, value; /* actual owner values; zero means none */ cui_id item; /* attempted item, distinct from accepted value */ cui_selection_reason reason; } cui_selection_change; typedef void (*cui_selection_change_fn)(void *, const cui_selection_change *); typedef struct { cui_selection_change_fn on_change; void *user; } cui_selection_handler; typedef struct { bool valid, submitted, count_overflow; size_t change_count; } cui_selection_event_result; typedef struct { cui_selection_event_result events; cui_radio_group_result legacy; } cui_radio_group_event_result; typedef struct { cui_selection_event_result events; bool legacy_changed; } cui_select_event_result; typedef struct { cui_selection_event_result events; cui_combobox_result legacy; } cui_combobox_event_result; ``` `change_count` counts actual observer callback invocations, saturating at `SIZE_MAX`. Missing observer preserves ordinary mutation and reports zero. `valid` means preflight succeeded, not that later rendering cannot fail. `submitted` follows existing active-submission policy (disabled can submit, inert/layout-only cannot dispatch). Preserve legacy aggregate results exactly, including surprising differences from transition counts. Payloads omit labels/query strings, indices and borrowed descriptors: IDs remain stable under reorder/filtering, and query text belongs to the edit-event API. An invalid/removed selection stays caller-owned rather than being normalized silently. Exact proposed entry points (arguments intentionally match legacy order, then handler): ```c cui_radio_group_event_result cui_base_radio_group_events( cui_context *, cui_id, const cui_radio_group_item *, size_t, cui_id *, cui_radio_group_state *, cui_radio_group_options, cui_selection_handler); cui_radio_group_event_result cui_radio_group_events( cui_context *, cui_id, const cui_theme *, const cui_radio_group_item *, size_t, cui_id *, cui_radio_group_state *, cui_radio_group_options, cui_selection_handler); cui_select_event_result cui_select_events( cui_context *, cui_id, const cui_theme *, cui_str name, cui_str placeholder, const cui_choice_item *, size_t, cui_id *, cui_choice_popup *, cui_choice_popup_options, cui_selection_handler); cui_combobox_event_result cui_base_combobox_events( cui_context *, cui_id, cui_str name, cui_edit *, const cui_choice_item *, size_t, cui_choice_item *, size_t, cui_id *, cui_choice_popup *, bool disabled, cui_selection_handler); cui_combobox_event_result cui_combobox_events( cui_context *, cui_id, const cui_theme *, cui_str name, cui_edit *, const cui_choice_item *, size_t, cui_choice_item *, size_t, cui_id *, cui_choice_popup *, cui_choice_popup_options, cui_selection_handler); ``` No new Base Select is invented: current Base exposes trigger and list primitives, not a full Select. Implementation needs private observer plumbing into existing reducers, with legacy calls supplying no observer; a wrapper comparing entry/exit values is insufficient. ## Timing, evidence and architectural decisions For each eligible transition, freeze real input facts before calling mutable legacy callbacks; capture `previous` immediately before the existing write/request, run that existing operation, capture `value` immediately afterward, then synchronously notify if different. RadioGroup order is old request callback → new CHANGE observer → remaining events → semantics/paint. Select list order is assignment → existing list activation/confirmation sequence → observer → remaining list events → existing popup close/paint. Combobox Enter order is assignment → existing internal commit callback (where present) → observer → existing close decision. Do not enable observers for multi-select through shared helpers accidentally. Observer payload is an immutable entry-to-observer snapshot. If an observer changes owner selection itself, that write is not another recursively synthesized notification; later events and painting see it according to the existing pointer-owned model. Owner acceptance is not inferred from equality with `item`: a RadioGroup request callback can assign another value, and CHANGE must report that actual value. Rejection with no transition emits no CHANGE. Same-item confirmations and query-only edits emit none. Programmatic assignments outside submission emit none. **Approved decision 1: compound target identity.** `event.target` is the public group/trigger/input ID. `item` identifies the attempted option. A copied `activation.target` remains the actual activated child ID; do not rewrite it to impersonate a trigger. Shared helper `cui_component_event_from_activation` initially copies activation target into metadata target, so compound forwarding assigns the public compound ID to metadata after copying, retaining original activation. This approved convention adds no Core routing mechanism. **Approved decision 2: preserve reducer order, not promise global input-index order.** Styled Combobox runs its Base query/Enter reducer before the popup list reducer. An Enter/text/pointer mixture can therefore yield callbacks in reducer-phase order rather than monotonically increasing event indices. Preserve that existing order and expose truthful indices; do not sort/defer callbacks or replay inputs to manufacture global ordering. Select likewise closes only after its list pass. Any requirement to close after the first activation or unify Combo event phases is a separate behavioral change. For genuine accepted Core activation, retain `cui_activation_snapshot` copied before consumption/callbacks. Navigation and Combo Enter use `HAS_FRAME|HAS_INDEX`, source KEYBOARD, and **no HAS_ACTIVATION**; direct accessibility activation gets only evidence actually supplied by Core. Navigation reason is separate from physical source; touch is retained in real pointer evidence, not a new inferred source. No clock/device fields are invented. Missing evidence is explicit; unknown must not be labeled programmatic merely because a snapshot is absent. The callback, user and payload are borrowed synchronously. Pointer-free copied payload survives context/frame lifetime; caller item arrays, edit/scratch/state, theme/render resources and users must remain valid through active submission/render completion as their existing APIs require. Copy handler/options at entry. Descriptor mutation affects later calls; freeing active arrays/users/state, context destruction, recursive same-frame submission and arbitrary teardown during dispatch remain unsupported. Consume-later-input effects remain observable; there is no prequeued callback batch or fake destruction guard. ## Implementation ownership and meaningful proof Suggested implementation scope, pending approval: new `include/cui/cui_selection_events.h`; narrow declarations in `include/cui/cui_radio_group.h` and `include/cui/cui_choice.h`; private reducer/forwarding changes in `src/base/cui_radio_group.c`, `src/components/cui_radio_group.c`, `src/base/cui_choice.c`, `src/components/cui_choice.c`; new `tests/unit/test_selection_events.c`; human/LLM guide `docs/SELECTION_EVENTS.md`. Root owns module/CMake/generator/SDK/bindings integration. No Core/backend, manifest or existing option/result layout changes. Tests must exercise actual reducers, not fabricated snapshots: - RadioGroup accepted/rejected/redirected old requests, legacy-before-observer ordering/users, selected-item suppression, two arrows advancing focus and per-transition values; old result unchanged. Missing observer retains legacy writes. - Select open→option pointer/touch/key/accessibility selection, multiple queued activations with final value returning to entry (two CHANGE notifications despite false final bool), same-item activation closing without CHANGE, scrolling invalidating old pointer targets, outside dismissal without selection. - Combo query-only edits and filtered-out committed IDs, both existing text/Enter order cases, Enter selection and popup pointer selection, same-item confirmation, phase-order mixed input records, matching/scratch errors, no duplicate events from Base+Styled forwarding. - Freeze activation before old callback consumes accessibility input; keyboard navigation/Enter retain index/source without false activation. Copy payload after frame/context destruction; exact child versus control target convention. Observer consumes later input, updates owner, schedules deferred removal; no reentrant synthesized notifications. - Disabled group/item, empty/all-disabled lists, inert/layout-only/missing invocation, invalid arguments, missing handler, count saturation; legacy suites remain unchanged. Strict C11/C++ public-header compilation and registered headless CTest through `python scripts/test_local.py --build-dir build` only. Deferred explicitly: controlled Select/Combo request/rejection, RadioGroup typed request replacement, query-edit events, same-item ACTIVATE/COMMIT, open/close lifecycle, menu/list/multi-select/tabs/toggle-group facades, async/deferred listeners, foreign-language synchronous requests, bridge typed selection allowlist, label/text copying and uniform 78-family coverage. Existing bridge queued notifications keep their timing and current allowlist. Approved implementation sequence: first RadioGroup Base/Styled only, with minimal shared selection types. Select/Combobox signatures above remain proposals for a separate later slice. No choice reducer edits are authorized by the RadioGroup implementation. RadioGroup implementation exception approved during source proof: its legacy reducer registers current semantics after reduction/callbacks, while `cui_event_activation_snapshot` requires current submitted semantics. Preserve that timing rather than registering early. RadioGroup therefore omits HAS_ACTIVATION on every notification and freezes only actual input frame/index/source facts before callback consumption. Explicit event type proves pointer/keyboard/accessibility source; it does not provide an accepted snapshot or authorize fabricating its coordinates/device fields. The compound/child target convention remains approved for later families where genuine accepted snapshots are available. Early registration is a separate architecture change outside this slice. The implemented minimal shared reason enum includes ACTIVATION and NAVIGATION only; CONFIRM remains deferred with Select/Combobox. Shared results count observer invocations only. The RadioGroup guide/header are authoritative for the shipped subset; no broader signature in this proposal implies implementation. --- ## Select observer implementation checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SELECT_EVENTS_SLICE.md # Select observer implementation checkpoint Approved [selection design](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SELECTION_EVENTS_SLICE.md), narrowed to Select only. RadioGroup is already implemented; Combobox remains deferred. This document fixes private reducer plumbing before production edits. Add `cui_select_event_result` with `cui_selection_event_result events` and `bool legacy_changed`, plus `cui_select_events` matching all `cui_select` arguments followed by `cui_selection_handler`. Use immutable shared `cui_selection_events.h` types and ACTIVATION reason. Missing handler preserves normal caller-owned selection mutation and reports zero callback invocations. No option/result layout is changed. The Styled Select renderer currently constructs private list options and calls `cui_base_list`; that reducer processes the whole event batch before Select closes the popup. Add a private cross-translation-unit forwarding reducer (`cui_choice_private_list_events`, locally declared in Components, not a public application API). Its extra control ID/handler/result pointer observe each actual selection write, after the existing activation/confirmation callback sequence, with frozen pre-callback metadata and pre/post-operation values. Legacy `cui_base_list` calls that implementation with no observer. Only new Select forwarding enables the observer; List/Menu/Combobox/multi-select remain unchanged. No entry/exit comparison can implement this: A→B→A must emit two transitions while Select retains false final `legacy_changed`. Same-item activation closes the popup without CHANGE. Callback updates to owner selection affect subsequent events and final legacy comparison, with no recursively synthesized event. Preserve full list pass, focus/typeahead/scroll logic, and popup close after the pass. No preflight or early semantic registration is added. Like RadioGroup, `cui_base_list` registers option semantics after its reducer. Accepted activation snapshots are normally unavailable before callbacks at this seam. Attempt a genuine existing snapshot only if already available; never register early to obtain one. Otherwise freeze only actual frame/index/source from explicit pointer-up, key or accessibility event type and omit HAS_ACTIVATION. Metadata target is the Select trigger; any genuine copied activation retains its child target. Input source alone does not imply copied coordinates/touch/accessibility snapshot evidence. Handlers/payloads are synchronous borrowed views; pointer-free copies survive frame/context lifetime. Caller storage/resources/users remain alive through existing boundaries. No context destruction guard, recursive submission, queue, retiming, request rejection, lifecycle/confirmation event, query observer or foreign hook is added. Tests must cover real pointer/touch/key/accessibility, multiple transitions returning to entry, handler owner writes/consuming later input, same-item close, disabled/inert/omission, scroll-invalidated pointer activation, legacy coexistence and explicit evidence absence. Root owns registration/generation. Source proof exception: current Core accessibility ACTIVATE allowlist excludes CUI_ROLE_OPTION; FOCUS is supported. This slice preserves that boundary and verifies focus plus keyboard selection, with unsupported activation explicitly documented. Enabling option activation requires separate Core ownership/review. --- ## Settings event checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SETTINGS_EVENTS_SLICE.md # Settings event checkpoint Design only, audited at `ace7190d`. No declarations below are shipped APIs. Preserve the shared component event contract and all existing Settings behavior. ## Existing ownership and callback contract `cui_settings.h` borrows page/group/item arrays, labels, mutable value pointers, editors, control states, dropdown workspaces, custom render/dirty/reset/search callbacks and userdata. `cui_settings_state` borrows page states and optional search editor. Source indices survive filtering; they are positions rather than persistent identities across a caller reorder. Derived control IDs use `cui_settings_part_id` with the compound root and source indices. `cui_settings_filter` validates nested arrays before initialization, chooses the initial page/group, counts matching entries, and reconciles hidden selections. It can call custom `matches` repeatedly. Initial default selection is established before its previous-value comparison. No input evidence exists for this helper; filtering is maintenance, not user navigation or value acceptance. Styled `cui_settings` filters before layout, and filters again immediately after search reduction so same-frame text affects navigation and content. Navigation uses a synchronous private Sidebar `on_activate` callback: set result flag, write page/group, set pending group scroll, invalidate. It is distinct from filter reconciliation. Layout can be stacked or split; the split path records final sidebar width after Resizable and content callbacks return. Search, scrolling, resizing and selection are distinct domains. Built-in field adapters run once in content order. After reducing/painting a field, they record the first edit error, then invoke existing item `on_change` when its old `changed` predicate is true. This predicate is component-specific: Input uses its aggregate changed flag, Checkbox writes its local enum back to the owner, Number additionally applies bounds and updates `last_value`, Dropdown uses Menu or legacy Select. Custom `render` bypasses the built-in adapter and produces no built-in changed result. Presentation callbacks are not event handlers. `cui_settings_reset_page` visits matching items in source order. Custom reset runs instead of the built-in path and returns success without `on_change`. Built-in defaults write/reset, then call `on_change` on successful operation, even if a scalar was already equal. Disabled items are not excluded by this helper. A later malformed group can return false after earlier resets; there is no rollback. Styled reset calls this helper from the existing reset button. Do not infer value change or suppression from its aggregate bool. ## Independently reviewable implementation slices 1. **Navigation only.** Add `cui_settings_events` via a narrow Styled common entry; legacy entry supplies no observer. New handler has only implemented `on_navigation` plus `user`. Payload is pointer-free shared metadata, `{previous_page, previous_group, page, group}`. Notify immediately after the existing navigation writes/invalidation when the pair actually differs. Preserve repeated/net-zero navigation and actual callback counts separately from unchanged `cui_settings_result`. Freeze genuine Sidebar activation evidence before callback writes when available; otherwise use only evidence actually retained by that seam. No invented local input index or source. Filter initialization/reconciliation is silent; do not report it as navigation. Identical-page activation can still update pending scroll under the old path without a navigation CHANGE. Require new compound ID and normal required arguments before any new submission; missing handler preserves all old work. 2. **Built-in scalar values.** Separate typed boolean, double and choice-ID handlers with page/group/item indices and derived field ID. Capture entry values immediately before the old adapter, invoke old `on_change` in exactly its current position, then read the supported final owner and report actual inequality. This intentionally observes callback-driven legacy redirection or cancellation. It is an applied notification, never a rejectable request. No new side-effect replay when reading result counts. Each adapter is an aggregate operation; do not claim per-input multiplicity inside nested controls. Preserve partial-error changes and Number's additional bounds policy. 3. **Built-in text values.** The revised exact proposal below supersedes the earlier before-text snapshot/workspace option. Observe committed revision and byte-count snapshots plus callback-borrowed final UTF-8 after old callbacks. No hidden or caller-required before-text copy, per-input multiplicity or SUBMIT. 4. **Reset observations.** The revised proposal below reuses the implemented typed value observers with explicit EDIT/RESET reasons; no invented reset action or lifecycle event. Preserve all existing helper/callback/order/failure behavior. 5. **Search, resize and viewport.** Audit independently. Search can reuse its actual text revision semantics; width/scroll may need honest aggregate final completion observations. Do not turn filter maintenance into user navigation, final geometry into per-input movement, or render callbacks into change events. No slice changes old public struct layouts, nested state ownership, dispatch, input consumption, acceptance rules, or dependency direction. New typed handlers are synchronous and borrowed for submission. They may copy pointer-free payloads and modify unrelated application flags, but may not mutate/rebind/free active page arrays, values/editors/states, dropdown workspace, labels, callback userdata, input or context. Legacy callbacks keep their existing mutation timing and behavior; they must still preserve storage required by the remainder of the old operation. Omit/remove/destroy after outer return and renderer consumption. No context destruction or recursive UI submission during dispatch. ## Evidence required before each slice ships Keep `tests/unit/test_settings.c`: filter, navigation/fields, search/reset/resize/ scroll, input/number/sizes, Menu dropdown/reset tooltip, design sizes and narrow layout. Add dedicated headless event tests with paired old/new state, owner values, legacy results, callbacks, focus, semantics and draw output. Cover ordered navigation and net-zero transitions, repeated activation, filter reconciliation silence, custom callbacks, partial errors, callback-driven scalar redirects, copy/deferred omission, unsupported active teardown, null observer, disabled and passive paths. Test actual pointer/keyboard/accessibility routing supported by Sidebar; never fabricate accepted evidence or promise support from compilation. Native Linux runs through `python scripts/test_local.py --build-dir build`. No desktop windows. Strict C11/C++ headers and warnings are required. ## Binding omissions `bridge_render_settings` builds separate owned pages and field callbacks, then calls old Styled Settings. Field callbacks enqueue existing generic bridge changes; final page selection is compared after the complete operation. Errors return before final page notification. Existing Python/JS/TS/Go/Rust wrappers do not expose this proposed immediate navigation or field observer, source indices, per-navigation counts, reset reasons or synchronous requests. New opt-in scalar/ text polling does not automatically classify Settings or its nested item slots. Document and test any bridge extension separately, without changing old queue order, after-mutation semantics or foreign lifetime contracts. ## Navigation implementation checkpoint The first slice implements only Styled `cui_settings_events` navigation. Its private per-trigger descriptor uses a monotonic actual-activation lookup matching Sidebar's synchronous per-item callback loop; accepted snapshots are copied before writes. This is evidence lookup only, without Sidebar modification or replay. Unexpected mismatch retains only proven frame/UNKNOWN evidence. Notification follows original pair/pending-scroll writes and invalidation, before content. Existing item traversal order (not global event order), filter repairs and all field/reset paths are preserved. No unimplemented scalar/text/reset handler fields were added. ## Scalar implementation checkpoint The second slice adds only boolean/double/choice-ID field observers. Each existing built-in adapter captures entry immediately before reduction, preserves error and old on_change timing, then observes actual final owner inequality. Number finite flags report nonfinite callback redirects; two NaNs and signed zeros are equal. Disabled/passive/inert maintenance remains unobserved without changing old writes or callbacks. Aggregate field metadata is frame-only UNKNOWN, with compound target and separate derived field ID/source indices. No input reconstruction or text/reset observer was added; custom render overrides remain outside built-in scalar hooks. New handler/result fields require consumer rebuild; old legacy layouts stay intact. ## Revised text/reset checkpoint — design only This section proposes the next slices; it does not declare shipped APIs. The navigation/scalar checkpoints above describe their prior implemented scope. No production, generated or binding files change in this revision. ### Exact text API and compatibility In `cui_settings_events.h`, propose: ```c typedef enum { CUI_SETTINGS_CHANGE_EDIT = 0, CUI_SETTINGS_CHANGE_RESET } cui_settings_change_reason; typedef struct { cui_component_event_metadata event; cui_id field_id; size_t page, group, item; uint64_t before_revision, after_revision; size_t before_bytes, after_bytes; cui_str text; /* final committed UTF-8, borrowed only through this callback */ cui_settings_change_reason reason; } cui_settings_text_change; /* Append to the new handler: */ /* void (*on_text)(void *, const cui_settings_text_change *); */ /* Append to the new event result: size_t text_count; */ ``` Append `reason` to the existing new bool/number/choice payloads as well. Existing adapter notifications use EDIT; reset observations use RESET. Navigation has no reason change. These event structs/handler/result are **unreleased** additions: changing their ABI requires rebuilding all consumers/generated copies before a release. Use designated initializers. EDIT=0 preserves zero/default interpretation; there is no claim of binary compatibility with the preceding event-struct layout. Do not change old Settings functions/options/state/result or old callback types. Add fields only with the independently implemented slice, not reserved stubs. `cui_settings_events` keeps its signature; on_text shares the existing handler user. Capture the Input editor's `cui_edit_get_state` revision/length immediately before the old built-in adapter. Run the same Input once, preserve its aggregate error and old on_change predicate/timing, then read the **same still-live editor's** final state and `cui_edit_get_text`. Emit zero/one text CHANGE if revisions differ, even when old changed is false or a later edit error exists. The final byte count equals text.length; before_bytes is the old committed UTF-8 length, not characters/caret. Use revision inequality, not ordering/subtraction. Multiple changes/undo/redo can end with identical bytes but a different revision; that is one revision-change notification, not proof of differing old/final strings. No before string, changed range, selection transaction, request, COMMIT or SUBMIT is promised. The callback follows old on_change, so it observes callback-driven committed edits and redirects, including undo to the prior bytes. Only actual revision difference matters. Selection/scroll/caret changes and IME preedit without committed revision change are silent; commit/undo/redo may notify. Do not reposition old paint or rerender to match callback-redirection text. Preserve the first aggregate edit_error exactly; unchanged revision on failure is silent, changed revision before/through an error is still notified. Legacy callback edit errors are not reconstructible from its void return and must not be invented in the payload/result. EDIT metadata stays frame-only UNKNOWN, compound target plus explicit field ID and source indices. A whole Input plus host callback is not a unique input event. Enabled only: preserve disabled/passive/inert old work while suppressing new EDIT notifications. Custom render overrides remain outside built-in text observation. Settings supplies no secure/masked Input option; this proposal exposes committed bytes and adds no implicit password redaction or before-text retention. Payload pointer/text are borrowed only during callback. Copy text using existing `cui_component_event_copy_utf8` with caller maximum/capacity; failure is atomic, no truncation/allocation. Copying the struct retains only a borrowed string pointer. Legacy callbacks must leave the editor/owner storage readable through the typed notification, and must not replace/destroy the editor while the opted-in operation is active. Typed observers cannot edit/rebind/free active resources, submit UI, change input or destroy context. Unrelated flags allowed; defer omission/teardown until outer return plus frame/render consumption. No new runtime guard is implied. ### Reset helper and exact observation order Current authority is `src/base/cui_settings.c:reset_item/cui_settings_reset_page`: custom reset wins first and returns true without old on_change; otherwise missing default/custom_item returns false. Built-in bool/double/choice writes and successful text replace call old on_change even if the value/revision was already unchanged. `cui_edit_replace_range` can accept same bytes without revision increment (while changing selection). Matching is evaluated once per visited item in source order; disabled is not a reset exclusion. A malformed later group's nonnull-count/null- items case immediately returns false, discarding the aggregate earlier-success bool but not earlier writes/effects. Failed item text replacements return false and do not call old on_change; subsequent items still run. No transaction/rollback exists. Propose an additive helper using the **same** typed field handlers: ```c typedef struct { bool reset; /* exact legacy helper bool, including false after progress */ size_t boolean_count, number_count, choice_count, text_count; bool count_overflow; } cui_settings_reset_event_result; cui_settings_reset_event_result cui_settings_reset_page_events( cui_id root, size_t page_index, const cui_setting_page *page, cui_str query, cui_settings_handler handler); ``` Root and page_index are necessary: the old single-page pointer has neither a root identity nor its position in a host page array. Require nonzero root and nonnull page before invoking the old common helper; invalid new admission returns a zero result. The caller supplies the truthful source page index; no invented zero index, global ID lookup, artificial page cap or context is introduced. Group/item indices come from the existing loop. Preserve old page/query/no_reset validation and all matching calls. Missing handlers still execute the same resets; navigation handler is ignored by this helper. Keep old helper signature/return and no-observer path. At each matching **built-in** reset, capture the corresponding scalar or text revision/byte snapshot, run exactly the existing reset and old on_change sequence, then notify actual final inequality/revision difference with reason RESET. Reuse the same equality, finite flags and typed payloads; Number reset does not introduce bounds checks or update number_state.last_value. Same-value successful old callbacks still run: no typed event if final value remains equal, but callback redirect to a different final owner does notify. Text replacement rejection with no revision change emits none. Do not gate observation on helper aggregate bool or operation success: delivered callbacks/counts survive a later false return. This helper retains only the old reset bool, not a fabricated per-item error/atomicity guarantee. A custom reset stays an explicit typed-value omission even if an item also has a scalar pointer: arbitrary host reset may affect multiple owners or replace its own model, and its opaque callback has no typed return/lifetime contract. Invoke it once, preserve true/no-old-on_change, emit no built-in typed RESET. Custom render alone does not override reset: when reset==NULL, has_default is true and custom_item is false, existing built-in reset still applies and can be observed. No-default and unmatched items remain untouched/silent. There is no reset ACTIVATE, LIFECYCLE, COMMIT, synthesized request or new standalone reset callback. Programmatic helper metadata is known PROGRAMMATIC source, compound target, **no frame/index/activation** (the API has no context). Typed RESET intentionally reports actual built-in changes to disabled items too: explicit reset already includes them; this is not a disabled-input event. This differs deliberately from EDIT suppression. Custom reset's omission does not alter reset bool, old effects or source order. ### Styled reset composition Use a private common reset implementation/evidence argument, not a call to the new programmatic public helper that would mislabel UI reset as PROGRAMMATIC. Existing Styled button_ex runs once at the same header point; keep result.reset assignment and complete all matching resets before old content proceeds. Freeze cause before the first reset write: if there is exactly one actual matching button activation and its genuine accepted snapshot is available, copy it, retaining the reset button's original activation.target while event.target remains Settings. Multiple coalesced activations or unavailable evidence get only proven active frame/UNKNOWN, never a guessed first/last event. No early registration/replay/consume. New metadata kind is CHANGE, reason RESET; accepted activation is supporting evidence only. Suppress new Styled RESET observations for passive/layout-only/inert work while preserving any old writes/callbacks. Active reset still includes disabled items. Reset is before the field adapters. Therefore default Number20 can produce RESET 3→20, then the old later Number bounds pass can produce EDIT20→10 in the same call; text formatting/host redirects can similarly create later adapter work. Preserve and document these ordered operations rather than collapsing them or mutating last_value/drafts early. Navigation counts/results stay independent. Reset errors are not added to old Settings edit_error: only existing adapters set that field. ### Independent proof and proposed ownership Implement text EDIT first; then reset helper/Styled composition in a separate verified commit. Extend only the existing Settings event header/common Base reset seam/Styled seams/test/guide/proposal and discovery comment after approval; root owns wiring/generation. No Core/Input/editor mutation redesign or bridge change. Pair old/new complete operation outputs/state/callback counts and paint timing. Text tests: real text/paste/multi-input, IME preedit/commit/cancel, undo/redo and same-byte revised text, legacy on_change redirect, failure after earlier committed mutation, unchanged failure/selection-only silence, null handler, disabled/passive/ inert, custom render omission, exact UTF-8 byte counts, bounded copy success/failure, borrowed pointer versus owned copy, deferred omission and model lifetime limits. Reset tests: programmatic no-frame PROGRAMMATIC metadata; Styled unique real snapshot versus multi-activation honest fallback; source-index IDs; match order/disabled/ no-default/no_reset policy; built-in same-value old callbacks with and without redirect; text acceptance/presentation/capacity failures followed by later items; custom reset true/no-old-on_change/no-typed-event; malformed group after earlier observations returning false with retained counts; Number nonfinite defaults/finite flags/unchanged state synchronization; same-frame RESET then EDIT order; copied scalar/text payload lifetimes; null handlers and passive UI suppression. Existing Settings/Input/Number/Choice/edit acceptance regressions remain mandatory through the private wrapper, plus strict C/C++ headers. No foreign wrapper or full parity claim follows from those checks. No builds or production changes in this revision. ### Text EDIT implementation checkpoint Implemented the approved built-in Input aggregate EDIT seam after old callbacks. The text payload/count and unreleased reason fields are present; RESET remains the next independent implementation slice. Strict tests compare old/new state, paint, semantics and errors, including multiple inputs, callback redirect, byte-net-zero revision changes, IME preedit/commit, progress before capacity error, absent observer, passive/inert/disabled silence and bounded copy. No reset implementation or wrapper support is implied by this checkpoint. ### Programmatic reset implementation checkpoint The explicit helper now shares the exact old traversal/reset operation, with optional final-owner observations after legacy callbacks. No reset-button wiring is claimed yet. Tests cover ordered callbacks, same-value defaults, disabled fields, custom-reset exclusion, nonfinite callback redirect, partial progress then malformed group, text capacity failure, missing handlers, copied text and atomic root admission. Programmatic metadata has no UI evidence. ### Styled reset implementation checkpoint The old reset-button aggregate now calls the same optional observation seam once. Evidence is frozen before writes: one actual matching activation with accepted snapshot is copied; ambiguous/missing evidence gets frame-only UNKNOWN. Tests compare legacy and opt-in state, paint, semantics, focus, errors and callbacks; cover disabled-field inclusion, single/repeated keyboard activation, real copied snapshot identity, RESET20 then bounded EDIT10 order, missing handlers, text reset and passive/inert silence. No new dispatch, filter/reset policy or wrapper support. --- ## Component shadow ownership: first rollout proposal Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SHADOW_COMPONENT_OWNERSHIP.md # Component shadow ownership: first rollout proposal Audit: fb3be922 plus named-element shadow slice c872cb4a. The first approved root/existing-part slice is implemented; anonymous-part and binding rollout remain proposals. Evidence below describes the actual tested entry points. The Core setter accepts current-frame paint IDs, not arbitrary semantic handles. All rows below require component-owned acceptance tests before coverage is claimed. ## Concrete root and part inventory | Family / entry | Current painted target | Limits / source evidence | | --- | --- | --- | | Button / button_ex / styled | caller `id` | `cui_components.c:609` opens resolved root with this ID; wrappers reuse painter. Custom content is inside it. Radius follows resolved style, not necessarily theme radius. | | Input / input_ex / input_paint | caller `id` | `cui_components.c:2579` opens actual framed/clipped root. `cui_input_viewport_id(id)` is already public, but is inner text viewport, not surface. No-appearance remains a transparent caster unless explicitly styled. | | Checkbox / checkbox_ex / source | caller `id` is whole label/content row | `cui_components.c:1323–1329`: column, optional spacer and actual square indicator are anonymous. Shadow on caller ID covers label too. Indicator callback runs while indicator is open but replaces default glyph composition; not a general post-submission part API. | | Radio / radio_ex | caller `id` is whole row | `cui_components.c:1875–1883`: anonymous column/spacer/circular indicator. `cui_radio_group.c:54–60` independently paints item rows and anonymous indicators; do not infer group parity from radio_ex. | | Switch / switch_ex | caller `id` whole row; public `cui_switch_track_id(id)` and `cui_switch_thumb_id(id)` are real named boxes | `cui_components.c:1436–1439,1544–1574`; legacy wrapper delegates ex at1625. Track owns clip; thumb shadow is clipped by track. Root shadow includes label. No new part identity needed. | | Slider / cui_slider | caller `id` framed label/control; track already named privately | `cui_components.c:2079,2085`; track uses existing owner-derived ID; fill is anonymous, conditional on positive ratio. This entry has no independent thumb box: do not invent thumb support. | | Avatar / avatar_ex / events | caller `id` circular outer surface/ring | `cui_content.c:109,265–289`; image child has separately derived ID via private helper, image may be absent; outer root handles ring/focus. Stack children are another API, not covered by single-avatar evidence. | | Badge / cui_badge | caller `id` is colored pill | `cui_components.c:1914`. | | Badge / cui_badge_ex | caller `id` wraps content; visible indicator already named privately | `cui_components.c:1939–1982`: separate absolute overlay and indicator. Root shadow includes wrapped application content. Count0 omits indicator; dot/icon show independently. Indicator has existing STATUS semantics, not a new shadow input target. | | Popover / cui_popover_begin | `state.overlay.id` is panel portal | `cui_surface.c:160,189,218–233`; begin opens nested body, so open-box setter immediately after begin styles body instead. Apply named setter after surface submission (or end). Refined panel already may have copied shadows: explicit assignment replaces list. | | Dialog / cui_surface_begin with DIALOG state | `state.overlay.id` is panel portal | Same surface implementation. Separate backdrop, resize, close/title/body parts; `cui_surface_part_id` documents1..8 (`cui_surface.h:162–164`). None is an alternate alias for the panel root. | | Tooltip / cui_tooltip | caller tooltip `id` is popup portal, only when function returns true | `cui_content.c:1100,1128–1134`; `options.trigger` is a different owner. Inactive/delayed/omitted tooltip has no current-frame panel. Tooltip-events entry follows same panel path; HoverCard is separate contract. | Paths above are relative to `src/components/` except named headers. Existing part helpers return identity, not evidence that a part was emitted this frame. The Core setter supplies current-frame presence validation. Do not call it on absent conditional parts and treat INVALID_ACTION as ordinary application success. ## Independently reviewable first ownership slice Start with explicit root contracts/tests for Button, Input, Avatar, simple Badge, Switch track/thumb and surface/tooltip panel targets. They need no new identity, Core registry, pending-style mechanism or widget struct layout. Document the actual root, radius choice and lifecycle alongside its authoritative header. Root Button/Input/Avatar and legacy Badge IDs already need no identity getter. Popover/Dialog use public state.overlay.id; Tooltip uses its caller ID. Avoid redundant aliases that imply a semantic ID is universally a painted surface. Add only two pure public part getters initially: ```c /* Proposed, not implemented. Return0 for owner0. Identity only, no presence check. */ cui_id cui_badge_indicator_id(cui_id owner); cui_id cui_slider_track_id(cui_id owner); ``` Internally centralize the existing derivations and replace the current literal calculations with these getters. Do not alter assigned IDs, element count, clip, paint, semantics or event ownership. Badge's existing overlay ID need not become public until a real styling use and tests establish its empty-layout behavior. A slider fill/knob getter is not part of this slice. Existing switch getters remain unchanged. Public IDs remain stable contract; users never need private XOR salts. Acceptance tests must submit each entry in a real frame, apply a distinctive copied layer after composition, and verify caster matches the intended surface rather than content row/viewport/trigger. Include actual software pixels, rounded geometry, both positive/negative spread, inset and DROP, ancestor clip, opacity, current-frame resize, supplied image/ring Avatar, custom Button style, Input no-appearance, Switch thumb clip and Badge0/1/dot/icon visibility. Portal tests assert panel styling changes neither backdrop/arrow nor trigger paint and does not change modal dismissal/activation. Verify same IDs, element/semantic counts, legacy command lists/pixels and queued interactions with no shadow opt-in. Getters need deterministic0 handling, owner separation, actual emitted-ID match, no duplicate registration and explicit adversarial collision/capacity tests. Test existing IDs before/after refactoring, not merely getter arithmetic copied into expectations. Test conditional Badge absence before calling the element setter; separately assert missing target rejects atomically. Report entry coverage, not family completion for every variant. ## Anonymous indicators: separate approval boundary Checkbox and Radio require an additive opt-in composition route exposing stable indicator identities. Do not silently name anonymous boxes on every legacy call: that changes registered ID capacity/collision behavior and descendant auto IDs. First audit both individual Radio and RadioGroup painters, plus Checkbox custom indicator/state paths. Proposed next decision: an additive named-parts entry point or explicit part descriptor passed to a new variant; original public options layouts and all old call paths remain unchanged. Only the opted-in route assigns indicator IDs; glyph decoration remains passive and uses the existing one reducer. No global registry, pending-next-box style or new input dispatch is required. Before approval, specify owner0/part collision rejection, custom indicator presence, stable identity across checked/mixed/error/disabled and item reorder, and failure atomics. Tests must compare old path commands/pixels/layout/input/semantics exactly, then prove opt-in identity adds no nodes or focus targets, retains clipping/radii, and explicitly accounts for extra named-ID slots and new collision opportunities. Do not claim anonymous parts covered because the whole row can cast a shadow. ## Foreign-language authoring route Current bridge enum has the requested widget kinds (`include/cui/cui_bridge.h`), but its internal retained node (`src/bridge/cui_bridge_internal.h`) has no shadow property. Submission is centralized in `src/bridge/cui_bridge.c`: Tooltip at4398, Surface at4423, Input at4580, Switch at4652 and Button at4695. This is a concrete shared integration point for Python, Node, TypeScript, Go and Rust builders. Propose a new additive bridge shadow setter with generation-checked node handle, explicit target enum ROOT/known typed PART and bounded record array. Validate and copy all <=8 typed records into bridge-owned node storage immediately. A dedicated boolean distinguishes no override from explicit empty override; an empty override clears component defaults, while removing the override restores defaults. Keep legacy bridge structs/ABI version1 layouts stable by adding functions/new records, not growing existing wire structs. Records carry finite float offsets, sigma, spread, RGBA bytes and fixed-width kind; bindings must not cast host-language arrays to arbitrary C layout. Existing Core kinds/presets and CSS factory provide validation/conversion; do not parse CSS strings or reinterpret sigma. Resolve each typed target in that component's actual frame submission, then apply a copied value list after its painter closes. A retained builder property is not a call to Core before a frame exists. A hidden popup keeps its owned requested style but emits no setter until its panel is submitted. Present-but-unsupported parts reject at bridge authoring; known conditional parts can be dormant and activate on later visible submission. Define that distinction explicitly, instead of converting every Core INVALID_ACTION into silent success. Deletion/reuse drops old style with the generation; update failure leaves prior node style intact. Expose matching typed `ShadowLayer`/preset/CSS-constructor helpers plus node shadow/clear/reset methods in all five facades. Switch/Badge/Slider part selectors must match the reviewed public ownership API; Checkbox/Radio indicators stay unsupported until their opt-in composition route is integrated. Contract tests exercise copying, stale handles, all kinds/counts, preset replacement, empty vs unset, invalid transaction, popup hide/show and real target pixels through each language. Bundled Go/Rust C source alone remains insufficient binding evidence. ## Proposed beta-roadmap status - Delivered: portable eight-layer DROP/INSET renderer capability, named presets, current-frame named-box addressing and explicit CSS blur conversion. - Next independently testable slice: common painted roots plus existing named Switch parts and additive Badge-indicator/Slider-track getters. - Pending: anonymous Checkbox/Radio indicators and remaining78-family part audit; owned typed bridge and Python/Node/TypeScript/Go/Rust authoring; cohesive visual examples and relevant headless/browser evidence. The beta target remains consistent style selection across applicable component paint parts and bindings. The generic C API is an enabling slice, not completion of that target. Host/behavior-only families still need an explicit not-applicable caster decision rather than fabricated rectangular surfaces. No compilation, renderer work or generated consumer resources are changed by this proposal. ## Approved first ownership contract The first implementation centralizes Badge_ex's existing visible indicator ID and cui_slider's existing track ID behind checked pure getters. Each returns0 for owner0; nonzero owners retain exactly their current derived IDs. The functions report identity only. No anonymous boxes receive IDs, no component nodes are added, and old behavior/pixels/semantics remain unchanged absent explicit styling. Authoritative header comments identify actual surfaces: Button, Input, Avatar and legacy Badge use caller ID; Checkbox/Radio caller IDs denote whole rows; Switch has existing track/thumb getters; Slider exposes track but no thumb; Badge_ex's caller ID wraps content and its indicator can be absent. Popover/Dialog panels use state.overlay.id and Tooltip's emitted popup uses its caller ID. Tests style these current-frame paint targets after their owner submits them. Corner radii remain explicit caller style values, not inferred from a semantic record. New getter validation does not change old zero-ID submission behavior: composition uses the existing internal derivation while public getter0 returns0. Collisions must still be rejected by existing Core identity validation. No all-family or foreign-language style support is implied by this additive C-only contract. ## First ownership implementation evidence The Badge indicator and Slider track getters centralize existing assigned IDs; they add no paint/layout/semantic nodes or new dispatch path. Header comments and consumer metadata identify actual root/part ownership. Tests freeze preexisting ID values, reject owner0/derived0 as style targets, check omitted count0 Badge and existing application/part collision rejection. Slider's legacy owner0 painter keeps its original track derivation, independent of checked getter0 behavior. `test_component_shadow_ownership.c` exercises Button_ex with custom rounding, Input_ex framed and no-appearance, Avatar_ex initials and actual copied photo cache/ring, legacy Badge, Switch_ex track and thumb, Slider track, and Badge_ex count/dot/icon indicators. Actual tracked current-frame bounds match emitted mixed DROP/INSET casters; software output changes under opt-in and returns exactly to default after clear. Cases cover movement, applicable resizing, ancestor clip/opacity, unchanged semantic IDs and real queued Switch activation with and without track styling. Text commands are omitted from font-free software raster oracles; actual layout uses an explicit measurement callback, not fabricated glyph rendering or source typography claims. Popover (anchored with arrow), Dialog and focused Tooltip tests separately prove panel caster ownership, conditional tooltip omission, unchanged semantic IDs/roles and preserved trigger/backdrop/arrow paint. An early Tooltip assertion exposed a legitimate command-placement distinction: explicit CUSTOM shadow paint emits the background before child-overflow clip, while ordinary rectangle paint can be inside that clip. The test does not require these active opt-in wrapper positions to be identical. Instead an independent ordinary-only software render removes shadow commands and compares every RGBA byte to the unstyled baseline, including all ancestor masks, trigger, backdrop and arrow. Cleared/unmodified frames retain full ordinary-command order/bounds/colors and identical software pixels. Focused strict Release build/tests use the existing build-shadow directory, nice19, CPU0 and -j1. The new ownership and existing element-shadow tests passed 2/2 through private Xvfb. Source SDK/distribution/skill resources are generated by canonical tools. Installed-skill tests passed17/17; SDK checksum, amalgamation, skill freshness and78-entry manifest checks passed. No browser, native GPU, full-78-family, anonymous Checkbox/Radio indicator or typed binding completion evidence is added by this slice. --- ## Sidebar event checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SIDEBAR_EVENTS_SLICE.md # Sidebar event checkpoint Activation, item expansion and collapse Base/Styled slices implemented in this branch; see [Sidebar events](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/SIDEBAR_EVENTS.md). Header/footer action forwarding is implemented in the final independent slice. Original audit: `2d7e16d1`. Activation, expansion and collapse payload/handler/result types are exposed now. Preserve the shared component event contract, existing public layouts and all old callbacks/results. This is an additive seam proposal, not new input routing. ## Existing source contract `cui_sidebar.h` separates retained virtual layout/cache state from immediate menu items, header/footer actions and a controlled collapse toggle. Entry render and icon/label/suffix/context callbacks are composition, not behavioral events. `cui_sidebar_prepare` reconciles bounded cache/motion; collapse options are owner-supplied. Its successful bool is not an activation or value notification. Base item validates ID/label/state, initializes uncontrolled open state, registers TREEITEM and optional Button caret semantics, then loops existing inputs in index order. Row invocation can open/toggle the submenu before old `on_activate`. Caret invocation only changes expansion. `cui_sidebar_set_open` writes internal `state.open` only when `expanded == NULL`, then invokes old `on_expand` in either mode. With `expanded != NULL`, it never writes owner storage: old `on_expand` is a request and the owner can accept/reject synchronously. The next event rereads the actual owner; no optimistic request state is retained. Final result/semantics read owner state again. `expansion_changed` records attempts, not owner acceptance. The Styled menu traverses items/visible children in source order, reducing and painting each item before the next. Thus callbacks across items are traversal ordered, and local input indices can decrease. An observer must not sort or defer this sequence. Custom rendering and context composition retain their old positions. Base collapse toggle registers a Button, starts a local bool at options.collapsed, and flips that local bool for each matching activation before old `on_change`. This is a sequence of requests from by-value options, not applied owner writes; callback-driven external updates do not replace the local sequence mid-call. Styled toggle reduces once before paint. Header/footer actions use pointer-only semantics, existing item-specific focus scope and old callback before content. Their successful bool means valid submission, not action count. ## Proposed additive types and functions New `cui_sidebar_events.h` includes Sidebar plus shared metadata: ```c typedef struct { cui_component_event_metadata event; cui_id item; unsigned level; } cui_sidebar_activation; typedef struct { cui_component_event_metadata event; cui_id item; unsigned level; bool previous, value; } cui_sidebar_expansion_event; typedef struct { void (*on_activate)(void *, const cui_sidebar_activation *); void (*on_expand_request)(void *, const cui_sidebar_expansion_event *); void (*on_expand_change)(void *, const cui_sidebar_expansion_event *); void *user; } cui_sidebar_item_handler; typedef struct { cui_sidebar_item_result control; size_t activation_count, request_count, change_count; bool valid, count_overflow; } cui_sidebar_item_event_result; ``` First expose only the implemented subset of these fields. Add Base `cui_base_sidebar_item_events(ui,item,collapsed,level,handler)` and Styled `cui_sidebar_menu_events(ui,id,theme,items,count,collapsed,handler)`. Menu result has legacy submission bool plus actual callback counts and validity; it must not pretend to return one item's final open state. Base event.target is item ID; Styled menu uses compound menu ID, preserving original copied activation.target. Payload item/level identifies the actual affected row. Source array index is not needed as identity. No extra workspace or retained handler. For toggle, propose distinct typed collapse request `{event,previous,value}` and handler/user plus result `{activated,request_count,count_overflow,valid}` on `cui_base_sidebar_toggle_events` and `cui_sidebar_toggle_button_events`, with existing arguments plus handler. Collapse is not expansion: retain separate names. Header/footer additive entrypoints use the action payload/count convention with existing options plus action handler; do not expose unimplemented fields early. ## Narrow timing and ownership seams 1. **Item activation first.** Freeze accepted activation evidence at the existing row branch before expansion/old callbacks. Invoke typed ACTIVATE after the old `on_activate`, preserving expansion-before-activation ordering. Repeated same row invocations all notify, including when old callback is absent. No action for caret-only toggle, passive/disabled/inert work or successful paint alone. 2. **Item expansion separately.** Capture actual before and requested next plus cause before the old set-open operation. Run its write/old callback once. Controlled mode then invokes typed REQUEST, allowing that specific handler to assign the same controlled expanded bool synchronously. No input-consumption, propagation or default-prevention decision follows from that assignment. Uncontrolled mode instead reads actual state.open after old callback, invokes typed CHANGE only if before differs, and forbids observer model mutation. Do not label a controlled request an applied change, even if an earlier legacy callback already accepted it. Do not emit initialization/default maintenance. Old callback -> typed expansion -> old activation -> typed activation remains synchronous. Capture evidence once and reuse it across related notifications. 3. **Collapse toggle separately.** Preserve the exact old local flip sequence; old on_change then typed REQUEST for each actual activation. Handler may update unrelated owner state/options for the next submission, but cannot mutate the active copied options or infer confirmed state. Missing callbacks preserve the old reducer/result. No after-frame dispatch or controlled-state architecture. 4. **Header/footer separately.** Existing old action then typed ACTIVATE before content rendering, pointer-only semantics unchanged. A typed handler may act without an old callback on the additive entrypoint; old entrypoint remains byte/behavior equivalent. No keyboard/accessibility support is invented. Try actual Core accepted snapshots while current semantics already exist; preserve original target/frame/index/source. If unavailable, carry only proven actual local index/type/frame. TEXT never implies keyboard. No early interact, extra reduction, synthetic activation or global capture/bubble. Input consumed/default state stays unchanged. Menu validation/recursive traversal and final semantics/paint remain at their existing positions. Callback-visible arrays/geometry may be intermediate. All new handler/user/payload pointers are borrowed during submission. Pointer-free payload copies survive omission and owner teardown; handles do not own live rows. Only the controlled REQUEST handler may update the explicit expanded bool under its documented narrow permission. Otherwise no active item arrays/labels/child state/userdata/input mutation, recursive UI, context destruction or storage removal. Legacy callback mutation behavior is retained. Defer structural changes and resource teardown until outer return and renderer consumption. Retained Sidebar entry/cache/header/footer content lifetimes are unchanged by immediate observers. ## Independent evidence and binding omissions Keep `test_sidebar.c` and Settings regressions: Settings uses these existing callbacks and must not acquire duplicate actions. Add dedicated headless tests: old/new results, state, callback trace, focus, semantics and draw equivalence; repeated/net-zero inputs; old and typed handlers coexisting; request acceptance, rejection and redirection separately from consumption; internal open-state legacy redirection; default/disabled/inert/passive/collapsed/disable-caret policy; item traversal with decreasing input indices; copied metadata/lifetime/deferred removal. Exercise actual pointer/keyboard/accessibility paths only where Core supports them; TREEITEM role alone does not prove accessibility ACTIVATE. Header/footer remain pointer-only. Toggle tests must preserve by-value local request alternation. Strict C11/C++ headers, warning builds and private-Xvfb native tests are required. Bridge Sidebar has its own retained menu/control state and queued callbacks. No Python/JS/TS/Go/Rust builder automatically acquires immediate typed requests, per-item metadata or synchronous acceptance from these C facades. Existing generic queue timing, copies and lifecycle remain separate, with explicit omissions. No source manifest promotion or new dependency follows from this checkpoint. ## Activation implementation checkpoint The shipped activation names match this proposal. The menu result is named `cui_sidebar_menu_event_result`; its `submitted` field is the old submission bool, not an aggregate action. `valid` records argument/tree validation. Header discovery includes the new standalone `cui_sidebar_events.h`; old public layouts are unchanged. Actual snapshots are copied before legacy callbacks. A tested accessibility-focus then Enter sequence lacks a current accepted snapshot, so only genuine keyboard, frame and index metadata is carried there. TREEITEM ACTIVATE is rejected at ingress. Generic consumption of later ordinary mouse events does not cancel cached activation; explicit cancellation does. Both legacy outcomes remain unchanged. These are existing Core facts, not new acceptance/propagation rules. Expansion fields have now been appended to the unreleased handler/results as approved; rebuild consumers. Section event fields remain unexposed. ## Expansion implementation checkpoint Controlled REQUEST runs after the legacy on_expand with frozen previous/requested values, regardless of earlier acceptance; only its explicit owner bool may be assigned. Uncontrolled CHANGE reads actual state.open after the legacy callback, suppressing redirected net-zero transitions. Existing attempt flags remain unchanged. Shared evidence is frozen before any legacy callback and reused for related row activation; caret evidence retains its actual Button identity. Tests prove both controlled acceptance paths/rejection/repeated requests, precise synchronous order, legacy cancellation after capture, missing observers, caret accessibility/touch, passive work and Styled compound forwarding. This is an unreleased struct extension, not an ABI-preserving change to a published event handler. Legacy Sidebar layouts are unchanged; header/footer remain a separate review checkpoint. ## Collapse implementation checkpoint Separate `cui_sidebar_collapse_request`/`cui_sidebar_collapse_handler` and `cui_sidebar_toggle_event_result` support Base `cui_base_sidebar_toggle_events` and Styled `cui_sidebar_toggle_button_events`. Requests follow the legacy local flip sequence from entry options, old callback then typed callback per activation. External owner assignment is permitted but never redirects that local sequence. Semantics and Styled paint retain the entry snapshot, including after acceptance. No collapse CHANGE, callback reconstruction from aggregate bool or hidden resync. Bounded tests compare actual old/new callback values and Styled geometry, repeated requests, divergent owner writes, entry semantics, genuine pointer/touch/key/Button accessibility, inert/layout-only/disabled/missing handlers and copied lifetime. Header/footer were subsequently approved and implemented; see the routing correction below. ## Header/footer routing correction and implementation The earlier pointer-only description was incomplete: existing GROUP sections set `pointer_activatable`, which Core's accessibility eligibility explicitly accepts. The additive Styled-only `cui_sidebar_header_events` / `cui_sidebar_footer_events` therefore preserve pointer, touch and accepted accessibility ACTIVATE. No keyboard activation routing or Base section API is introduced. Shared activation handlers and action results report actual observer calls, after each legacy callback; metadata is frozen beforehand. Legacy entrypoints retain their original path. --- ## Skeleton parity checkpoint Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SKELETON_PARITY_CHECKPOINT.md # Skeleton parity checkpoint Source-only audit at CUI `956a853c`. No production, manifest, generated output, compiler or runtime changes; existing evidence below was inspected, not rerun. Keep the family open for the identified theme/layout/binding work. A `tested` manifest row is not a claim that every source feature or platform is complete. ## Frozen authority upstream Kit0.7.1 commit `87d10ae5e1299d1be18670a37570c5402f952e34`: | Primary file | SHA256 of fetched exact bytes | | --- | --- | | [Skeleton source](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/crates/component/src/skeleton.rs) | `1f8818cef643e2e7160151be4516331f28cddd255762d1bd0af2777561073c8d` | | [Component guide](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/website/component/skeleton.md) | `da87bfccdb5f32831a146db75706f6b41aa5f511fab70956142ea8fac3fa4adb` | | [Theme schema](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/crates/component/src/theme/schema.rs) | `d700cb811d96ed075cdec2df616e0b20321ae6488d2dec36e3fbf85b8892ba23` | | [Theme color](https://github.com/longbridge/gpui-kit/blob/87d10ae5e1299d1be18670a37570c5402f952e34/crates/component/src/theme/theme_color.rs) | `2d42060c00a0cb0fc91d698a4111c6df2cd80d074a1ed87eb03771e027da38f1` | Only these specific files and theme module declaration were fetched into `/tmp/cui-skeleton-reference`; no checkout/dependency installation. The guide hash matches `docs/component manifest`. Component source lines10–13 contain only style refinement and secondary flag; lines40–60 establish full width, height4, theme skeleton color, caller refinement, then repeating two-second opacity. Theme schema lines533–535 and995 explicitly resolve `skeleton.background`, fallback `tokens.secondary`; this is not the border token. ThemeColor stores Skeleton as Hsla, so this family does not require gradient transport. ## Coverage, gaps and exceptions | Feature / exact source behavior | Current implementation and inspected proof | Assessment | | --- | --- | --- | | Decorative placeholder; no action, focus stop, loading flag or content relation | `src/components/cui_content.c:994` submits one box; `tests/unit/test_status_motion.c:155` asserts zero semantics | Implemented. Do not add per-placeholder busy/status semantics to imitate nonexistent source behavior. | | Primary theme skeleton color, fallback secondary | `cui_skeleton_ex` always uses `theme->secondary` (`cui_content.c:1011`); legacy uses border at903 | Concrete missing dedicated source token. Secondary fallback works only when no explicit source token. Legacy appearance must remain frozen. | | Secondary variant multiplies color alpha by .5; animated element opacity1→.5→1 | ex multiplies existing alpha by result opacity and secondary factor; shared sampler `src/base/cui_status.c:344` | Implemented byte-color adaptation, not exact floating-Hsla compositing. Existing test submits secondary but does not independently inspect its rectangle alpha across the cycle. Need dedicated oracle, including translucent authored colors. | | Two-second repeat, bounce(ease_in_out) | ex defaults2seconds, triangle then quadratic ease, caller absolute clock/state; `test_status_motion.c:52–87` samples endpoints/custom ease/errors | Implemented tested subset; source kernel equivalence at interior/boundary times deserves independent dense oracle. Legacy cosine pulse is intentionally different. | | Source new() full parent width, height4 (16px default rem) | ex defaults160×16, radius0; legacy fallback160×16; bridge fallback120×16,radius4 | Missing source responsive default. Current APIs explicitly fixed positive dimensions, not source full-width defaults. Width0 is rejected by ex, so wrapping a grow parent does not make its painted child fill. | | Width fraction/full, flex, explicit sizes, height utilities/rem | Core `cui_box` exposes percent/grow/fixed sizing; Skeleton facade exposes only positive float width/height <=4096 | Underlying composition exists, but not equivalent own painted-root sizing. Need additive direct root sizing; do not claim a percentage wrapper stretches current fixed child. Rem can be caller-computed now, with no named Skeleton size source enum required. | | Square/circle/rectangle, arbitrary rounding | ex width/height/radius, renderer radius clamp; legacy content test checks rectangle120×16 | Basic capability exists; no dedicated current proof for circle pixels, square corners, fractional radii or resize/clip. Source has no separate shape enum. | | Styled refinement overrides own background, border, spacing, corner/layout properties before animation | No custom background/style descriptor in ex; parent box can compose layout, inherited opacity/clip but cannot replace child color | Partial. General source Styled surface exceeds existing fixed facade. Parent composition is valid only where it preserves actual root geometry/paint. Do not mark all Styled properties implemented. | | Conditional loading and profile/list/table/button/form placeholders | Application conditionally submits multiple Skeletons and real content; `examples/loading_region/scene.c` provides busy-region composition | Composition capability exists; not separate component modes. Full responsive example matrix is not demonstrated by current gallery. | | Meaningful loading semantics | `docs/design/ALERT_SKELETON_SEMANTICS_AUDIT.md`, loading_region Core/DOM/AT-SPI fixtures establish application region/status semantics | Existing reviewed justified application ownership. Physical screen-reader delivery remains separate; no Skeleton input/keyboard work is missing from decorative source. | | Reduced motion | ex merges caller and Core preference, returns opacity1/no wake; browser `tests/web/test_status_motion.py:26–52` checks actual changing pixels then idle | Intentional accessibility extension: source guide says animation cannot be disabled. Preserve quiescence and document difference. | | Scheduling, omission/reinsertion, lifetime | caller-owned `cui_loading_motion`, finite next wake; gallery case18 translates Core deadline to host clock; no state allocation | Scheduler tested, but state persists across omission unless caller resets. This is explicit CUI ownership, not source element lifecycle parity. Add omission/resume/reset proof; never fabricate frame time. | | Native/WASM rendering | status test includes software renderer; existing browser fixture checks changing canvas and no busy/status | Focused proof, not all renderers, themes, shape pixels, DPI or physical GPU/native window delivery. No new platform support inferred. | | Shadow ownership | caller ID is painted Skeleton root; `docs/design/ELEMENT_SHADOW_COVERAGE.md` Skeleton row | Existing root identity. No separate source glyph/highlight owner to invent. Layout/painter changes must preserve IDs and ordering. | ### Theme counterexample is concrete The retained pinned `third_party/gpui_themes/presets.json` contains explicit Skeleton values for Default Light (`#f5f5f5ff` vs secondary `#e5e5e5ff`), Aurora Light (`#f1f5f9ff` vs `#e2e8f0ff`) and Default Dark (`#171717ff` vs `#262626ff`). Other presets need schema fallback, not guessed identity. Current theme public record has no Skeleton field; palette adaptation discards this component token. Changing legacy theme.secondary globally would incorrectly recolor other families. ### Public layers and foreign authoring There is no separate public Base Skeleton widget/reducer. The portable shared motion sampler lives in Base (`cui_status.c`) but its declaration is currently in `cui_content.h`; Styled painting is in Components. Preserve Core→Base→Components, no platform/Clay types, and old by-value options layout. All five bindings currently expose bridge kind35, not `cui_skeleton_ex`: `src/bridge/cui_bridge.c:4938` calls legacy `cui_skeleton` with Core-clock phase, fixed radius4, primary variant, no explicit reduced-motion argument and continuous legacy invalidation. Python `__init__.py:1247`, Node `index.cjs:315`, TypeScript `index.d.ts:114`, Go `native.go:2674`, Rust `lib.rs:830` expose constructors; generic visual sizing supplies dimensions. Their `tested_subset` rows are legitimate legacy construction coverage, not source-motion/color/secondary/ responsive-style authoring. `bindings/node/test/extended.test.cjs` and Go `native_test.go:481` check sizing/construction, not these omitted features. Do not silently migrate old bridge kind35 or its repaint cadence. Gallery `web/gallery.c:5242` uses ex with width computed from external preview, height36/radius6, clock/reduced motion and host wake; it demonstrates a single rectangle, not default source fill, secondary variant or layout compositions. Source metadata `docs/component-usage.json` Skeleton still indexes only legacy APIs/phase and no state, unlike actual ex implementation. This is a discoverability gap to repair with the eventual verified slice, not evidence ex is absent. ## Proposed independently reviewable work 1. **Recommended first: additive owned palette/style values and direct C paint.** Before production, specify exact version/size/reserved and atomic failure contract for a new source-specific palette resolver plus additive Skeleton presentation entrypoint; leave `cui_theme`, existing options and legacy APIs unchanged. Resolve all4 builtins+38presets from pinned schema, explicit token versus secondary fallback, and custom theme from supplied values without preset inference. Owned color is sufficient for this Hsla source family; preserve alpha and documented byte conversion, no brush/gradient architecture. Reuse the existing sampler and root ID. This fixes actual wrong colors while keeping responsive sizing as explicitly outstanding, not falsely closing family. 2. **Responsive own-root presentation.** Review a borrowed submission descriptor that applies existing Core box sizing/corners/style before paint, with explicit defaults full width/16px and application rem policy. Investigate ordinary flow and percent sizing first; no new dispatcher/layout architecture. Reject any unsupported registered-scroll combination explicitly rather than expanding Core admission without review. Preserve fixed-route command compatibility. 3. **Genuine authored foreign UI and gallery.** Add optional bridge-owned motion/ options with bounded copied records and five equivalent builders; exact ABI, owner-thread, wake and lifecycle policy need their own checkpoint. Keep legacy constructors unchanged. Gallery should show secondary/color/shape, full/fraction width on narrow/wide resize and application loading→content transition with copyable UI code. Update human/agent metadata only after actual proof. ## Required proof before implementation claims * Independent frozen-data palette oracle for all presets/builtins/custom fallback; do not calculate expected output through candidate helper. Verify token absence, transparent authored colors, failed indices/config and unchanged outputs. * Exact source pulse oracle at0,.25,.5,.75,1, interior/random/boundary/repeated cycles, backwards clock, independent states, invalid ease and reduced motion; fieldwise comparisons or byte snapshots for atomic unchanged outputs, never struct-copy padding equality. * Actual software pixels/rounded bounds for normal/secondary translucent colors, circles/squares/rectangles, clip/inherited opacity; first-frame and narrow/wide resize fill/fraction geometry and stable root IDs. Test source border/custom paint precedence if exposed. Keep legacy cosine/border commands frozen. * No Skeleton focus/busy/role, application busy/status transition and omission reset/resume; scheduler wakes only while needed, reduced-motion idle stable. * Actual five-runtime authored UI, options/status/old-library omissions, immutable copied wire data and optional-symbol fallback once bindings are implemented. Strict C11, selective/umbrella C/C++, WASM compile, private-Xvfb native and headless browser tests under a separately granted serial lease. No tests were added merely to assert current known gaps, and none were executed for this audit. No status promotion or all78 ledger edit belongs to this checkpoint. ## Exact additive palette/presentation proposal (review required) This is a proposed next slice, not shipped declarations. Keep the existing `cui_theme`, `cui_skeleton_options`, phase API, ex API and shared sampler ABI and behavior untouched. No version/size/reserved fields or new retained object are needed for a new plain owned C value. No common brush/style framework is justified by this single-color family. Proposed new portable header `include/cui/cui_skeleton_palette.h` includes only `cui_theme.h`; C/C++ linkage guards follow existing headers: ```c typedef struct { cui_color background; } cui_skeleton_palette; /* Fallback adaptation, never infer identity from equal theme bytes. */ bool cui_skeleton_palette_from_theme(const cui_theme *, cui_skeleton_palette *out); /* Index and lifetime/order authority: existing cui_theme_preset_count/name. */ bool cui_skeleton_palette_preset_get(size_t index, cui_skeleton_palette *out); ``` Proposed additive declaration in `cui_content.h` (includes the new value header): ```c bool cui_skeleton_with_palette(cui_context *ui, cui_id id, const cui_skeleton_palette *palette, cui_loading_motion *state, cui_skeleton_options options, cui_loading_motion_result *out); ``` ### Pure resolution, source interpretation and ownership * `cui_skeleton_palette` owns one encoded RGBA8 CUI paint color; no pointer, context, preset index, color identity tag, hidden allocation or source lifetime. Its layout is the layout of its sole `cui_color` member (target ABI tests, not a new hardcoded platform-width assertion). All channel combinations are valid. * `from_theme` copies exactly `theme->secondary`, including alpha and hidden RGB at alpha0. Null theme/output returns false without changing output. Other theme fields are irrelevant and need not be validated. Custom theme changes do not discover a preset; no registry search, name guessing or matching bytes. * Custom authored color uses an explicit value, for example `cui_skeleton_palette p = {.background = {21, 34, 55, 0}};`. There is no "unset" zero sentinel: alpha0 is authored transparent paint, never replaced by theme fallback. A separate bool/override mask is unnecessary when the whole supplied palette is active. Callers wanting fallback explicitly call `from_theme` first, then optionally overwrite the owned member. * All four CUI builtins are covered by `from_theme(&builtin, &out)` using the actual existing light/dark/high-contrast/terminal constructors. They are CUI adaptations, not aliases of similarly named upstream presets. No new builtin enum or four duplicated selection functions. * `preset_get` uses precisely the existing38-preset `cui_theme_preset_get` index order; out-of-range/null output returns false unchanged. Resolve pinned raw `palettes.json` values: `skeleton.background` if present, else `secondary.background` (schema's `tokens.secondary`), then named-color lookup. Inspection of the exact retained source found secondary.background in all38 and only solid hex values for the selected Skeleton/fallback tokens. Preserve explicit alpha; #RRGGBB means255, #RRGGBBAA copies all four bytes. Do not use current theme adaptation output as the source oracle, synthesize border blends, or silently accept a future unsupported token/brush syntax. Generator must fail on changed pin/order/missing fallback or unreviewed syntax. No gradient renderer requirement is introduced by this pinned source. * "Exact source token" here means exact selected token/channel bytes and fallback, not upstream shader floating-Hsla/linear compositing bit identity. This entrypoint deliberately uses existing CUI RGBA8 rectangle rendering and inherited-opacity conversion. It must not claim source GPU pixels or introduce a new color-space transport. A future float pipeline would be a separate reviewed API. * Pure resolver writes only after resolution succeeds; no allocation, locale, global mutation, context diagnostic or renderer access. Output is immediately copyable; no loader/library record pointers are returned. ### Presentation and compatibility The new painter snapshots `palette->background` and reuses the existing Skeleton validation, sampler and box emission implementation through a private color-value helper. Existing ex still supplies `theme->secondary`; legacy phase API still supplies border/cosine/invalidation exactly. No public old record gains fields. No global theme.secondary replacement, switch to source preset from theme bytes, Core query, dispatch, native transport or bridge ABI change. * Mandatory nonnull ui/palette/state/out and nonzero id. Dimensions/radius/duration, clock/state/easing validity and reduced-motion resolution are exactly existing `cui_skeleton_ex` rules: positive width/height<=4096, radius0..4096, duration0 selects2 else finite0..60, sampler now0..1e12. Reuse its actual validation; no new divergent reducer. All options remain by-value and easing userdata is borrowed only during synchronous sampling, never retained. * Palette color is multiplied by `(options.secondary ? .5f : 1)` and sampler opacity using the existing float calculation/order, then a single uint8_t truncation as current ex. Do not quantize secondary first. Alpha0 remains0, RGB is preserved. Source component's Hsla secondary opacity multiplies alpha; inherited parent Core opacity remains a separate existing layer, not a palette rewrite. Out result describes motion, not effective post-parent alpha. * Same caller ID, single box, width/height/radius, clip/ancestor opacity and draw ordering as existing ex; no semantic node, busy region or extra focus stop. A transparent rectangle may be culled by existing rendering; do not invent a visible paint/presence guarantee. Custom palette is active even when invisible. * Prevalidation/sampler failure returns false with state/out and draw stream unchanged (easing callback side effects cannot be rolled back). Success means accepted component submission as with existing ex, not completed Core layout, renderer success, native presentation or physical accessibility delivery. A later Core/frame failure does not roll back sampling or already performed application effects. Caller still checks existing Core error/frame result. * Caller owns persistent motion state; state/out must be distinct valid writable objects, not overlapping each other or borrowed inputs. No general alias/in-place support is promised. Palette need live only through this call; snapshots/copies may be kept indefinitely. Start/reset/omission/reinsertion remain explicit caller policy; the new palette does not create a new animation owner. * Caller schedules absolute `out->next_wake_seconds` in the same clock units as options.now_seconds. Reduced motion suppresses easing and returns static/no wake exactly as existing Skeleton sampler. No implicit perpetual invalidation. ### Implementation, proof and deliberate boundaries Proposed ownership after review: new header/source `src/theme/cui_skeleton_palette.c`, pinned generated color table and narrow generator/data oracle; additive content header/Components helper+painter; focused new tests/docs and canonical metadata when granted. Theme resolver remains portable data; Components depends on that value and Base sampler, never Base→Components/platform. Reuse registry ordering and pinned source manifests; avoid a second independently sorted registry. Required proof: independent raw JSON/name resolution for all38, byte-exact selected colors plus explicit Default Light/Aurora Light/Default Dark counterexamples; all4 builtin fallbacks, custom themes with identical preset-looking bytes but no inferred identity, alpha0 hidden RGB, invalid indices/nulls with output byte snapshots. Painter: actual software pixels for translucent/transparent/secondary colors at quarter/interior/boundary times, clipping/inherited opacity and corner geometry; fieldwise command equivalence of existing ex versus new painter using `from_theme` under fixed clocks, independent states and callback traces. Freeze legacy phase output separately before helper extraction. Invalid options/ease and zero id leave outputs/state/commands unchanged; reduced and omission/reset scheduling tested without native desktop windows. Verify strict C11, standalone/ selective/umbrella C/C++ and WASM compilation under a later bounded lease. This step fixes source color selection and explicit custom paint only. It does NOT deliver source full-parent/fraction/flex root sizing, own Styled border/layout refinement, richer gallery compositions or any modern Skeleton binding options. All five legacy constructors remain unchanged and their omissions remain visible. Family completion, full renderer/platform parity and all78 closure remain open. ### Prepared production checkpoint and integrator-owned wiring Implementation now prepared in the worker tree, not C-compiled/runtime-verified. The narrow offline `python tests/test_skeleton_palette.py` run passed two tests; actual C dumper check skipped until a binary is supplied. Source generator repairs missing/changed table, checks its pin/order and preserves identical bytes. No canonical SDK/amalgamation/skill generation was run. Integrator wiring required (worker intentionally does not edit shared lists): * Register public `include/cui/cui_skeleton_palette.h` with theme/value header authority and before `cui_content.h` in amalgamation; add `src/theme/cui_skeleton_palette.c` and its private table to the theme source manifest/SDK closure. No new external dependency or Components→platform edge. * `test_skeleton_palette`: `tests/unit/test_skeleton_palette.c`, link `cui`. Register `python tests/test_skeleton_palette.py --dumper ` and narrow generator `--check`; the C dumper uses actual exported functions while expected bytes come independently from normalized pinned presets. * `test_skeleton_presentation`: `tests/unit/test_skeleton_presentation.c`, link `cui` and `cui_software` (same dependencies as existing status motion test). Frozen `tests/fixtures/skeleton/frozen.c.inc` records exact old functions from `956a853c` with macro name remapping and their unchanged positive-size helper; it is independent of candidate painter helper. * Compile `tests/fixtures/skeleton/header.c` in C11/C++11 with/without `CUI_SKELETON_CONTENT_FIRST`, then selective/umbrella consumers. Compile the new source and affected Components TU under pinned WASM strict flags separately. All native executions use `scripts/test_local.py`; no desktop window tests. * After actual proof, update source usage/coverage/skill metadata to index the new palette/painter and caller-owned state/wake semantics while preserving all78 and explicit responsive/Styled/five-binding omissions. Canonical SDK→amalgamation →skill and required installed-skill/freshness checks remain integrator-owned. ### Pre-validation review correction: legacy callback color timing The frozen ex reads `theme->secondary` after synchronous custom easing. The private helper therefore accepts a color pointer and reads it only after sampling; old ex passes the original theme member. New palette route snapshots its color at entry then passes that local address, as its new contract specifies. Prepared independent frozen/current callback mutation tests assert old post-callback RGBA and new call-entry snapshot RGBA explicitly. No Core/input change. Generator selection now accesses secondary fallback only when no explicit Skeleton token exists; offline synthetic source tests prove explicit-only success and required missing fallback failure (with test-local pin update, production pin unchanged). C compilation and callback runtime tests remain pending the serial lease. --- ## Skeleton own-root responsive and Styled presentation Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SKELETON_RESPONSIVE_CHECKPOINT.md # Skeleton own-root responsive and Styled presentation Design only, against worker `65742454` and frozen source reviewed in [Skeleton parity](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SKELETON_PARITY_CHECKPOINT.md). Palette C compilation/runtime acceptance is still pending; no production authorization is implied here. Keep all old phase/ex/options functions and layouts unchanged. Full family and all five foreign authoring surfaces remain open. ## Existing mechanisms and actual limits Pinned `skeleton.rs:40–60` builds a single div: full width, height4, theme Skeleton background with optional .5 alpha, then `.refine_style(&self.style)`, then an animation closure `this.opacity(1 - delta*.5)`. Refinement can replace the base background, dimensions, corners, border and spacing. The animation sets the root opacity AFTER refinement: a caller's root opacity does not multiply the pulse. Ancestor opacity remains independent. This ordering also animates authored border paint, not just background. There is no child content/slot or input behavior. Current Core already submits these properties in one `cui_box`: * `src/core/cui.c:1995–2023`: positive dimension fixed, negative grow, zero FIT; percentage flag takes precedence over fixed/max with fraction clamped0..1. Explicit fixed zero uses Core's canonical zero handling. These are existing public conventions, not a proposed new layout engine. * `cui.c:2063–2066`: custom root opacity clamps then multiplies ancestor opacity; box background/border paint and corner geometry are emitted by the existing pipeline. `include/cui/cui.h:431–464` provides root sizing, max caps, physical padding/border edges, offsets, clip, corners, inert and layout_only. * `src/core/cui_scroll_layout_internal.h:397–409`: registered scroll-tree admission rejects percentage HEIGHT except requested canonical fixed zero. Width percent is not rejected by that rule, but final width fingerprint and ordinary/floating admission checks still apply. No blanket registered-scroll support inferred. * A grow/percent PARENT around existing fixed Skeleton does not change its actual child paint width. Therefore the existing palette/ex function is not a substitute for the proposed direct root route. No prior-frame bounds read, input replay, prepaint geometry hook, portal or global dispatcher is necessary for this leaf's ordinary responsive sizing. Full-width under an unconstrained/FIT parent has Core/Clay's existing dependency semantics; no guessed viewport width fallback. The meaningful source full-width proof must use a positive definite parent extent and resize that actual parent. ## Proposed exact public value and entrypoints Add declarations to `cui_content.h` only after review and palette acceptance: ```c typedef struct { cui_box root; bool custom_background; bool secondary; float duration; double now_seconds; bool reduced_motion; cui_loading_ease_fn ease; void *ease_user; } cui_skeleton_presentation; cui_skeleton_presentation cui_skeleton_presentation_default(void); bool cui_skeleton_present(cui_context *ui, cui_id id, const cui_skeleton_palette *palette, cui_loading_motion *state, cui_skeleton_presentation presentation, cui_loading_motion_result *out); ``` This is a new by-value submission record, not an extension of old options/state. No version/size field, new enum, retained object, public platform/Clay type or extra animation authority. The only persistent state is existing caller-owned `cui_loading_motion`. `ease_user` is borrowed synchronously. `cui_box` already is the portable public own-root style vocabulary; no family-specific duplicate fraction/flex/corner/edge flags are justified. Default constructor returns all-zero fields EXCEPT: * `root.width=1`, `root.width_percent=true`: source full-parent width, NOT fixed160 and NOT grow(-1). Caller may explicitly select grow or another fraction through ordinary root fields. * `root.height=16`: source default4rem-quarter units at CUI default16px rem. This is literal16 logical pixels; source user rem scaling is explicit application assignment (`root.height=rem_size`). No invented theme-font inference. No size variants exist in source and no new size enum is proposed. * `duration=2`: source period. `duration=0` also selects2 as existing options. Default root has radius0, no border/padding/clip/custom background. A zero-initialized record is legal Core FIT sizing; it is NOT a second default spelling. Applications wanting source defaults call the constructor, then change fields explicitly. ## Authoritative precedence, sampling and failure rules 1. Validate mandatory ui/id/palette/state/out, duration and existing sampler state/ now/ease contract before any box submission. Copy the entire presentation and palette color at entry; no borrowed public config/theme is reread after user easing. Existing ex remains post-callback theme-color behavior unchanged. 2. Select base background from owned palette. If secondary is true, apply .5 to palette alpha using the established encoded-byte adaptation. If `custom_background` is true, replace that result with `root.background` completely, INCLUDING authored alpha0; secondary no longer attenuates the explicit replacement, matching source refinement order. No zero sentinel. Inactive root.background is ignored. Other root paint fields remain active. 3. Sample existing motion exactly once on a local state copy. Palette/style values cannot influence easing input. Reduced motion combines caller/Core preference, skips easing and resolves root opacity1/no wake as existing Skeleton policy. 4. Apply selected background to copied root. Set `root.custom_opacity=true` and `root.opacity=result.opacity`, replacing both caller root opacity fields. Caller root opacity is deliberately inactive even if nonfinite: source animation writes it last. To fade a whole loading group, use ancestor opacity. Border color, per-edge border widths and background all receive the existing Core inherited opacity pipeline; never multiply only the background by the pulse. 5. Submit exactly one `cui_begin_box(ui,id,root)`/end pair, then commit local motion and result. No generated child identity, semantic registration or extra scope. Root contains no children; padding/border/FIT sizing use actual Core leaf rules. Scheduling remains caller-owned absolute `next_wake_seconds` in supplied clock units. Omission preserves caller state; explicit reset is caller policy. Core style normalization remains Core's existing contract: negative/nonfinite padding/edges normalize, percent/max/fixed precedence remains unchanged, corner radii are renderer-clamped. Do not inconsistently reject Core-normalized values only for Skeleton or duplicate a private layout validator. Pointer-valued members are only ease_user (and existing cui_box contains no borrowed text/children). Inputs/state/out must be valid disjoint objects; no generic alias guarantee. On invalid mandatory arguments or failed motion prevalidation/sampling, return false without box output/state/result changes. Callback side effects are not rolled back. On successful component submission commit state/result as existing ex; later Core capacity/layout/registered-scroll errors remain Core failures, not a hidden transaction or rollback. Caller must inspect completed-frame error before claiming geometry/paint. No presence query or hardware delivery promise. A failed current registered layout must not be described as supported Skeleton geometry simply because sampling returned true. ### Byte adaptation tradeoff requiring explicit acceptance Current fixed palette painter multiplies background alpha by secondary and pulse then truncates once. This new source-ordered route applies secondary to background before root opacity, and Core may truncate at its own existing paint conversion. It can differ by one byte from the fixed painter for fractional/translucent values. This is a new opt-in source-order presentation route; preserve old/ex/ fixed-palette output EXACTLY, and document/test the new rounding stages rather than weakening a frozen comparator or pretending both routes are identical. No new renderer/float-color architecture is proposed to erase this difference. ## First proof slice before production Prepare a test-only ordinary-box prototype using palette plus existing sampler, not a private production hook. Under a separately granted small cached-Core lease: | Witness | Required actual observation | | --- | --- | | First frame at parents320/91px, width100% | Own ID bounds equal parent inner width immediately, height16; no prior frame/bounds dependency. | | Parent resize320→91→420, nested padding/border | Actual own root and rectangle track inner extent; clip and rounded pixels agree. No wrapper-only measurement. | | Width50%, explicit120, grow with fixed sibling/spacers, max caps, explicit zero/FIT | Follow actual existing Core conventions in rows and columns; stable IDs; no viewport fallback. Test percentage flag precedence explicitly. | | Square/circle/rectangular own custom corners and borders | Actual rectangle/border commands and software pixels, not only count; per-corner and per-edge clear/paint bounds. | | Secondary palette vs explicit authored background(alpha0 included) | Source precedence proven independently. Explicit background unaffected by secondary, RGB retained for transparent authored input; no fallback. | | Caller root.opacity0/.2/NaN vs parent opacity.5 | Root authored opacity ignored because animation replaces it; parent remains multiplicative; pulse fades border AND background. Exact expected byte stages recorded. | | Custom ease mutates source descriptor/palette | Both new snapshots remain call-entry values; one synchronous invocation, original userdata mutations visible externally. Frozen old ex timing remains unchanged. | | Reduced motion, omission/reset/reinsert, backwards clock | No implicit invalidation; finite absolute wakes, idle quiescence and explicit owner lifecycle. | | Registered Y body: fixed16 height/full or half width | Actual successful current-frame admission, first/resize width fingerprint, final bounds and retained scroll offsets. No broad claim until this passes. | | Registered body percent HEIGHT and problematic floating/height-dependent cases | Expected existing Core diagnostic/empty failed snapshot, no rollback claim. Clearing diagnostic alone does not certify geometry; fresh good frame recovers. | | Layout-only/inert/clip, capacity error | Existing Core suppression/normalization and later-error contract, no semantic/focus/action nodes created; state effects explicitly observed. | Do not change scroll admission to make these tests green. If default full width or supported fixed-height cases fail, report exact witness and reconsider only that portable presentation descriptor before any Core proposal. Percent-height inside registered scroll remains an explicit unsupported combination unless separately reviewed Core work establishes it. After proof/review, implementation can reuse the Base sampler and existing box submission with one Components function; no engine architecture is required by this proposal. A complete authored loading profile/list example should demonstrate actual narrow/wide own-root fractions and loading→real-content replacement plus application busy/status semantics. Five modern bindings and bridge wake/copy/ owner policies remain separate required delivery work; old constructors stay frozen. Metadata/SDK/skill changes wait for verified implementation under integrator ownership. ## Prepared public implementation checkpoint Source-only separate `include/cui/cui_skeleton_presentation.h` and `src/components/cui_skeleton_presentation.c` implement the reviewed record/default/ function without editing old content code/headers. The public header includes the existing portable content/palette types; the source depends only on ordinary Core box submission and the existing Base motion sampler. Palette/style snapshot, secondary→custom replacement→root opacity order and later-Core-error limits are explicit in the public comments. No layout/dispatcher changes were required. Prepared public fixtures: `tests/unit/test_skeleton_responsive.c` repeats the proven prototype's independent geometry/pixel/registered-body expectations through `cui_skeleton_present`; `test_skeleton_presentation_contract.c` tests15 atomic rejections, easing mutation/copy ordering, explicit defaults, grow/fraction/fixed/ zero sizing and layout-only/inert sampling. Header C/C++ include-order fixture is `tests/fixtures/skeleton/presentation_header.c`. All remain uncompiled/unexecuted. Integrator-owned wiring needed after review/lease: add the new Components source and public header to module/source/SDK order (after content header), link both new C tests against `cui` (responsive also `cui_software`), and register four C/C++ header-order compile/link tests. Preserve the frozen legacy palette/presentation fixture and rerun it against the combined object set. Strict WASM source/header and selective/umbrella distribution closures remain later gates. No shared CMake, manifest, metadata, skill, generator or generated-resource edit in this checkpoint. ### Focused public-route proof completed The new API passed strict native object/three-fixture links and four C/C++11 header-order consumers against rootb7e494ba cached actual engine/palette library. Final private-Xvfb wrapper7/7 passed; actual own-root first-frame and320→91→420 resizing, half/grow/fixed/zero/percent precedence, source custom-background/alpha0, parent/root opacity, border+background pulse alpha at0/.25/.5/.75/1,15 atomic rejections, callback snapshots, registered Y fixed-height/full-width success and expected percent-height failure/recovery all executed. Independent frozen old phase/ex callback/pixel fixtures passed unchanged against current cached root. Pinned Zig0.16 wasm32-wasi strict compile newsource/header passed; not runtime. First driver failed by leaking `-x c` onto binary archive inputs, not a CUI source failure. Corrected driver resets language and limits diagnostics. Complete initial diagnostics are losslessly gzipped/CRC-verified; compact receipt records raw size and hash without retaining1.7GB of disposable raw output. Canonical distribution closure/metadata/skill remain root-owned pending gates; no five-binding/platform or full-family claim follows this local proof. --- ## Slider numeric accessibility actions: minimal queue extension Source: https://github.com/mattmezza/cui/blob/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SLIDER_ACCESSIBILITY_ACTIONS.md # Slider numeric accessibility actions: minimal queue extension Design-only addendum to [the complete Slider proposal](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/design/SLIDER_RANGE_ORIENTATION_SCALE.md), source checkpoint `502f1e22`. No implementation, dependency/build, generated or public-ABI changes in this commit. Existing FOCUS/ACTIVATE behavior stays intact. Numeric action delivery remains a whole-family blocker until implemented/tested. ## Audited actual route and hazards | Authority | Current behavior / required boundary | | --- | --- | | [`cui.h`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui.h):113,654 | Only FOCUS=0/ACTIVATE=1. `cui_event` already has targeted action enum+ID, so no event/semantic/details/config struct growth is needed. | | [`cui.c`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/src/core/cui.c):1270–1310 | Supported query uses completed `previous` semantics and previous modal eligibility, returns false during frame. Queue validates support, then normalizes to action type/target/action only, zeroing unrelated input. Capacity checked before enqueue. | | Core:1502–1520 | Begin-frame revalidates against previous semantics and routes to explicit target. **Every non-FOCUS action currently becomes activation**; must change to explicit ACTIVATE branch before numeric actions exist. | | Core:3187–3240 | `cui_interact` handles disabled focus/capture and validates activation role/current scope. Numeric requests must not enter this activation path at all. | | Core:4190–4342 | End-frame removes inert/layout-only semantics, withdraws actions after current omission/role/scope/eligibility changes, copies current to previous. Its FOCUS/else-ACTIVATE eligibility branch also needs explicit numeric branch. | | Core:4517–4640 | `cui_event_target` is a raw routed-target query, not current capability validation. `cui_consume_event` marks consumed; activation cancellation has no slot for a non-activation action. A new validated claim boundary is necessary. | | Core:4979,5068 | Details can change after interaction; dismissed scopes compact semantic arrays. Capability sidecars must follow every compaction, not merely append/reset/end copy. | | [`cui_component_events.h`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/include/cui/cui_component_events.h) | ACCESSIBILITY source already exists. Activation helper sets HAS_ACTIVATION; **wrong helper for increment/decrement** because they create no activation. | | [`cui_accessibility.c`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/backends/accesskit/cui_accessibility.c):237–251,466,518–562 | Snapshot action mask, native action mapping, mailbox validation and drain currently only Focus/Click. Native callback queues locked tokens, never calls Core; UI-thread drain revalidates. | | [`test_core.c`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_core.c):3119 onward; [`test_accessibility.c`](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/tests/unit/test_accessibility.c) | Existing targeted Focus/Activate ABI values, queue/routing/disabled/role/omission/overflow/lifetime coverage remains required and unchanged. | Pinned AccessKit C0.23.0 commit `0824c4a1e3a4d13ce5582df20e394fba49485a15` ([pin](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/third_party/accesskit/pin.json), archive SHA256 `19c3ecda791acb100b43442adb8738e245dd14ad641de5fa2b494ac52a9f11a9`). The retained pinned header `include/accesskit.h`:84/88 contains `ACCESSKIT_ACTION_DECREMENT` / `ACCESSKIT_ACTION_INCREMENT`; no dependency update is needed. Source URL: https://raw.githubusercontent.com/AccessKit/accesskit-c/0824c4a1e3a4d13ce5582df20e394fba49485a15/include/accesskit.h . The CUI adapter currently does NOT advertise/map them. Other CUI native hosts have no independent numeric accessibility-action implementation found here; SDL helper supplies window metadata only. WASM gallery DOM controls are not a semantic bridge for canvas-painted Sliders. Do not imply browser/other-OS AT parity. ## Minimal additive portable API, no public struct growth Append explicitly numbered enum values INCREMENT=2, DECREMENT=3 to the existing `cui_accessibility_action`; preserve existing0/1 and all existing event-type values. Add numeric-only capability constants and functions (spelling subject to review): ```c #define CUI_ACCESSIBILITY_NUMERIC_INCREMENT (1u << 0) #define CUI_ACCESSIBILITY_NUMERIC_DECREMENT (1u << 1) bool cui_set_accessibility_numeric_actions(cui_context *, cui_id, uint32_t mask); bool cui_claim_accessibility_numeric_action(cui_context *, cui_id, size_t event_index, cui_accessibility_action *out); ``` Registration is explicit per **current semantic**. No automatic role-based advertisement for legacy Slider, controlled scalar reducer, Progress, Scrollbar, NumberInput, or arbitrary callers that do not consume these events. Initially allow only role Slider; future supported roles require separate implementation and tests. Mask0 revokes; only two declared bits accepted. Existing Focus/Activate capability policy remains derived exactly as today and is not set through this API. Registration requires active mutable painted submission, nonzero existing unique current semantic ID, supported role and valid mask. It changes only that semantic's private mask. Invalid role/ID/mask/lifecycle leaves mask unchanged and reports the normal applicable error; inert/layout-only submission returns false with no side effects. Disabled/readonly semantics may retain authored registration, but supported/claim/publish eligibility always gates them off using actual details. New component sets details first, then registers, then claims input. A legacy component never calls registration and therefore remains unsupported. Store numeric capabilities/payloads in a **lazy owned numeric-state allocation** behind one private context pointer, initiallyNULL. Allocate only on the first otherwise-valid nonzero capability registration; mask0 before opt-in allocates nothing. Existing `cui_create` performs no new allocation and gains no new OOM branch for legacy users. Arrays remain bounded by existing max_elements/event limits and live until context destroy. The exact layout/failure/publication contract in the revision below supersedes the earlier eager allocation idea. ## Eligibility, delivery and independent acceptance 1. **Completed query/enqueue:** preserve existing query timing (outside frame only). Numeric support requires previous same-ID Slider registration bit, enabled, not readonly, and allowed previous modal scope. Unknown enums false. Enqueue normalizes to the existing target/action event only; lifecycle, unsupported and capacity failure leave queue/interaction state unchanged under existing sticky-error conventions. Generic `cui_queue_event` follows same rule. 2. **Begin routing:** recheck previous snapshot before routing. Numeric actions set target only; no focus change, focus-visible change, capture/release transition, activation slot/snapshot, pointer/keyboard event or implicit key repeat. FOCUS and ACTIVATE execute their old explicit branches unchanged. 3. **Current claim:** validate output and index/type/action, unconsumed event, exact routed target, previous AND current same-ID/same-role Slider, both capability bits, current enabled/not-readonly/modal eligibility, mutable painted phase. Only then copy action and consume the original input once. Failure leaves output and consumption unchanged; no capability-less reducer can claim it. `cui_event_target` alone is insufficient authority. 4. **Component request:** the new Slider model maps action to focused *targeted* thumb value±step (step0 uses existing span/100 policy), neighbor/domain clamps and min-origin snapping. The target selects thumb; it need not be keyboard focused. Each action emits BEGIN/UPDATE/COMMIT from one immutable entry pair, not a mouse gesture; no drag capture/preview survives. Existing source-f32 accessibility range→Single behavior is deliberately rejected. Rejection by owner does not unconsume the action or propagate it to an ancestor. 5. **End-frame:** invalidate still-unclaimed numeric events whose target is absent, role changed, mask revoked, disabled/readonly, inert/layout-only or outside current modal scope. Discard them this frame; never replay next frame or onto reused IDs. Completed capabilities reflect final current semantics, not the event's previous admission. Preserve FOCUS rollback/ACTIVATE withdrawal paths. Support means a handler can process a request, not that value must change. At min/max or a neighbor boundary the new model may emit the same clamped value, consistent with its keyboard/source repeated-update contract; it advertises both numeric actions while enabled/writable with valid positive domain. Zero-span linear, missing handler and readonly register mask0. No Core inference from float numeric min/max determines step/domain/double precision. Log actions remain additive in value units; reverse fill does not reverse increment/decrement. Role/disabled/readonly/revocation changes **before claim** prevent callbacks. Omission means no claim is called; final snapshot withdraws pending action. No synchronous system can undo an already delivered request if the application later changes the tree in that same frame. Claim freezes eligibility/evidence at that point; callers defer destructive/reentrant changes until submission returns. Late dismissal can withdraw remaining input and next-frame capabilities, not retroactively revoke emitted owner intent. Do not promise transactional end-frame rollback or delay all component callbacks to introduce a new dispatcher. Same-ID/same-role logical replacement still requires a new CUI ID, as current native-token contract states; no new hidden object generation is invented. ## Evidence and request ABI Do not grow existing `cui_slider_event_input` or scalar callback records. The proposed new model request owns its new input record containing action/target alongside existing pointer-free fields. Actual numeric request has input=true, ACCESSIBILITY source, frame/index from the original normalized queue event and explicit action/target. It has **no HAS_ACTIVATION** and activation identity stays zero. Use `cui_component_event_init` + frame-index helper directly, never `cui_component_event_from_activation`. No fabricated keyboard fields, pointer contact, activation or “physical screen reader” evidence from a test enqueue. Multiple queued actions remain ordered individual inputs; each uses the call's same immutable owner pair, matching existing controlled key snapshots. Acceptance is external and appears next submission. The C model handler is synchronous; bridge copies these requests and language callbacks remain after-frame, using the independently reviewed acceptance receipt contract. Missing observer is read-only, not silent auto-accept. Consumed input does not imply accepted value. ## Native adapter, lifecycle and portable fallback Extend the adapter's existing private action mask with separate increment/ decrement bits populated solely by completed Core supported queries. Include new bits in snapshot equality (already compares mask). Advertise AccessKit actions only for those bits; native callback maps exact action to the matching CUI enum, using the existing locked bounded token mailbox and foreign-thread wake contract. No native callback may invoke Core/SDL/user handlers. Request mask validation must use an explicit safe enum→bit mapping, not unchecked shift on caller enum. UI-thread drain validates live token, live snapshot bit AND current completed Core capability, then enqueues before begin-frame. Existing queue-full policy retains unqueued requests and reports capacity; rejected stale/unsupported actions are discarded with rejected stats. Do not label every failed enqueue CAPACITY: unsupported/invalid/lifecycle failure must retain its actual diagnostic/status, otherwise the new branch can turn permanent invalid work into infinite retries. No duplicate accepted work after recovery. Snapshot capacity/string failure keeps last published tree/tokens; Core eligibility is rechecked even when publication failed. Closed backend synchronously disables wake and drops requests as today. Removal/reappearance or role change gets a new backend token. Same-role mask changes need not churn token: requests validate live bits at request/drain and Core again at claim. Capability revoked and restored without any intermediate published snapshot is indistinguishable from continuous support, like existing same-frame identity; do not assert stronger stale-token protection. Native token, CUI ID and bridge node generation are distinct authorities. Existing optional Linux native accessibility integration is explicitly opt-in ([native guide](https://raw.githubusercontent.com/mattmezza/cui/4752885b8a8f8eec40d1c91964f1f57e4d8d37e1/docs/NATIVE_ACCESSIBILITY.md)); it is not automatically created by all bridge runners. Required host proof uses real pinned adapter action mapping and a private DBus/Xvfb AT-SPI session, not only `cui_accessibility_request` helper. Inspect which AT-SPI interface the pinned AccessKit platform emits for Increment/ Decrement before choosing the client call; do not invent action names or claim AT-SPI Value set-current-value is supported by merely adding these two actions. SET_VALUE is currently unsupported; the separately typed design below adds numeric SET_VALUE only. Text editing remains unsupported. UIA/macOS/other platform delivery stays unverified until tested; unsupported adapters publish no numeric capability and return/report unsupported rather than translate to keys or direct state writes. ### Pinned Linux delivery blocker, verified during this audit The already-retained Cargo.lock resolves `accesskit_unix`0.23.0 (crate checksum `665c9079b7325a8168a6793437a172dda44b19a05af8ed52d7e32abaada996fe`) and `accesskit_atspi_common`0.20.0 (checksum `c9d47ad644916f6cb7e432a5ca0dbd7cc78281a9772881057bb72d4aadb93257`). Read only those retained source files, no download/install/build: | Pinned crate/file | Raw file SHA256 | Actual platform authority | | --- | --- | --- | | [accesskit_unix0.23.0/src/atspi/interfaces/action.rs](https://docs.rs/crate/accesskit_unix/0.23.0/source/src/atspi/interfaces/action.rs) | `7ffa334b1cace21aa567a074d0c1ba59dd2229449af02ffc329bfd4671940903` | Delegates AT-SPI action names/count/do_action to common PlatformNode. | | [accesskit_unix0.23.0/src/atspi/interfaces/value.rs](https://docs.rs/crate/accesskit_unix/0.23.0/source/src/atspi/interfaces/value.rs) | `829dfa73ab581da1be9210c1a6a0361bbb8563fb8d49c7057557cc1ddefafbab` | Value property setter delegates set_current_value, not increment/decrement. | | [accesskit_atspi_common0.20.0/src/node.rs](https://docs.rs/crate/accesskit_atspi_common/0.20.0/source/src/node.rs) | `ce331e201e4a65f68f2e4d155b034a27c30f513d7ca3645976a5968ef0d3cdec` | `n_actions`/`get_action_name`:532 only click when clickable. `do_action`:1104 index0 emits Action::Click; others false. `set_current_value`:1745 emits Action::SetValue with NumericValue. No Increment/Decrement mapping. | Consequently **adding Core and CUI AccessKit callback support does not deliver these actions through this pinned Linux AT-SPI platform**. An adapter helper injection can test CUI mapping/mailbox only; it is not real native delivery proof. Do not publish increment/decrement host capability on Linux as if that path exists. Keep Core consumer capability distinct from native platform delivery capability. Native Windows/macOS crates are not retained here and were not audited/tested; locked versions alone do not establish support. Root review rules out patching/updating this dependency. The additive typed SET_VALUE alternative below reuses actual AT-SPI Value delivery without changing its pinned source. Increment/decrement remain Core semantics for hosts that can deliver them; an increment-only slice is **not Linux host completion**. Full physical-AT acceptance is separately measured, not inferred from either path. ## All-five binding authority and compatibility C model facade alone registers real capabilities. Binding options/method names cannot assert support for a legacy/unpainted/readonly Slider. A versioned bridge query/action API should resolve a live model node plus START/END thumb to its actual stable semantic ID, then call completed Core supported/query queue; it must validate node generation, mode, completed presence and thread/lifecycle. No exposed raw ID cast from a language handle. Single START returns unsupported; Range root is not an editable Slider target. Queueing uses actual accessibility input, not Arrow keys or a direct accepted-value setter. Python/JS/TS/Go/Rust wrappers expose the same optional capability query and typed action enum through the new model API only. Native symbol absence reports unsupported without breaking old library loading; TypeScript compiles against the same real JS capability/method path. Distinguish (a) configured model support, (b) current completed Core consumer capability, (c) installed native platform numeric delivery, and (d) actual request acceptance. Only (b) authorizes Core enqueue; only measured (c) supports a host delivery claim. A live request still requires explicit owner acceptance after frame dispatch under the reviewed bridge receipt contract. No existing scalar callback/event ABI changes. Current bridge native runners do not automatically own a `cui_accessibility` backend. Enabling it needs explicit lifecycle integration/configuration and proof in each promised runner, reusing the existing optional adapter contract: create outside stepping, drain before frame, publish after end-frame, destroy before window/user teardown. Do not silently add backend creation to all runners, grow old bridge options or claim installed-language native AT delivery from direct Core tests. Renderer-only/headless hosts may support Core query/event tests while reporting native accessibility unavailable. Browser canvas semantic host mapping remains separately unsupported until implemented; DOM gallery controls are not it. ## Meaningful headless proof and review gate No compiler/tests were run for this design. Required future evidence: | Layer | Required proof | | --- | --- | | Old compatibility | Existing Core Focus/Activate and AccessKit unit/native/package suites retain enum values, normalized event bytes, timing, focus/capture, activations, rollback and error/capacity semantics. Legacy mutable/controlled/event Slider cannot advertise or queue numeric actions without explicit new registration. | | Capability storage | Two independently registered Slider semantics; current append defaults0; mask replace/revoke; unknown bits/zero/wrong role/missing ID/duplicate ID; max_elements allocation/overflow/failure cleanup. Compaction through hidden/layout-only/dismissed scopes keeps masks attached to correct IDs; next frame does not inherit authorization. | | Snapshot timeline | Previous allowed→current disabled/readonly/role change/revoked/omitted/current modal blocked rejects claim. Newly enabled capability unavailable until first completed publication. Gap/reappearance and different role cannot resurrect stale events. Late mutation after claim has documented non-rollback behavior; no replay. | | Target/non-activation | Actual normalized numeric event retains only target/action; exact original frame/index; unchanged focus/capture/focus-visible, zero activation counts/slots/snapshots. Two targets/same input order, wrong target/index/action/consumed claim fails unchanged output. Claim consumes even owner rejects. FOCUS/ACTIVATE are never claimable as numeric actions. | | Model values/evidence | Per-thumb additive step/clamp/log/range/limit/continuous/zero-span/read-only; pair never scalarizes or crosses. Same-call immutable snapshots, begin/request/commit counts, unchanged requested value permitted at bound. ACCESSIBILITY source and real input/action metadata, no invented key/pointer/activation. Copied request survives frame/context lifetime as documented. | | Bounded recovery | Fill Core event queue and adapter mailbox, failed enqueue preserves input/focus/capture, clear error/drain recovery delivers once, unsupported work discarded rather than endless retry, snapshot overflow preserves tree/token but rechecks Core eligibility. Foreign-thread wake/non-reentrancy, close/destroy/no stale user access use existing sanitizer/lifetime fixtures. | | CUI adapter | Verify published AccessKit action masks match Core exact capability; native callback maps Increment/Decrement independently; unknown native actions freed/ignored; current token/role/mask/generation checks. Helper injection proves this layer only. No advertisement of an unimplemented native platform delivery route. | | Real native platform | For the typed alternative below, call actual AT-SPI Value SetCurrentValue through private DBus/Xvfb; observe actual new model request with ACCESSIBILITY origin and accepted next-frame pair/paint. No direct helper call or keyboard event substituted. Other OS/browser hosts remain unsupported/unverified until independently proven. | | Five runtimes | Actual Python/JS/TS-runtime/Go/Rust new-model queries and action queue calls target correct thumb, preserve all metadata and after-frame callback timing, reject stale nodes and unavailable symbols, accept/reject request explicitly. Verify legacy scalar paths untouched; actual native runner proof separate from Core/API tests. | | Distribution/docs | Strict C11 selective/umbrella declaration+link checks and ABI old-client probes; generated SDK/dist/skill/source metadata, all78 entries, usage JSON+exact mirrored guide and component_usage tests. Explicit supported-host and claim-vs-acceptance documentation. | No public struct growth, keyboard fabrication or global dispatcher is needed for Core numeric actions and typed SET_VALUE payloads. Explicit bounded semantic capability storage and a validated current-semantic claim boundary are the minimum coherent Core changes. Do not ship bare enum additions or pretend optional AccessKit action tags close the pinned Linux platform gap. Concrete API/error/sidecar tests and the native typed payload/native integration contracts require integrator review before production. Signed: `/root/hidden_windows`, 2026-10-31. Design-only checkpoint; no production, generated files, compiler/dependency changes, merge or push. ## Root-requested typed SET_VALUE alternative (no dependency changes) This section extends/supersedes the increment/decrement-only claim prototype above before any API ships. Append SET_VALUE=4 after INCREMENT2/DECREMENT3; registration gains numeric SET_VALUE bit2. Keep Focus/Activate derived policy and old event/semantic/details/config/activation layouts unchanged. A legacy Slider still registers nothing; no action is advertised merely because role is Slider. ### Exact new portable records and queue/accessor boundary ```c #define CUI_ACCESSIBILITY_NUMERIC_SET_VALUE (1u << 2) #define CUI_ACCESSIBILITY_NUMERIC_INPUT_V1 1u #define CUI_ACCESSIBILITY_NUMERIC_HAS_VALUE 1u typedef struct { uint32_t version; /* exactly1 */ uint32_t reserved; /* exactly0 */ double value; /* finite, semantic numeric units */ } cui_accessibility_set_value_v1; typedef struct { uint32_t version, action, flags, reserved; /* action is fixed-width enum tag */ cui_id target; double value; /* present only for SET_VALUE; canonical0 otherwise */ } cui_accessibility_numeric_input_v1; bool cui_queue_accessibility_set_value_v1(cui_context *, cui_id, uint32_t payload_size, const cui_accessibility_set_value_v1 *); bool cui_claim_accessibility_numeric_input_v1(cui_context *, cui_id, size_t event_index, uint32_t output_size, cui_accessibility_numeric_input_v1 *out); ``` Use the versioned claim instead of publishing two overlapping numeric claim functions. It handles increment/decrement (flags0/value0) and SET_VALUE (HAS_VALUE/value copied exactly). Generic no-payload `cui_queue_event` or `cui_queue_accessibility_action(...SET_VALUE)` rejects INVALID_ACTION: value0 must not be guessed from missing payload. Existing no-payload enqueue still works unchanged for Focus/Activate and explicitly numeric increment/decrement. Supported query may return true for SET_VALUE; the documented typed entry point is required to enqueue that action. No value hidden in x/y, key, text, pointer identity, activation or unrelated fields. Queue validates exact record size/version/reserved0, nonnull pointer, finite value, current completed capability/target and outside-frame lifecycle **before** queue/payload mutation. NaN/Inf/unknown versions/malformed size fail atomically. Copy the scalar into private owned storage before return; caller may reuse stack payload immediately. No arbitrary blob, borrowed pointer, allocation per event, new transport abstraction or generic event bus. New records are additive; no existing public-by-value type grows. Matching new API clients require matching new symbols, while old ABI clients retain existing behavior. ### Bounded sidecar and stable event-index lookup Existing Core has queued events bounded by CUI_CORE_EVENT_MAX and dispatched events bounded by CUI_CORE_DISPATCH_MAX. Begin-frame copies queued events and sets `event_origin[i]=i`. Touch handoff can insert synthetic cancellations (origin SIZE_MAX), memmove origins and later swap origins with events (Core1429–1433,1473–1483,1718–1720). A sidecar naively indexed by dispatch offset would attach the wrong value after those operations. Use two private fixed arrays, queued payloads and frame payloads, each exactly CUI_CORE_EVENT_MAX entries of `{bool present; double value;}` (or equivalent explicit tagged slot). Before incrementing queued_count, internal enqueue commits the normalized event and matching payload as one operation. Ordinary events explicitly clear the slot. Typed enqueue cannot call a public generic enqueue that first rejects SET_VALUE or publishes a half-filled slot. At begin-frame copy queued payload slots into frame origin slots alongside event copy; clear reused queued slots. Retain the original queued count as a private bounded frame count. Claim maps actual dispatch event_index through `event_origin[index]`, validates origin