|
Portals0.7.0 · dev (544a5c68c72e · 2026-11-28 UTC)
|
Русская версия · Declarative guide
This page describes preparation, lifetime, dispatch and error contracts.
Scene::get(id) returns DynamicRef; get<T>(id) and conversion to Ref<T> validate public Widget inheritance with RTTI. Deferred conversion waits for the original dynamic slot. Once published, conversion checks that slot's original NodeId even after rename or ID reuse. It never searches the name again. A request owns its ID and call site, while its scene anchor remains weak. All successful slots remain observations; the scene owns widgets and registrations.
Requests are bounded independently by SceneOptions::maxConfigurations and resolve between complete recipe mount and pending configuration. Startup lookup errors are latched before observer callbacks and notified once. Same-name deferred conversions retain that primary cause without another notification. Immediate failures are recoverable reports except inside the existing checked setup/configuration scope. Construction and argument/capture allocation before request admission may throw; admitted internal failures map to BIND/NO_MEMORY or CALLBACK_FAILED.
Scoped ui::style(ref, bytes) and styleFile(ref, path) use complete strict PSS v0. The optional StyleSheet::scope is an exact NodeId filter before existing selectors; it changes neither selector specificity nor tier order. The standalone metadata-only resolveStyle preview has no live node identity and ignores this filter; StyleEngine checks it for actual bindings. The scoped source document retains unchanged selector and declaration coordinates. New metadata for an unstyled layout/custom widget is staged atomically with the layer; rejection publishes neither. Existing global sheets continue to register the same targets as before.
Scope excludes descendants and rejects cross-scene, stale, closed and wrong-thread references before publication. Equal sheet/identity reuse keeps existing no-op and invalidation behavior. Theme-slot replacement preserves independent scoped APPLICATION and USER layers. File I/O remains deferred to admitted consumption and uses the existing bounded reader, file error carrier and source-aware parser; no watcher or loader is added. See the complete guide and installed consumer.
Scene::runApp(), ui::runApp(scene) and scene | ui::runApp() delegate to the same run() boundary: zero on success, one on a typed failure. All forms accept an optional stop token and a borrowed custom/replay ApplicationTerminal. The final UI stage, returned by ui::runApp(), borrows its lvalue or temporary scene for the synchronous call; it does not move it. scene.run() and scene | ui::run() retain the owning expected<ApplicationStats, ManagedError> result for embedding and explicit logs. Typed run does not invoke the final report sink or impose stderr I/O.
A program using ui::scene(recipe) constructs its recipe before entering the final runApp boundary. Allocation or capture-copy exceptions during that construction can still escape main; the exit-code policy does not retroactively catch them. Use the factory-based runApp(factory, setup) overload when the application also needs the library to guard recipe construction.
ui::quit() is a void convenience command for the current entered scene. scene.onKey(key::F10, ui::quit), ui::onKey(key::F10, ui::quit), button.onClick(ui::quit) and ui::onClick(button, ui::quit) use the same stop path. Bare commands retain the registration origin, including an explicitly supplied source location; a call inside a lambda retains that call's own site. Current ownership is resolved at invocation, so registering a lazy stage does not remember a previously run scene.
Current scene is scoped to actual facade recipe/setup/configure/run execution and managed key, button, custom-input, text-result/validator, checkbox and custom event/preparation callbacks. Those bridges also establish their owner during prepared direct dispatch. Managed property delivery uses its weak facade owner. Nested independent work suspends the caller's context; normal return and exceptions restore it. Cleanup, final reporting and owned capture retirement do not expose an unrelated outer scene. During configure/setup, a rejected short text mutation records the first setup failure before notifying observers. The current void callback finishes; later setup and terminal entry are skipped. A failure in a callback entered by another scene does not change the caller's setup state. A weak context does not retain the facade or widgets, survives facade moves, and is revoked before cleanup releases captures.
The library does not infer ownership for arbitrary raw router, property, provider or scheduler callbacks invoked directly by client code outside these entered bridges. Use an explicit SceneRef when such work belongs to another scene. Caller argument/temporary construction and arbitrary custom by-value parameter epilogues retain the C++ execution limits described below.
With no current live scene, the void command is a safe no-op without diagnostics, stderr or a deferred error. SceneRef::quit() remains the explicit checked API; an unavailable current snapshot has RUN/CLOSED internally. Existing UI affinity and notification/close/report guards still apply; context does not grant extra mutation authority. Quit failures use the same weak snapshot and live collector as ui::quit(scene.ref()), which remains supported. The explicit observing handle never keeps a destroyed scene alive. Adding the same-name overload makes untyped auto action = &ui::quit ambiguous; specify the desired function-pointer type. Existing typed pointers to the explicit-scene overload remain supported.
Scene::quit() requests orderly cancellation through the Application. It is UI-only and idempotent while the scene is live. Before preparation, or inside its recipe/configuration, the intent waits until complete successful mount and deferred configuration; bindings finish before cancellation. During a prepared configuration or running callback, the current action finishes before cleanup. Notification/close reentry returns sticky WOULD_BLOCK; a closed/moved scene returns CLOSED, and a foreign thread returns WRONG_THREAD without changing the owner. Pre-run quit preserves the native runner's opening/restoration path; it does not promise to skip terminal acquisition.
runApp delivers one final report after terminal close/restoration was attempted and the scene cleanup boundary returned. Primary, independent runner/restoration, and cleanup causes returned by the lifecycle remain in the owning SceneReport::failure envelope. A current lower-layer limitation remains: WidgetTree catches Widget::unmount exceptions and sends them only to its optional tree error sink; that path does not return them through managed cleanup. runApp does not recover swallowed callback errors or claim that every unmount hook succeeded. The default reportToStderr formatter uses symbolic categories, source locations and native error codes without C++ allocation. When restoration fails, ordinary stderr is a best-effort fallback; a restoration failure is retained rather than declared successful. Repeated final calls do not duplicate a report. Foreign-thread, moved-from and nested calls return one quietly: only an admitted outer call can establish the terminal restoration boundary. Use typed run()/checked() to inspect rejected-call causes.
onError is the application reaction channel: its non-veto notification timing is unchanged, and observer exceptions stay separate from the primary cause. reportOnError independently selects diagnostic delivery; neither registration order nor clearing an observer changes reporting priority:
Both method and ui::reportOnError(sink) pipe modifier own a copyable callable accepting const SceneReport& and returning void. Captures remain alive through synchronous delivery; explicitly borrowed services must outlive runApp. reportOnError() or reportOnError({}) selects the default sink. Reporting is a read-only final boundary: typed lifecycle reentry returns WOULD_BLOCK quietly, fluent mutation/registration attempts do nothing, and the completed result stays unchanged. Self-removal/replacement during delivery is rejected; the active sink and captures remain alive until it returns. Sink exceptions invoke the default formatter once with the original report, bypassing both the sink and onError; they do not replace the typed primary or recursively generate diagnostics. Success with recoverable diagnostics keeps exit zero and reports only bounded retained/dropped counts. The sink does not deliver each recoverable record: diagnostics() provides their detailed owning envelopes. Clean success is quiet.
Construction of recipes, captures, stages, and function arguments before final stage evaluation remains outside runApp. It does not catch arbitrary exceptions from that earlier work. Lazy recipe, configuration, and runtime callbacks execute inside their documented checked boundaries and preserve typed failures. Use an ordinary application try/catch around construction if its exceptions require an exit-code policy. The ui::runApp(factory, setup) overload can place recipe construction inside its checked boundary; argument evaluation before entering that boundary is still outside it.
The guide program captures observing Ref values and resolves the weak current scene when a command runs. A user callback that explicitly borrows &scene must keep that facade stationary and alive; a move does not rewrite arbitrary C++ captures. Compose consuming modifiers before installing such self-referencing callbacks.
An ordinary form can also use ui::scene to own its Application and ManagedScene. Preparation mounts the complete form and publishes its Refs; it performs no terminal I/O. Late Ref handlers can be registered directly in the pipe; they bind after successful mount, without a configure wrapper:
lineEdit(string_view) copies initial bytes immediately. The TextValue overload owns a literal, formatted value or resource expression and accepts an explicit TextResolver. It resolves under the scene's width policy at mount, creates an internal managed text state, and uses the editor binding. Confirmation modes, validation, paste, clipboard and Undo retain their behavior. The lineEdit(ManagedState<string>, ...) overload remains available for shared models. Ref-first forms support both kinds of initialization.
For CLI launch, return a lazy scene from an ordinary function and borrow typed settings with ui::opts(options). ui::applicationOptions(provider) reads those settings after successful parsing and before mounting. The final ui::runApp(argc, argv, parser) captures process snapshots and invokes the parser; help, version and parse failures return before the scene factory or terminal acquisition. See command-line startup for ui::lyra::cli, errors and snapshot lifetimes.
A scene can consume a direct description or a factory receiving ManagedScene&. The factory returns a description or expected<Description<T>, ManagedError>; it runs once at preparation and can create the states and models. Recipe and callable construction can throw before a checked boundary. Captures are owned; explicitly borrowed services must outlive use. Scene construction and operations are UI-affine. Move construction preserves the stable owner and thread identity; move assignment is unavailable. Moving or destroying an active owner, foreign-thread destruction, and destruction within a tree frame retain the terminate contract.
SceneOptions forwards ApplicationOptions, ManagedOptions and an optional borrowed SchedulerClock. maxConfigurations defaults to 64 and bounds pending configure/key closures. Before prepare, theme and observer replacements retain the latest setting. Configure and key registrations execute in registration order after complete mount. Prepared key handlers use the managed budget and newest matching chord consumes input. Direct ManagedScene::onInput still replaces that whole composition. Raw ui::key/KeyEvent bindings admit PRESS and REPEAT; string shortcuts default to PRESS.
The small pipe stages call the same methods:
ui::prepare(), ui::configure(...) and ui::onError(...) and ui::reportOnError(...) are also stages. Configuration stages accept both named and temporary adapters. With a named Scene, they return the same Scene& without relocating the facade. With an rvalue Scene, they first move the idle facade, then dispatch the same method; use std::move(scene) when deliberately consuming a named owner. Prepared idle owners may also move. Moving an active scene or moving it on a foreign thread retains the terminating move guard. Callbacks that must survive a move should capture SceneRef rather than the facade's address.
A stage owns its captures, but applying it may consume them. A named adapter is not a promise of repeated application. Configuration stages reject const facades, const mutable adapters, descriptions and adapter-to-adapter composition at overload resolution. run(terminal, stop) borrows the terminal while consuming the scene, so a named facade requires std::move(scene) for this typed final stage. The runApp final stage borrows either a named or temporary scene for its synchronous run and reporting. Modifiers remain lazy until explicit prepare/run/runApp; prepare mounts without terminal I/O. A pipe introduces no new runtime, parser or control modifier system.
Repeated prepare on a prepared owner is a no-op. prepareChecked() and checked() expose typed preparation/sticky failures; managed() only observes an already prepared live owner. diagnostics() snapshots the bounded collector. The first facade failure prevents further configuration actions. run() returns that first cause with independent runner/restoration and cleanup details. It closes the managed scene after every admitted attempt, including native open failure. Partial prepare/configure failures also close the owner; published refs then become stale/closed, rather than reusable empty slots. Successful completion and explicit close never remount or reopen the terminal. close() is idempotent and returns its own cleanup outcome.
Configure actions return void or exactly expected<void, ManagedError>. Rejected short text mutations inside an entered configure or stationary runApp setup scope latch the first typed failure before context allocation or observer reentry. The current ordinary void lambda finishes: its remaining statements still execute. Later configure stages and terminal entry are skipped, and normal cleanup follows. Explicit expected/return remains the way to leave the current lambda early. Earlier UI changes and external side effects are not rolled back.
Empty, unbound and stale observing refs also stop their active UI setup. A target owned on another thread is never inspected or notified through that foreign owner; the caller-operation error belongs to the entered setup on this thread. Nested independent setup scenes restore the outer context when they return. Independent factory/recipe execution, lifecycle cleanup, facade-owned capture retirement and final report delivery suspend the caller's setup attribution. Only an actual configure or stationary setup opens its own setup-fatal scope; a failed short write in recipe-only code does not silently acquire the outer scene's scope. This isolation covers entered library execution and the callback storage owned and retired by the facade. It does not extend to construction or destruction of caller arguments, temporaries, or arbitrary user-defined by-value callback parameters outside that execution. In particular, user work in a moved-from custom configure callable's destructor follows the setup scope active when that destructor actually runs. The standard onError and reportOnError handlers transfer incoming storage under isolation, including allocation failure and rejected entry; their incoming captures retire before that isolation ends. Stationary setup finishes short-error delivery before expected/exception handling can clean up its publication, so all return forms preserve one primary notification. Outside an entered setup scope, short runtime errors keep the recoverable policy. Arbitrary low-level reportError calls remain nonfatal, including inside void configure; ignored low-level expected results remain the caller's responsibility. The automatic setup stop covers TextProperty assignment, +=, set and append, including concatenation assignment and explicit programmatic editor text writes. Undo/Redo/stopGrouping keep their checked EditorCommandResult policy; Ref click registration remains its checked/recoverable operation. These are not silently turned into setup-fatal commands when their result is ignored.
Returning the exact short mutation's error through expected preserves an opaque same-collector reporting receipt, so the configure boundary does not report it twice. History overflow, missing observer and observer throw do not erase that receipt or the setup stop. A fresh equal-valued error and the intentional manual reportError(error); return unexpected(error); case remain distinct boundary events. Existing EditorCommandResult key/click adapters retain their own receipt contract; extracting their .result() still deliberately loses that provenance.
ManagedError remains an aggregate. Its additive operation and execution labels use library static storage, and operationOrigin preserves the entered source even when bounded diagnostic contexts cannot be allocated. phase remains the original managed operation category; execution names the facade boundary and setupStopped describes the response. Primary, restoration and cleanup causes remain independent typed values. The extra fields change data representation; this does not promise binary ABI compatibility. checked() only inspects state; it never executes deferred configure or mounting.
onError observes errors without vetoing operations. The first pre-owner failure uses one owning fallback diagnostic with an empty node and no contexts; a late observer receives an undelivered failure once. Run notification uses the exact managed receipt of whether the observer was invoked for its returned primary; finish-after-stop failures get a fallback notification, while already notified failures are not repeated. Observer exceptions remain separate from the original cause. Lifecycle/configuration reentry returns or stores WOULD_BLOCK and never retires an active owner. Runtime theme/key mutation can delegate to the existing managed boundary; failure is returned after run exits and cleanup completes. Foreign-thread checked calls return WRONG_THREAD before mutable state access; fluent calls there leave state untouched, and checked() on that thread exposes WRONG_THREAD. Fluent chaining is not a concurrent thread-safe interface.
Internal theme and callback transfers belong to the checked facade boundary, including rvalue methods and pipe dispatch. Allocation failures become sticky typed errors and retire a prepared owner. Constructing caller arguments or a pipe adapter before dispatch may still throw. Final teardown releases retained state, runtime captures and owning option services while the complete facade state remains guarded; lifecycle reentry is rejected before owner destruction.
ui::onClick(ref, callback) installs a scene-owned handler after the complete recipe mounts. It accepts a ui::Ref<Button> belonging to that same scene; no binding token or presentation synchronization is required. The observing ref must name a button: stale, cross-scene and incomplete-mount references produce typed setup errors. ui::hbox and ui::vbox are forwarding aliases for ui::row and ui::column, including their reference and layout-options overloads. They create the same retained layouts and add no runtime layer.
A handler can take no arguments or borrow ui::ClickParams&. Multiple handlers run in registration order. For example, replace the single handler in the guide program with these two stages:
followed by:
Without Shift the first callback leaves the chain running and the second appends Hello!. With an admitted Shift-modified activation, the first appends HELLO! and skips the second. A terminal may reserve Shift+mouse for selection instead of reporting it; the library cannot infer an event the terminal withheld.
| Member | Meaning and lifetime |
|---|---|
| target | Observing Node<Button> identity. Does not own the control; may become stale after removal. |
| mods | Original semantic modifiers; query has(key::SHIFT), has(key::ALT) or has(key::CTRL). No physical left/right distinction is claimed. |
| source | ClickSource::KEYBOARD, MOUSE or PROGRAMMATIC. Enter-to-action translation preserves keyboard origin. |
| event | Owning original routed activation. Translated actions carry their source, not a reconstructed raw keyboard record. |
| stop() | Stops remaining handlers of this synchronous activation. Alias: stopPropagation(). |
| propagationStopped() | Reads the stop flag of this particular context or saved copy. |
The public event metadata is read-only. Callbacks borrow the shared parameters only during delivery. Copy construction (for example, auto snapshot = params) retains an owning event snapshot and observing identity; calling stop() on a saved copy cannot affect the original chain. For an optional snapshot, use snapshot.emplace(params); const metadata deliberately prevents whole-object assignment. Activation already returns HANDLED through the button routing, so ancestor callbacks are suppressed even without stop(). This is not a new DOM bubbling model.
The binding retains the chain, but only observes the scene lifetime. The chain owns callback records, never the scene or the binding. The active record stays alive through self-removal. Cleanup retires the registry and releases its handler budget before destroying inactive captures; dispatch stops before using a retired identity. This ownership is the same for keyboard, mouse and programmatic input.
Key and click actions may return void, expected<T, TreeError> or the existing EditorCommandResult. A successful expected payload is ignored and destroyed before leaving the callback scope. In particular, a successful false payload still means the action was handled; it does not request input fallthrough. The adapter does not interpret fields inside a successful payload. If an application needs a notification-delivery receipt or another success-side status, inspect that receipt explicitly before returning from the callback.
Return field.undo() or field.redo() directly to preserve its exact already-reported provenance. The first returned failure or exception stops the remaining handlers and reaches the typed diagnostics; an error already reported by that exact editor command is not reported a second time. Unrelated failures and observer failures remain distinct. Earlier external side effects are not rolled back.
A short mutation such as field.text() += "!" in a void callback still uses the normal text-property diagnostics. It does not implicitly return its failure or abort the remaining C++ instructions. Choose an explicit checked return or stop() when the next action depends on success. The setup error policy described above applies to entered configure and stationary setup scopes. Successful text edits keep the editor's configured model, validation and Undo behavior. A mutation is not a new revision-management API.
Removing, hiding or disabling the target or an ancestor, or closing the scene, ends the chain before the next handler. The currently executing owning callback survives cleanup until it returns; no callback retains a raw pointer to a removed widget. Captured references to application objects remain the caller's lifetime responsibility. These operations are UI-affine.
Appending to an chain during delivery takes effect on the next event; the current event uses its original handler count. Creating a new action binding while the router dispatches retains the WOULD_BLOCK result. Manual per-handler disconnect handles are not part of this interface.
ManagedOptions::maxClickHandlers defaults to 256 across the scene and maxClickHandlersPerNode to 64. Both must be greater than zero. Exceeding either returns TreeError::NODE_LIMIT without replacing handlers; allocation failure returns NO_MEMORY. SceneOptions::maxConfigurations independently defaults to 64 and bounds all deferred click/key/configure registrations before preparation. Raise the appropriate budget explicitly for larger forms.
Ref<Button>::onClick, recipe .onClick and ManagedScene::onClick retain their single-binding contract and reject duplicate bindings. Their no-argument form admits only unmodified activation; parameterized callbacks admit modifiers. The pipe chain allows both no-argument and parameterized callbacks on a modified activation. Mixing a pre-single binding with a pipe chain is rejected.
Key aliases and chords use semantic modifiers supplied by the terminal decoder:
These are alternative registrations shown independently. Choose one form for one action. A list or string registers one owning handler; duplicate alternatives invoke it once. Names in strings ignore ASCII case. Letter aliases match either ASCII letter case, with exact modifiers. Other Unicode text passes through unless an explicitly supported shortcut matches it. Modified text such as decoded ESC + q is admitted without a second input router.
New shortcut bindings admit PRESS by default. Select REPEAT explicitly with ui::repeat or ui::pressRepeat; the compatibility ShortcutBehavior option also enables repeats. See phase selection. Existing ui::key(InputKey::F10) / KeyEvent bindings retain PRESS and REPEAT behavior. A nonmatching shortcut delegates to the previous handler and normal widget routing. The newest matching binding wins.
parseShortcut provides a checked expected<Shortcut, ShortcutError> path. Syntax diagnostics include a typed cause and a zero-based byte offset; no caller string is borrowed after registration. Default parser budgets are 4096 bytes, 32 alternatives and 8 strokes per alternative, configurable through ShortcutOptions. Invalid syntax or exhausted registration budgets do not replace handlers. Facade errors reach the scene diagnostics.
Multi-stroke commands use the same registration path:
Ctrl+K+K means Ctrl+K followed by Ctrl+K. All modifiers in one plus-separated segment apply to every key in that segment, including modifiers written after a key. Comma starts a segment with independent modifiers: Ctrl+K,K requires an unmodified second K. No held-key state is inferred. Shortcut::sequences owns typed ShortcutSequence values while alternatives retains its single-chord meaning; their combined count uses maxAlternatives.
At each stroke the newest matching registration decides whether to invoke a terminal command or wait for continuation. A prefix retains compatible longer candidates from older registrations, but suppresses older terminal commands permanently. Within one registration, an alternative that is a proper prefix of another is rejected with AMBIGUOUS_PREFIX; duplicate complete alternatives still invoke once. Pending continuation precedes standalone root bindings.
An unmatched admitted PRESS clears the prefix and processes the current event normally once. Previously consumed prefix events are never replayed. An ignored phase or unmatched REPEAT/RELEASE keeps the prefix and passes through normally; if that root pass starts another prefix, the new group replaces the old one. Explicit phase selections apply independently to every stroke. Thus a PRESS between two explicitly selected RELEASE strokes does not cancel the sequence. Text represents PRESS only; backends do not gain new event phases.
Unmodified Escape PRESS cancels pending input and is consumed. Such Escape in a continuation is rejected with RESERVED_CANCEL; modified Escape remains an exact chord. Focus changes, visibility/enabled changes, removal and input replacement invalidate a pending prefix, including changes away and back between strokes. The conservative tree invalidation also includes mutations of unrelated nodes; ordinary paint/layout invalidation does not cancel it.
ManagedOptions::keySequenceTimeout defaults to 1000 milliseconds and must be positive; configure it through SceneOptions::managed. Each accepted nonterminal stroke restarts the timeout. Expiration clears the prefix without invoking any command, even before the scheduler dispatches its timer. There is one scoped timer and no idle redraw. Completion clears pending state before invoking the callback; its captures survive self-removal, close and input replacement. Failed registration preserves old bindings and pending state. A timer-arm failure uses the fatal input error path and leaves no pending command.
Generic SHIFT, ALT and CTRL describe observed semantic modifiers. The API does not infer left/right identity or AltGr from terminal events. Current-scene quit uses these same registrations and event selections; it changes no input phases.
A description owns its child descriptions and callback objects. Standard text factories copy their input immediately, so a description can outlive the source std::string or std::string_view. Creating a description does not mount widgets or subscribe to events. Descriptions are movable and noncopyable; mounting consumes them. Reusing a consumed or moved-from description returns TreeError::INVALID_ARGUMENT through ManagedError.
Use ui::vbox(...) and ui::hbox(...) for nested composition. Their overloads accept LinearOptions before the children when gaps, padding or alignment need customization. Standard control factories are label, button, checkbox and lineEdit; virtualList, virtualTable and chart compose managed virtual views. Binding state and models belong to the scene's ManagedScene. custom<T>(args...) constructs the concrete public Widget subtype, including final classes. It does not introduce another base class.
Factories and fluent modifiers construct ordinary C++ values: allocation or user-defined argument-copy exceptions can escape while assembling a description. The ui::mount(scene, std::move(description)) boundary returns typed managed errors for mount, binding and initialization failures. A failed attempt removes its new subtree and releases its managed registration budget. Existing siblings and states remain intact. External side effects of user callbacks are not rolled back. The original cause and an independent cleanup error remain distinguishable.
ManagedScene::remove retires identities immediately. Managed mutations reentering that call return WOULD_BLOCK. If the caller holds an outer tree.edit or withScope borrow, physical destruction and unmount wait for that borrow to finish. Those deferred hooks follow the tree contract and can remove other nodes; their external effects are not undone by description rollback.
ui::NodeRef<T> is a copyable observing slot. Attach it with .reference(ref) and obtain the checked Node<T> through ref.node(). References are published after the entire description mounts successfully; before that they are empty. Reusing a populated slot or binding it twice in one description is rejected. Removing the mounted widget leaves a stale checked identity, not a live owning pointer. Application, ManagedScene and mutable widget operations keep their UI-thread contracts.
For widgets, ui::Ref<T> shares the same publication transaction and low-level node() observation. It adds fluent text properties for control captions and LineEdit drafts, including owning read-only concatenation. The NodeRef<T> interface remains available for other checked tree access.
Composite views use the same declaration syntax, while keeping their existing commands rather than inventing widget operations:
| Role | Declaration | Bind with | Commands |
|---|---|---|---|
| Button / editor | ui::Ref<Button>, ui::Ref<LineEdit> | ui::button, ui::lineEdit | Text, focus and the control's operations |
| Dialog | ui::Ref<Dialog> | ui::dialog | open(), dismiss() |
| Help view | ui::Ref<HelpView> | ui::helpView | Checked open(), close() |
| Choice dialog | ui::Ref<MessageDialog> | ui::messageBox, ui::confirmDialog, ui::unsavedChangesDialog | open(callback), cancel(), lastResult(), receive(context) |
| Theme selector | ui::Ref<ThemeSelector> | ui::themeSelector | Checked open(), apply(), cancel(), closeKeepingPreview(), lastApply() |
| Notification surface | ui::Ref<Overlay> | ui::notifications | Observe the actual surface node |
The names above assume using namespace portals. Pass the reference as the first factory argument. MessageDialog and ThemeSelector name the existing composite facades: the new references share their observations and add no second slot or owner. Their old handles, ui::MessageBox and ui::ThemeSelectorRef, remain supported. Copies observe the same identity; moving transfers the observation. Creation has the same fallible cold-handle allocation as before. MessageDialog avoids the Win32 MessageBox macro; including Windows headers does not change the underlying facade's class name.
The MessageDialog and ThemeSelector references do not provide node(), text() or focus(). For explicit access to their actual dialog widget, attach a separate ui::Ref<Dialog> with the recipe's .reference(view). Existing checked commands remain checked: return a selector's result from an action to propagate its failure through the normal runner boundary. lastApply() retains its documented owning result after view retirement; it does not keep a scene alive.
ThemeSelectionRef observes a theme model, and NotificationCenter is a posting service. They retain their distinct roles. ToastMessage describes one message; posting returns its existing receipt, not a widget reference.
Ordinary forms need only the declarative factory. A custom provider can opt into ui::scene([](ManagedScene &owner, Application &app) { ... }) and scene.configure([](ManagedScene &owner, Application &app) { ... }) to use the same scheduler, router and tree. Existing one-argument factories/configurations keep priority, including generic and variadic callbacks. Results obey the same typed-error rules as the original overloads.
Application& is a UI-affine borrow, not a worker-thread API or an independent owner. It supplies UI services; run the facade through Scene, never by calling its borrowed Application::run directly from factory, configure or shutdown. Do not retain it beyond the facade lifetime. Register scene.onStop(...) before preparation when partial provider construction needs cleanup. The one owning, replaceable shutdown callback runs once before nodes and models retire, including failed preparation, explicit close and destruction. It accepts void or exactly expected<void, ManagedError>. Registering a replacement retires the old callback without calling it. An exception becomes a typed cleanup failure; managed cleanup still runs. An earlier setup/input/run error remains primary. Checked Scene methods and ManagedScene::run reject lifecycle reentry. Raw Application::run retains its documented prohibition on entering run from hooks; the borrow does not turn that low-level API into an independent runner. Shutdown executes with empty current-scene/setup contexts, so use explicit provider cancellation rather than contextual ui::quit() there.
The complete dashboard composition uses these opt-in hooks. Its provider retains its scheduler and bounded page loading, and stops before the model it publishes to is destroyed. Basic forms do not need these hooks or a manual Application.
Standard controls inherit their normal managed bindings, styles and LineEdit semantics. A business result callback runs after standard behavior; it cannot undo a committed edit or checkbox toggle. The LineEdit validator remains the commit veto. No manual token storage or standard presentation sync is needed.
ui::LineEditConfig uses named fields for the editor result callback, editor options, sizing, clipboard and validation. For example, ui::lineEdit(name, {.validate = nonempty}) does not require positional placeholder arguments. Invalid factory text retains its original TextError in ManagedError::text; construction conveniences do not discard diagnostic kind or byte offset.
Fluent .style(target), .onEvent(handler) and .onPrepare(handler) attach custom identity and behavior through the same managed APIs. .setup(callback) is the explicit escape hatch for low-level initialization. Its callback receives the scene and typed node and returns expected<void, ManagedError>. Existing router, layout and tree operations remain available through the caller's Application; the composition layer does not hide them behind a new runtime.
Custom constructor arguments and lambda captures still obey C++ ownership rules. Owning a callback does not make objects captured by reference live longer. Explicit borrowed pointers or reference wrappers must remain valid for the uses made by the custom widget. Consult the custom factory reference for argument storage and forwarding requirements; reference members in user types remain borrowed.
ControlContext and a loaded scene store sparse initial values. An absent value keeps the receiving factory's default; an explicit false or 0 remains a value and overrides an inherited one. These settings do not reconfigure a mounted widget. Runtime changes use the existing typed widget APIs.
The type schema determines which canonical ControlSettings leaves each concrete control accepts. CONFIGURATION resources use the exact case-sensitive paths below. Counts use unsigned decimal literals; cell extents are nonnegative signed integers. Finite floating-point literals are accepted for gauge values and wheel steps; arbitrary expressions are not evaluated.
| Property path(s) | C++ type, units, validation | Default when omitted |
|---|---|---|
| text, placeholder | TextValue; owning text/resource expression. placeholder must satisfy the receiving editor's text and width limits. | text uses the factory's initial text (empty when omitted); placeholder is absent. |
| width, height, flex | std::optional<std::int32_t> cells, nonnegative; std::optional<std::uint32_t> flex weight, positive. | No size override; the factory's SizePolicy applies. |
| gap | optional<int32_t> nonnegative terminal cells. | LinearOptions::gap, zero. |
| state, cycle | CheckState: UNCHECKED, CHECKED, MIXED; CheckCycle: TWO_STATE, THREE_STATE. Invalid values fail preparation; ThreeState fixes the cycle to THREE_STATE. | Unchecked and TWO_STATE for CheckBox; ThreeState retains its fixed cycle. |
| editMode, readOnly, programmaticChange, displayMode | EditMode (IMMEDIATE, ON_COMPLETION, EXPLICIT); bool; ProgrammaticChange (RECORD, RESET_BASELINE); LineEditDisplayMode (NORMAL, PASSWORD, NO_ECHO). | IMMEDIATE, false, RECORD, NORMAL. |
| history.enabled, history.maxOperations, history.maxBytes, history.groupTyping, history.groupDeletion | bool, size_t operations, size_t retained bytes, bool, bool. Zero operation/byte capacity disables retention. | TextHistoryOptions: true, 128 operations, 1 MiB, true, true. |
| columns, rows, flow, columnGap, rowGap, padding.left/top/right/bottom, maxTracksPerAxis, maxPlacements, maxPlacementWork, scroll | Grid counts/budgets are size_t and positive; flow is ROW_MAJOR or COLUMN_MAJOR; gaps/insets are nonnegative int32_t cells; scroll is bool. | Omission preserves the Grid recipe defaults; gaps/insets are zero, flow is row-major for automatic placement, budgets are 4096 tracks, 4096 placements and 65536 placement-work units, scrolling is off. |
| padding.left/top/right/bottom, mainAlign, crossAlign, overflow | Insets are nonnegative int32_t cells. Alignment is LayoutAlign: START, CENTER, END, STRETCH. overflow is LayoutOverflow; only CLIP is supported. Invalid values fail validation. | LayoutPadding{} (zero each side), main START, cross STRETCH, CLIP. These paths belong to VBox/HBox schemas. |
| limits.maxInputBytes, limits.maxClusterBytes, limits.maxGraphemes, limits.maxCells | size_t input bytes, per-grapheme-cluster bytes, grapheme count, and terminal cells. Zero is valid and restrictive; each nonempty input must satisfy the corresponding limit. | LineEditOptions::limits: 4096 bytes, 4096 bytes, 4096 graphemes, 8192 cells. |
| chrome | ButtonChrome: BRACKETS, NONE. Applies to Button captions and actions. | The receiving factory's chrome; plainButton keeps NONE. |
| glyphs, maxPaintCells | PrimitiveGlyphs: UNICODE, ASCII; positive size_t paint-work cap. Border, Gauge and scroll controls accept these leaves. | UNICODE, 16384; the existing control defines whether the budget counts perimeter, area or track work. |
| value, minimum, maximum, preferredWidth | Finite double gauge values, maximum > minimum, inclusive value range; nonnegative int32_t intrinsic width in cells. | Gauge factory value; range 0–1 and preferred width 10. |
| wheelStep, keyStep, pageOverlap, minimumThumb, focusable | Scroll controls: positive finite double logical wheel cells; positive uint64_t key cells; uint64_t shared page cells including zero; positive int32_t thumb cells; bool. | 3, 1, 1, 1, true. readOnly is also accepted, default false; checked programmatic scrolling remains available. |
| horizontal, vertical, placement | ScrollArea policies: NEVER, AUTO, ALWAYS; placement RESERVED, OVERLAY, ON_FRAME. ON_FRAME requires an effective frame. | Both AUTO, placement RESERVED. |
| axis | Standalone ScrollBar: HORIZONTAL, VERTICAL. | VERTICAL, unless its receiving factory supplies another axis. |
| frame.enabled, frame.glyphs, frame.maxPaintCells | Optional frame on sized recipes; ScrollArea reuses its own frame. Explicit false removes it; frame-specific leaves require an enabled frame. See frames. | No frame. Explicit true creates default frame options only when absent. |
| frame.pattern, frame.sides.top/right/bottom/left, frame.title, frame.titleAlignment, frame.maxTitleBytes, frame.customGlyphs.* | Owning pattern, partial edges, resolved title and six custom one-cell glyphs. See resource syntax. | SINGLE, all sides, empty title, START, 4096 title bytes, no custom source. |
| horizontalAlign, verticalAlign | Overlay: LayoutAlign (START, CENTER, END, STRETCH); padding.* also applies. These differ from placement alignment in a containing Grid. | Both STRETCH; zero padding. Explicit factory options remain the baseline. |
| initiallyOpen | HelpView: boolean, using the existing focus-return lifecycle. | false. |
| format.maxBytesPerBinding, format.strokeSeparator, format.alternativeSeparator, format.repeatMarker, format.releaseMarker, format.unknownMarker | HelpView/KeyHints: positive whole-row byte cap and owning literal UTF-8 strings. .format({...}) and ui::format({...}) apply sparse patches. | 8192; " then ", " / ", " [repeat]", " [release]", " [?]". Omitted leaves preserve actual factory options. |
| emptyText, unavailableText | HelpView/KeyHints: owning literal UTF-8, without expression evaluation or i18n resolution. | HelpView: "No key bindings", "Help unavailable"; KeyHints: empty, "?". Native presentation budgets still apply. |
| entrySeparator, overflowMarker | KeyHints: literal UTF-8; overflow marker must be nonempty. | Two spaces, "+". |
| rowHeight, overscanRows | VirtualList/VirtualTable: positive cell rows per logical row; nonnegative additional requested rows per side. Explicit zero overscan is valid. | 1, 2. Omitted leaves preserve actual factory options. |
| maxColumns, maxPreparedCells, maxPreparedTextBytes | VirtualTable: positive column, prepared body-cell and header/body UTF-8 limits. | 64, 16384, 1048576. |
| mode, chartGlyphSet, candleGap | Chart: LINE/CANDLES, ASCII/BOX_DRAWING, and a nonnegative gap in cell columns. | LINE, ASCII, 0. Omitted leaves preserve actual factory options. |
| yRange.enabled, yRange.minimum, yRange.maximum | Chart: optional explicit Y-scale with finite endpoints; equal endpoints are valid. false clears it; bound-only patches require an existing explicit range. | Automatic visible-range scale; enabling without bounds starts with native (0, 0). |
| showStatus, statusRows, contentPolicy, spinnerInterval | DataStateView: status-strip presence, positive int32_t row height, KEEP_BODY/REPLACE and positive uint64_t monotonic milliseconds. | true, 1, KEEP_BODY, 100; omitted settings preserve the actual receiving configuration. |
| labels.loading/empty/error/offline/refreshing/retry | Owning text expressions; .labels({...}) and ui::labels({...}) patch only supplied captions. | Loading..., No data, Unable to load data, Offline, Refreshing..., Retry. |
| maxLayers | OverlayHost: positive size_t registered-layer cap, including hidden layers. | 32. |
| title, dialog.mode, dialog.placement | Owning Dialog caption; MODAL/NON_MODAL; CENTER/BELOW_START/ABOVE_START. | Actual factory title; MODAL, CENTER. The scoped resource fallback requires an effective supplied title; an empty string is valid. |
| dialog.maximumPanelSize.width/height, dialog.viewportMargin, dialog.anchorGap | Independent positive int32_t panel caps and nonnegative margin/gap, in cells. Caps never narrow the full-host structural Dialog root. | 60×20, 1, 1. |
| dialog.closeButton.enabled/placement/focusable | Optional three-cell [x] on the top frame edge, at START or END; optional Tab focus. | false, END, false. |
| dialog.closeOnEscape, dialog.frame.glyphs/maxPaintCells | Allow Escape cancellation; UNICODE/ASCII border glyphs and positive opaque-panel work cap. The panel frame remains mandatory. | true, UNICODE, 16384. |
| body | Owning MessageBox explanation; .body(...) / ui::body(...) apply to the actual native message recipe. | Actual captured explanation. |
| message.labels.acknowledge/confirm/save/discard/cancel/yes/no | Owning text expressions. Only active actions are resolved; captions must be nonempty and single-line. | OK, Continue, Save, Discard, Cancel, Yes, No. |
| message.buttons, message.order.first/second/third | Standard preset and optional positions in an exact permutation of its active choices. | Captured preset and order; see dialog sets. |
| message.defaultChoice.enabled/value, message.allowDestructiveDefault | Optional MessageChoice; active membership and destructive-default permission remain native checks. A supplied value activates the choice; explicit false clears it. Invalid enum values are rejected even when inactive. | Safe preset default: ACKNOWLEDGE for OK, NO for YES_NO, otherwise CANCEL; permission false. Enabling without a value retains a captured choice or uses the safe preset default. |
| message.textLimits.maxInputBytes/maxClusterBytes/maxGraphemes/maxCells, message.maxBodyLines | Positive per-expression UTF-8/cluster/grapheme/cell limits and wrapped-body line cap. .messageSettings({...}) / ui::messageSettings({...}) patch supplied message leaves. | 16384, 4096, 16384, 32768; 4096 lines. |
| notification.capacity/maxVisible | Positive retained/visible notification caps; visible cap must not exceed effective capacity. | 32, 3. |
| notification.placement/maximumWidth/margin/gap | BOTTOM_END/TOP_END/BOTTOM_START/TOP_START; positive width cap and nonnegative viewport margin/gap in cells. | BOTTOM_END, 48, 1, 1. |
| notification.overflow/refreshDeduplicated/reducedMotion | DROP_OLDEST_PENDING/REJECT_NEW; refresh an existing transient deadline; disable indicator alternation. | DROP_OLDEST_PENDING, false, false. |
| notification.textLimits.maxInputBytes/maxClusterBytes/maxGraphemes/maxCells | Positive validation limits for one resolved message. | 16384, 4096, 16384, 32768. |
| notification.actionLabelBytes/dedupKeyBytes/maxPaintCells | Positive action-label/deduplication-key byte caps and per-card paint-area cap. | 256, 128, 16384. |
| themeSelector.labels.apply/cancel/closeKeepingPreview/emptyStatus/errorStatus/conflictStatus | Owning view captions/status expressions; native .themeSelectorSettings({...}) and ui::themeSelectorSettings({...}) patch supplied leaves. | Apply, Cancel, Close (keep preview), Choose a theme to preview, Theme action failed; retry or close keeping preview, Theme changed elsewhere; preview again or close keeping preview. |
| themeSelector.textLimits.maxInputBytes/maxClusterBytes/maxGraphemes/maxCells | Positive validation limits for one resolved view caption/status. | 4096, 4096, 4096, 8192. |
| themeSelector.openingShortcut.enabled/value | Optional existing key-binding text. A value activates it, false clears it; true without a value retains the captured binding or restores the native default. Invalid supplied syntax is rejected even when disabled. | Ctrl+K, Ctrl+T. |
| themeCatalog.maxChoices/maxIdBytes/maxLabelBytes/maxDescriptionBytes/maxTextBytes | Positive catalog normalization caps: entries, ID bytes, resolved label/description bytes, aggregate logical text bytes. | 64, 128, 512, 2048, 1048576. |
| themeCatalog.textLimits.maxInputBytes/maxClusterBytes/maxGraphemes/maxCells | Positive per-value text validation limits. | 2048, 4096, 16384, 32768. |
| themeCatalog.initialId.enabled/value | Owning choice ID, not a localized caption. A value enables startup preview+commit; false clears it. true without a value retains a captured ID or fails with INVALID_ARGUMENT if none exists. | No initial committed choice. |
| themeCatalog.layers.enabled/maxLayers/maxRules/maxDeclarations/maxOwnedBytes | Optional first-preview layer admission. Numeric fields activate captured/default options unless explicitly disabled; supplied caps must be positive. An activated set requires at least two layers. false clears the optional. | Absent: established engine budgets or defaults 16, 1024, 6144, 1048576. |
Instance id, owning space-separated classes, visible and enabled are separate from scalar ControlSettings. Their native methods and pipes preserve the real control type. Hidden or disabled controls retain the existing tree and input semantics.
For native ScrollArea, horizontal and vertical are scroll policies. A containing Grid's placement alignment can be set separately with the existing .gridItem(...) recipe. Caller-registered types retain their own schema and the existing generic Grid placement syntax. An applicable frame{...} is a property group unless a registered child type owns the name frame; in that case bare frame{...} remains the child and frame={...} explicitly selects the property group.
Padding has one canonical path per side, shared by Grid and VBox/HBox. placeHolder is accepted as a CONFIGURATION alias for placeholder; it canonicalizes before duplicate checks. The alias does not add a property. ControlPropertyDescriptor keeps the aggregate prefix path, kind, depth, enumNames; its optional alias span follows those fields. SceneResourceArguments likewise retains its existing aggregate prefix text, id, width, height, flex, gap, checked; settings, visible and enabled follow it. ControlContext::registerType selects a subset of this canonical vocabulary rather than adding arbitrary property names. See TextLimits, LineEditOptions, LinearOptions and GridOptions for the receiving defaults and contracts.
KeyHints{help="guide"} binds to a HelpView instance with ID guide in the same resource; forward references are supported. With no help, exactly one declared HelpView-capable instance is required. Erased Widget factories require an explicit ID and are checked by the existing mount finalizer. A missing, ambiguous or wrong target produces a typed setup error and rolls back pending references. help is instance binding metadata, not a ControlSettings scalar. These resource controls use the same canonical key registrations as their native counterparts.
Message dialogs retain their native safety rules: MODAL and Escape cancellation are required. Their already validated internal panel does not inherit ordinary Dialog defaults a second time. A plain Dialog does not accept message-specific settings.
Resource binding requires a real captured message facade. The existing fluent registration collector also accepts the canonical semantic schema; errors are retained for prepareChecked() / runApp() rather than requiring a manual registration check:
The registry reads the schema metadata only during registration and retains an owning finite selection. A partial/foreign schema is rejected. The factory must return the actual native message recipe, including through type erasure; an ordinary Dialog is rejected during checked setup. A Prompt resource can override the captured title/body and settings; callbacks and question.open(...) remain code. Explicit factory localization takes priority; the resource resolver is only a synchronous constructor fallback for this opt-in binding.
The message schema also accepts message.buttons (OK, OK_CANCEL, YES_NO, YES_NO_CANCEL, CONFIRM_CANCEL, SAVE_DISCARD_CANCEL), message.labels.yes/no, and message.order.first/second/third. Order entries use the MessageChoice names. Omitted positions retain the selected preset or captured order; the final order must be an exact permutation of the active choices. Setting a default without an admissible active choice fails checked preparation. Resetting an explicit default selects the safe default of the effective preset, including NO for YES_NO.
dialog.closeButton.enabled, dialog.closeButton.placement (START/END) and dialog.closeButton.focusable configure the same optional native frame button as .closeButton(). Ordinary Dialogs support these geometry settings without acquiring a message-result capability. The native panel keeps its existing four-sided BorderOptions frame.
An explicitly message-schema-bound factory can receive one resource child as its owning custom body. The child replaces its captured paragraph or body recipe. Combining that child with an explicit body text override is an error. A resource never stores an executable result callback; it remains attached through the captured facade in C++.
Notifications use .notificationSettings({...}) or ui::notificationSettings({...}); omitted leaves retain the captured NotificationOptions. Explicit Notifications defaults apply to that semantic composition. Unrelated ordinary Overlay defaults still do not reinterpret it. Overlay layout/size settings retain the actual surface identity and source-over-factory priority.
The existing explicit native .variant("MyOverlay") with an Overlay-derived type remains a style-only path: it preserves the original visual identity and local factory settings without inheriting that variant's construction settings, ordinary Overlay defaults or new Notifications defaults. Use a Notifications-derived semantic variant when construction-setting inheritance is intended.
Resource factories capture an actual center and complete body and opt in with ui::controlPropertySchema("Notifications"). This does not add an unbound resource constructor or serialize individual toast commands. The resource resolver is borrowed only during scene preparation and is not retained by the center; provide NotificationOptions::textResolver explicitly for later runtime posts.
ToastOptions belongs to each runtime request: severity defaults to INFO, duration to 5000 milliseconds (nullopt is persistent), deduplication key to empty, and dismissOnAction to true. Its optional indicator defaults to disabled, glyph !, no alternating background, white foreground, red alert background and 500-millisecond period. These request settings remain the existing C++ posting API.
The ThemeSelector semantic schema configures the real view for either an existing same-scene model or the existing default-catalog constructor. title defaults to Themes; omitted leaves preserve actual captured options. The view retains native modal behavior and disables eager Escape closure. Its internal Dialog does not inherit ordinary Dialog defaults again, and the default-catalog constructor applies view settings once before delegating internally.
A registered factory supplies the actual selector facade and model/catalog and opts in with ui::controlPropertySchema("ThemeSelector"); a plain Dialog cannot acquire this capability from metadata. The resource node owns no external body children: the native view constructs its choices, status and actions. Own localization has priority; the resource resolver is only a synchronous preparation-time fallback and is not retained in future callbacks. onCommitted, choice factories and model/engine identities remain code-owned.
The actual default-catalog constructor also accepts .themeCatalogSettings({...}) and ui::themeCatalogSettings({...}). Resource factories expose these properties explicitly with ui::controlPropertySchema("ThemeSelectorCatalog"). An existing-model selector rejects catalog-only properties; metadata cannot turn it into an owning catalog.
For an actual catalog, initial settings resolve in this order: ThemeSelector defaults, ThemeSelectorCatalog defaults, the named variant chain, then explicit instance values. Existing view-derived variants and old ThemeSelector resource registrations remain compatible. Old view metadata still rejects explicit themeCatalog.* inputs before calling its factory. If that factory returns an actual catalog, catalog defaults apply from the original sparse input, retaining their provenance. Any additional budget reservation is checked after the factory returns, before model installation; effects already performed inside a user factory are not rolled back.
Omitted catalog settings preserve captured options, choices and callbacks. Startup selection uses the existing preview/commit path and does not call onCommitted. Optional layer budgets are admitted by the existing engine at preview: unequal already established budgets produce INVALID_ARGUMENT. These are initial settings, not a way to reconfigure a mounted selector or rebase an external model.
The built-in resource registry supplies eight ordinary factories. Grid, Border, Gauge, ScrollArea, ScrollBar, Overlay, HelpView, KeyHints, DataStateView, OverlayHost and Dialog also have scoped CONFIGURATION fallbacks; they do not reserve names against an explicit registration or change the legacy registry. The table records current resource support and omissions; an omitted scalar or declarative option is not thereby a permanent C++-only contract. Applications can register additional C++ factories, while callbacks, models, providers and captured behavior remain code-owned.
| Current family and C++ entry points | Built-in scene-resource properties | Not currently accepted by the resource loader |
|---|---|---|
| Linear containers: row, column, linear | VBox/HBox: width, height, flex, gap, padding.*, mainAlign, crossAlign, overflow. | Children remain nested node recipes. |
| Label: label | text, width, height, flex. | Style and model/resolver binding. |
| Button/plain button: button, plainButton | text, width, height, flex, chrome. | Click callbacks, models and action captures. |
| CheckBox/ThreeState: checkbox, threeState | text, width, height, flex, state, cycle. | Managed state and changed callback; Legacy retains its existing checked spelling. |
| LineEdit: lineEdit | Shared size/text leaves, editMode, readOnly, programmaticChange, displayMode, placeholder, history.*, limits.*. | Clipboard, validator, history shortcuts, styles, models, resolver and result callback. |
| Password: password | Empty text, public placeholder, size, editMode, readOnly, displayMode (PASSWORD, NO_ECHO), limits.*, securePolicy.*, pastePolicy. | Protected values/providers/models, validation and result callbacks remain C++; no text getter, history or outbound clipboard. |
| Grid: grid, GridSection | Loader-local fallback: shared size leaves, columns, rows, flow, gaps, padding.*, placement budgets and scroll; child row/column/span/alignment and header/body regions. | Track policies, presentation styles, controller and child providers. |
| Overlay layout: overlay | Scoped Overlay fallback: shared size leaves, padding.*, horizontalAlign, verticalAlign and ordinary child recipes in stacking order. | Service and event behavior remain code-owned. |
| ScrollArea/ScrollBar: scrollArea, scrollBar | Scoped fallbacks: shared size leaves, wheel/key/page/thumb/focus/read-only/glyph/work settings; area policies, placement and frame; bar axis. Area requires one content root; bar is a leaf. | ScrollController, model/provider and callbacks remain code-owned. |
| Border/frame: border, frame | Scoped Border fallback: shared size leaves, glyphs, maxPaintCells and exactly one content root. | Manual styles remain code-owned or use PSS. Advanced decoration uses .framed(...) or resource frame properties on sized sources. |
| Gauge: gauge | Scoped Gauge fallback: shared size leaves, finite value, range, preferredWidth, glyphs, maxPaintCells; no children. | Manual styles remain code-owned or use PSS. |
| Dialog/overlay host: dialog, OverlayHost, overlayHost | Scoped CONFIGURATION factories: host maxLayers; Dialog title, dialog.*; one host body followed by Dialog layers; one complete body per Dialog. | Opening, dismissal, anchors and result handlers remain code-owned. Resource dialogs begin closed. |
| MessageBox: messageBox, confirmDialog, unsavedChangesDialog | Explicit semantic registration of a real native factory: title, body, dialog.*, message.*; leaf node with native internal actions. | The real message facade, factory kind, result routing and callbacks remain code-owned. No unbound resource builtin is supplied. |
| Toast/NotificationCenter: toast, notifications | Explicit Notifications semantic registration of the real code-bound center and complete body: shared size/Overlay layout leaves and notification.*; resource node is a leaf. | Posting requests, actions, center identity and runtime resolver remain code-owned. |
| DataStateView: dataStateView | Scoped CONFIGURATION factory: shared size leaves, showStatus, statusRows, contentPolicy, spinnerInterval, labels.* and exactly one complete body recipe. | The fallback uses explicit READY with generation1; models, provider state and retry actions remain code bindings. |
| HelpView/KeyHints | Scoped leaf factories: shared size leaves, format.*, emptyText, unavailableText; HelpView initiallyOpen; KeyHints entrySeparator, overflowMarker, and local help="id" binding. | Key registrations remain code-owned; both controls project the existing canonical registrations. |
| Theme selection/selector | Explicit ThemeSelector semantic registration of an actual view: title, dialog.*, themeSelector.*. ThemeSelectorCatalog additionally exposes themeCatalog.* on the real owning constructor. The resource node is a leaf. | Existing model/catalog factories, layer service and commit callbacks remain code bindings. An external model does not acquire catalog capability. |
| VirtualList/VirtualTable | Exact typed registered factories: shared size leaves, rowHeight, overscanRows; VirtualTable also maxColumns, maxPreparedCells, maxPreparedTextBytes. | The factory supplies the real model, formatter, columns and prepared provider; no unbound built-in data factory is supplied. |
| Chart | Exact typed registered factories: mode, chartGlyphSet, candleGap, yRange.*. | The factory supplies the real model, accessor, origin and prepared provider. Chart is a plain Widget, so this schema does not add SizedWidget's size leaves. |
| Canvas/custom controls | None by default. | Drawing and custom factory captures remain code-owned; resource support depends on a registered factory. |
| Styles/theme layers | No per-control scalar property schema. | PSS and stylesheet/theme configuration use separate APIs and are not loaded as per-control scalar properties. |
For an exact add<VirtualList<T>> or add<VirtualTable<T>> registration, the default schema includes the applicable data-control leaves. The existing wrapper stages these resource values automatically; the factory does not need to forward arguments.settings manually. An explicitly supplied old narrow schema remains narrow and rejects the new leaves. Arbitrary custom subclasses do not inherit this schema. Native methods and pipes, such as .rowHeight(2).overscanRows(0) and ui::rowHeight(2), retain the existing model, formatter, policy and provider.
.nonModal() and | ui::nonModal() select DialogMode::NON_MODAL on a Dialog recipe without changing other options. They are shorthand for .mode(DialogMode::NON_MODAL); the last mode setting wins in declaration order.
Dialog/OverlayHost settings apply during construction. Methods and pipes such as .maximumPanelSize({42, 9}) and ui::maxLayers(2) retain unspecified actual factory options. .frame(BorderOptions{...}) changes the Dialog panel's own frame; its grouped pipe is ui::dialogSettings({.frame={...}}). The existing ui::frame(...) still wraps a recipe in Border.
A resource OverlayHost takes one ordinary body followed by zero or more Dialog layers. Each Dialog takes one complete body; title may come from the instance, defaults or a definition. The host binds its body before registering layers. Open the loaded Dialog with the existing ui::Ref<Dialog>::open(); opened() and dismiss() keep the normal managed lifecycle. A registered layer factory must create a real managed Dialog; bare custom<Dialog> does not register one.
The groups dialog { maximumPanelSize { width=42, height=9 } } and dialog.frame { ... } are distinct from Chart mode and ScrollArea placement. If a registered child owns a group name, use explicit dialog={...} syntax.
An exact add<DataStateView> registration stages settings over the actual configuration, retaining its model, retry and resolver. With showStatus=false, labels are not resolved and no status strip or animation timer is created. With status enabled, labels.retry is used only when a retry action exists. Scalar validation still applies with status disabled. In C++, supply optional captions as expressions: .labels({.loading = text("Fetching...")}).
The scoped DataStateView resource factory takes one complete body, including a nested layout/Grid. For example: DataStateView { showStatus=false Label{"body"} }. The group labels { loading=i18n("loading") } retains an expression until native construction; unused labels do not invoke a resolver. If a registered child type owns the name labels, use labels={...} to select the property group. The resource resolver is scoped to native fallback construction; an explicit factory resolver takes precedence.
An exact add<Chart<T>> likewise stages the six Chart leaves automatically. Its old explicit narrow schema is {text}; the expanded schema adds the six leaves. Text remains metadata for the code factory, rather than a rendered Chart caption. Native .yRange(ChartRange{90, 120}) and ui::yRange(...) set both endpoints; .yRange(std::nullopt) clears the range. The resource spelling is yRange { enabled=true, minimum=90, maximum=120 }. When a registered child owns the name yRange, use yRange={...} to select the property group explicitly.
ControlContext validates every defaults/definition independently. A declaration with reversed bounds and enabled omitted or true is invalid even when a later instance would disable it. Put enabled=false on that declaration to retain inactive finite bounds. Supplied nonfinite endpoints are always invalid. A second explicit preparation may reproject Chart rows, as with the native API; an idle event loop does not request additional preparation or redraw just because these settings are present.
ui::overlay accepts ordinary child recipes, optional OverlayOptions/SizePolicy and a Ref-first form. Its methods and pipes use the same initial layout settings. The existing ui::notifications composition also accepts those local Overlay modifiers; unrelated caller defaults named Overlay do not reinterpret it. Explicit semantic Notifications defaults and .notificationSettings(...) configure the actual center constructor.
Resource #id identifies one node. It is not a type default and is not inherited. The instance-only visible and enabled booleans are also outside the scalar ControlSettings vocabulary: their default is true, and they apply locally after the factory recipe. Hiding removes a subtree from layout, paint and input; disabling keeps layout and paint while changing input/style behavior. Ancestors still dominate child state. Definitions and defaults reject these instance-only keys.
C++ recipes can set the same initial state with .visible(bool) and .enabled(bool), or the ui::visible(...) and ui::enabled(...) pipe stages. Runtime query and mutation use the existing WidgetTree APIs. Text, callback, model, resolver, provider and factory-capture behavior stays in C++; unknown resource properties are rejected before the text resolver or factory is called.
This C++ scene applies sparse defaults to a linear container and editor variant, then gives one button an instance-only disabled state:
The equivalent resource uses the existing CONFIGURATION grammar. The nested scene contains one root node; type settings belong in definitions or defaults, while enabled belongs to the concrete instance:
CONFIGURATION must be selected explicitly; the default LEGACY format remains the historical single-root grammar. The new nested linear padding/alignment fields and LineEdit limits belong to CONFIGURATION; visible and enabled are accepted on node instances by both formats.
The example customizes initial values only. It does not serialize all fields of LinearOptions, LineEditOptions or any other public options struct. Keep application callbacks, models and providers in C++; the loader has no syntax for them. SceneResourceOptions exposes the format, context and explicit resource-factory registry.
Create a model once with scene.model<T>(snapshot) and pass its observing handle to any number of descriptions. The row type is deduced from that handle; arrays and vectors of TableColumn<T> convert to the table's span parameter. Each recipe opens its range only when mounted. There are no application-owned binding tokens, per-view style registrations or prepareViews hooks to retain.
See the guide examples for scene construction and handlers.
virtualTable copies its column descriptions immediately, including headers and formatter objects. The source span may expire before mount. List formatters, chart accessors, chart-origin callbacks and provider callbacks are owned values. As elsewhere in C++, a reference inside a callback is still a borrow. The model handle remains weak and UI-affine: the receiving scene must own that model.
Virtual factories retain their managed parameters. List/table settings and SizePolicy remain available, and chart settings include its optional origin callback. The final optional prepared callback receives the coherent borrowed model frame and an optional owning provider request. It runs in composition registration order, including layout retries. Resident snapshots need no provider callback; pending work without one fails with INVALID_ARGUMENT during preparation. Provider dispatch, request retention and cache policy remain application decisions.
All children share the description transaction. A failed factory or later setup removes the newly mounted subtree, bindings, ranges and captures; no NodeRef is published. The pre-scene model survives rollback. An origin callback may observe published refs when preparation begins. Standard list/table input bindings cannot be replaced with .onEvent; that conflicting setup returns a typed error and rolls back, as for ordinary bound controls. Hidden views cancel their pending range work; disabling affects input, not visibility. Idle frames, theme changes, rejected notifications and removal use the same managed virtual-view lifecycle.
Include <portals/table_column.hpp> to compose a projection and a formatter into the TableColumn<T>. The projection reads const T&; the formatter receives its exact result category and returns owning GraphemeText by value. Data members, const member functions and lambdas work through std::invoke. ColumnProjection and ColumnFormatter constraints reject incompatible calls at the factory, including formatters that return borrowed text or std::string.
For a fixed schema, prefer the identity-free recipes used by the current dashboard source:
This helper returns expected<array<TableColumn<PriceRow>, 1>, TextError>: header validation remains checked, and the caller chooses its error boundary. tableColumns assigns table-local identities once in declaration order; clients do not invent generations for a fixed schema. The formatter owns its format string and converts its result to grapheme text with the same width policy. This is a column-construction fragment, not a complete running application.
For dynamic schemas, use explicit IDs in TableColumnOptions so a column keeps its identity across replacement or reordering. See virtual tables for the column contract.
TableColumnOptions names the stable column ID, owning header and positive width in terminal cells. IDs are not derived from field names or display order. Existing column arrays remain valid, and the returned column can also be used by low-level VirtualTable or setVirtualTableColumns callers. No sorting or model reads happen at column construction. During preparation only visible ready cells are formatted. The adapter adds one projection call per formatted cell, no row copies or scans; callback cost remains application-defined.
Both callables must be copy constructible because TableColumn still uses std::function. Their captures are owned, but captured references and projection references remain borrowed. A temporary result lasts through the formatter call. Do not retain row/result borrows, perform I/O or mutate the model/tree in either callback. Construction can throw on allocation or capture copy/move; preparation uses the typed callback/allocation errors. Direct column.format(row) invocation propagates exceptions to its caller.
Named settings avoid positional placeholders:
| Recipe | Configuration | Fields |
|---|---|---|
| ui::virtualTable | ui::VirtualTableConfig<T> | options, policy, prepared |
| ui::virtualList | ui::VirtualListConfig<T> | options, policy, prepared |
| ui::chart | ui::ChartConfig<T> | options, first, prepared |
All fields default to the corresponding positional factory defaults. For example, ui::chart(model, accessor, ui::ChartConfig<Ohlc>{.prepared = provider}) starts at row zero without an explicit origin callback. Configurations own callbacks, copy from lvalues and consume rvalues; the model handle remains weak and UI-affine. Use the explicit configuration type with designated initializers. This keeps calls such as ui::chart(model, accessor, {}) unambiguous: bare {} still means ChartOptions. Named overloads preserve mount rollback, input, preparation order, pending-work requirements and typed errors.
See the text and column guide for checked column construction.
A widget ui::Ref<T> can be the first factory argument. It shares the same complete-mount publication as .reference(ref). Built-in controls, custom, row/column/grid and virtual view factories support this form, including positional options and named view configurations. References still observe objects owned by the scene; they do not become owning widget pointers.
See the guide examples for scene construction and handlers.
Callbacks can be supplied directly to ui::button(ref, caption, callback) or a consuming recipe's .onClick(callback). They return void by default; existing expected<T, TreeError> and exact EditorCommandResult callbacks are also supported. Successful payloads are ignored, including false; returned errors retain their original TreeError. Returning editor.undo() or editor.redo() directly preserves the command's receipt: a failure already reported to the same live collector is not reported again. Extracting .result() deliberately loses that provenance. Independent typed failures and thrown exceptions retain their own diagnostics.
A click callback optionally takes const ClickEvent&. The value owns its routed activation and includes modifiers and the activated button's observing target. This target names the button handling activation, including a mouse event that bubbled from a descendant; it does not claim to be the router's original hit. Keyboard Enter arrives as the semantic ActionEvent, while Space and mouse press retain their routed event values. Parameterized callbacks admit modified activation. No-argument callbacks and low-level bindButton retain unmodified activation admission. Mouse release/motion and paste do not click. Low-level bindButtonClick exposes the same parameters with a caller-owned token.
Ref<Button>::onClick registers one callback after successful mount, including after prepare and before run. The scene owns its binding and captures; later Ref destruction has no effect on registration. A duplicate binding returns INVALID_ARGUMENT; it is not replaced. Unpublished/destroyed references return CLOSED, retired widgets return STALE_NODE, and foreign-thread calls return WRONG_THREAD before reading mutable target state. A live UI collector records registration failures without stopping the scene. Allocation failure leaves an unbound button available for retry. Captured references remain borrowed; an admitted callback retains its captures through self-removal. A lazy description that has not mounted cannot receive runtime handlers through its Ref.
.id("status") copies a case-sensitive selector identity and applies it in modifier order. Later recipe .style(target) with an empty id preserves the compact identity; a nonempty explicit id replaces it. Type and class metadata retain their meaning. scene.id(node, value) changes only the id; scene.style(node, target) retains its complete replacement semantics. Metadata allocation failure preserves the old target and pending frame request.
scene.onKey(ui::key(...), callback) and ui::character(scalar, modifiers) match raw key identity, scalar and exact modifiers before semantic routing. Press and repeat match; release does not. Callbacks accept no arguments or const KeyEvent& and use the same void/typed/command result forms. Each registration composes an owning closure in the single onInput slot. The newest matching handler wins and consumes input on success; nonmatches delegate to the previous interceptor, then standard routing. Errors use the input failure path. Direct onInput replaces the whole chain. ManagedOptions::maxKeyHandlers (default 64, greater than zero) bounds this composition; limit or allocation failure preserves the previous chain. There is no separate hotkey registry or event loop.
A recipe assembles the tree once. Reconciliation and dynamic replacement of the tree description are not provided by this API.