Portals0.7.0 · dev (544a5c68c72e · 2026-11-28 UTC)
Loading...
Searching...
No Matches
Row, Column and size policies

Русская версия

All sizes are integer terminal columns/rows. Rectangles are parent-local, half-open values; WidgetTree::arrange translates and intersects clips through the checked geometry API. Row orders visible children left to right; Column orders them top to bottom. Disabled children still occupy space. Hidden children and their descendants are never measured or arranged and contribute no gap.

Each child may implement the const LayoutItem interface. Ordinary widgets use automatic policies and their guarded Widget::measure result. SizedWidget owns a convenient policy pair. Each axis has minimum, preferred, maximum, mode and a positive flex weight. INTRINSIC_EXTENT selects the measured size; other preferred values are nonnegative. Preferred is clamped to minimum/maximum. Invalid bounds, modes, weights and options return TreeError::INVALID_ARGUMENT.

Sizing can also be requested per axis through the C++ UI builders, PSS, and loaded-scene attributes. These inputs choose the allocated outer rectangle; they do not change how a control draws its content inside that rectangle. The table shows the corresponding axis modes and hard bounds:

Meaning C++ UI PSS Scene attribute
Exact extent .width(n) / .height(n) width: n / height: n width / height as a nonnegative integer
Measured content .fitWidth() / .fitHeight() width: fit-content / height: fit-content fitWidth: true / fitHeight: true
Automatic Existing automatic widget policy width: auto / height: auto fitWidth: false / fitHeight: false
Weighted flex .flexX(w) / .flexY(w) width: flex(w) / height: flex(w) flexX / flexY as positive weights
Both axes .flex(w) Set width and height independently flex as a common positive weight
Hard bounds .minWidth(n) / .maxWidth(n) and height equivalents min-width, max-width, min-height, max-height minWidth, maxWidth, minHeight, maxHeight

Here n is a nonnegative integer number of terminal cells; w is a positive 32-bit unsigned integer. PSS sizing declarations require selectors that apply independently of presentation state. A numeric PSS extent is exact: its intersection with style bounds and the widget's existing hard bounds must be nonempty. A mode request never relaxes the widget's own bounds. A contradiction rejects the update and preserves the previously published style and geometry.

Each axis has one mode request. PSS follows its ordinary cascade: a winning width or height declaration replaces that axis's earlier request, while each bound cascades independently. In one scene settings object, competing mode properties are invalid: for example, width together with fitWidth, or flex together with flexX. Their property order does not choose a winner. A higher scene source replaces the lower source's mode request and merges independent bounds. Ordered C++ method chains keep their existing semantics.

The new axis declarations are supported by runtime PSS. The existing compile-time min-width support is unchanged; the compile-time parser rejects the other new sizing declarations instead of expanding its descriptor budget.

The same measured-width intent can be expressed in either input format:

/* PSS */
Button#save { width: fit-content; min-width: 8; }
{
"fitWidth": true,
"minWidth": 8
}

The scene attributes are shown as a fragment of one control's settings. fitWidth: true selects measured content; false selects automatic sizing. Width and height describe the allocated outer rectangle, while the measured content is the control's preferred extent within the layout constraints. For a framed widget, these sizing modifiers constrain the outer frame; inner content bounds are not copied to it.

Control defaults

When a builder omits a SizePolicy, these control families use the defaults below. Each axis is resolved independently; the parent still decides how much space is available. CONTENT uses the measured extent, while FLEX starts at its preferred extent and receives a share of spare space.

Family Controls Width Height
Content-sized Label, Button, CheckBox, ThreeState, Menu, Gauge, Spinner CONTENT CONTENT
Fluid editor LineEdit, Password FLEX, preferred 0, minimum 1 CONTENT
Fluid form control ComboBox, DropDown, FormField, FindBar, KeyHints FLEX, preferred 0 CONTENT
Viewport VirtualList, VirtualTable, Chart, DataStateView, LogView, HelpView FLEX, preferred 0 FLEX, preferred 0
Scroll bar ScrollBar CONTENT when vertical; FLEX when horizontal FLEX when vertical; CONTENT when horizontal

For ScrollBar, breadth and length follow its orientation: a vertical bar has content-sized width and flexible height; a horizontal bar has flexible width and content-sized height. KeyHints uses its offered width to prepare a viewport-informed strip rather than sizing to the full hint text. Virtualized and log views size to their viewport and bounded prepared data; sizing does not scan the complete model or log. A chart measures the offered viewport, not the extent of its data; it accepts an explicit size policy when needed. DataStateView is a viewport wrapper: its default policy fills both axes in DataStateConfig and in the native DataStateView constructor. This lets virtual content receive the allocated viewport instead of inheriting a content-sized height of zero. For a deliberately compact view with a non-virtual, content-sized body, request measured height with .fitHeight(); an explicit SizePolicy{} remains the legacy AUTOMATIC/AUTOMATIC policy.

ComboBox and DropDown create their popups through the shared non-modal Dialog host. The configured popup width and row limits continue to cap the popup panel.

These are defaults for the listed controls. Containers, wrappers, capped families, and host sizing retain their existing behavior. In particular, omitting a policy is distinct from passing SizePolicy{}: the latter keeps the legacy AUTOMATIC/AUTOMATIC policy. No global default changes for layout containers.

To preserve an explicit fill-width request, keep .flexX():

ui::lineEdit(query).flexX(); // Explicit flex width remains supported.

With no explicit policy, LineEdit now uses fluid width by default. .width(n) still requests an exact width; .flexX() does not remove an explicit maximum.

// Copyright (c) 2026 ttldtor.
// SPDX-License-Identifier: BSL-1.0
#include <portals/ui_style.hpp>
int main() {
using namespace portals;
ui::Ref<Button> save, exit;
// clang-format off
auto scene = ui::scene(ui::vbox(
ui::label("Profile"),
ui::spacing(1),
ui::hbox(ui::label("Name").width(8), ui::lineEdit(name, "Ada")),
ui::checkbox("Alerts"),
ui::gauge(0.65),
ui::spacer(),
ui::hbox(ui::button(save, "Save"), ui::spacing(2),
ui::button(exit, "Exit"), ui::spacer()),
ui::label(saved, "Nothing saved")));
return scene
| ui::theme(nordTheme())
| ui::onClick(save, [name, saved] {
saved.text() = name.text();
})
| ui::onClick(exit, ui::quit)
| ui::onKey("F10 | Ctrl+C", ui::quit)
| ui::runApp();
// clang-format on
}
Typed Widget observation; explicit composite specializations reuse their existing weak facades.
Definition ui_ref.hpp:761
TextProperty text(TextResolver resolver={}, std::source_location origin=std::source_location::current()) const
Definition ui_ref.hpp:1968
Public Portals API.
Definition action.hpp:8
StyleSheet nordTheme()
Control defaults: the profile form adapts as the terminal is resized

Still image: control defaults. Source: complete C++ example.

A resizable work queue

This complete program keeps a compact command menu and editor above a virtual table, with actions and status below it. The menu and buttons use their content sizes. The table takes four shares of the flexible vertical space and the spacer takes one. Resizing changes the viewport without rebuilding the scene or replacing the editor value. Save is the same action in the menu, button and Ctrl+S binding.

The table's outer frame has a minimum size of 46 columns by 6 rows. The usable viewport is smaller because the frame occupies cells. The editor accepts 12–40 columns. These are application constraints, expressed with ordinary size modifiers. Table column widths are fixed independently of the viewport; enlarging the window does not automatically widen those columns.

The collection and column schema are checked during scene setup. Their errors propagate through the scene factory to runApp(). The model setup uses the current state/source/model adapters; the program includes that setup rather than relying on an omitted application helper.

// Copyright (c) 2026 ttldtor.
// SPDX-License-Identifier: BSL-1.0
#include <portals/table_column.hpp>
#include <portals/text_format.hpp>
#include <portals/ui_menu.hpp>
#include <portals/ui_style.hpp>
#include <array>
#include <string>
int main() {
using namespace portals;
struct Job {
std::string name, owner, status;
bool operator==(const Job &) const = default;
};
constexpr std::int32_t MIN_TABLE_WIDTH = 46;
constexpr std::int32_t MIN_TABLE_HEIGHT = 6;
constexpr std::int32_t MIN_NAME_WIDTH = 12;
constexpr std::int32_t MAX_NAME_WIDTH = 40;
// clang-format off
return [=] {
ui::ActionSet actions;
auto save = actions.action("save", "Save", [name, status] {
status.text() = name.text() + " saved";
});
auto reset = actions.action("reset", "Reset", [name, status] {
name.text() = "Morning queue";
status.text() = "Ready";
});
auto exit = actions.action("exit", "Quit", ui::quit);
auto scene = ui::scene([=](ManagedScene &owner) {
const std::array<ModelRow<Job>, 12> rows{{
{{1, 1}, {"Build SDK", "Ada", "Ready"}},
{{2, 1}, {"Run unit tests", "Grace", "Running"}},
{{3, 1}, {"Check headers", "Margaret", "Ready"}},
{{4, 1}, {"Render guide", "Ada", "Waiting"}},
{{5, 1}, {"Review examples", "Grace", "Running"}},
{{6, 1}, {"Check packages", "Margaret", "Ready"}},
{{7, 1}, {"Inspect resize", "Ada", "Ready"}},
{{8, 1}, {"Test keyboard", "Grace", "Waiting"}},
{{9, 1}, {"Verify cleanup", "Margaret", "Ready"}},
{{10, 1}, {"Read diagnostics", "Ada", "Waiting"}},
{{11, 1}, {"Prepare archive", "Grace", "Ready"}},
{{12, 1}, {"Publish notes", "Margaret", "Waiting"}}
}};
auto columns = tableColumns(
tableColumn("Job", &Job::name, cellFormat<std::string>("{}"), 20),
tableColumn("Owner", &Job::owner, cellFormat<std::string>("{}"), 10),
tableColumn("Status", &Job::status, cellFormat<std::string>("{}"), 10));
.transform_error([](TreeError error) {
return ManagedError{.phase = ManagedPhase::STATE, .cause = error, .application = {}, .cleanup = {}};
})
.and_then([&](auto collection) { return owner.state(std::move(collection)); })
.and_then([&](auto state) {
return owner.derive(state, [](const RowCollection<Job> &collection) { return collection; });
})
.and_then([&](auto source) { return owner.model(source); })
.and_then([&](auto model) {
return std::move(columns)
.transform_error([](TextError error) {
.application = {}, .cleanup = {}, .text = error};
})
.transform([&](auto schema) {
return ui::vbox(
ui::hbox(ui::menu({save, reset, exit}).framed("rounded", "Queue"),
ui::spacing(2), ui::label("Resize | Ctrl+S: save | F10: quit")).fitHeight(),
ui::hbox(ui::label("Name"), ui::spacing(1),
ui::lineEdit(name, "Morning queue")
.minWidth(MIN_NAME_WIDTH).maxWidth(MAX_NAME_WIDTH)).fitHeight(),
ui::virtualTable(model, schema).framed("rounded", "Work queue")
.minWidth(MIN_TABLE_WIDTH).minHeight(MIN_TABLE_HEIGHT).flexY(4),
ui::spacer(),
ui::hbox(ui::button(save), ui::spacing(1), ui::button(reset), ui::spacing(1),
ui::button(exit), ui::spacer(), ui::label(status, "Ready")).fitHeight());
});
});
});
return std::move(scene)
| ui::theme(nordTheme())
| ui::onKey("Ctrl+S", save)
| ui::onKey("F10 | Ctrl+C", exit);
}
| ui::runApp();
// clang-format on
}
Additive lifecycle owner over one existing Application subtree. UI affine and nonmovable....
Definition managed.hpp:530
std::expected< ManagedSource< detail::DerivedOutput< Transform, In > >, ManagedError > derive(ManagedState< In > input, Transform &&transform, Invalidation kind=Invalidation::PAINT, PropertyOptions options={}, std::source_location origin=std::source_location::current())
Create an owning read-only computation using the existing observer runtime.
Definition managed_derive.hpp:68
std::expected< ManagedModel< T >, ManagedError > model(std::shared_ptr< const ModelSnapshot< T > > initial, ModelOptions options={}, ManagedViewHandler< T > prepared={})
Create a scene-owned model and a weak typed UI handle.
Definition managed_views.hpp:65
std::expected< ManagedState< T >, ManagedError > state(T initial, Invalidation kind=Invalidation::PAINT, PropertyOptions options={})
Create UI-owned state with guaranteed dirty-frame recovery of missed notifications.
Definition managed.hpp:655
Immutable owning rows with explicit provider identity and bounded identity lookup.
Definition collection.hpp:19
static std::expected< RowCollection, TreeError > from(std::span< const ModelRow< T > > rows, CollectionLimits limits={})
Copy a checked whole collection into private immutable storage.
Definition collection.hpp:29
Cold owning declarations, transferred to one managed scene on first button/menu/key binding....
Definition ui_action.hpp:162
ActionRef action(std::string_view key, Action action)
consteval auto minWidth(E expression)
Definition style_static.hpp:954
CellFormat< T > cellFormat(std::format_string< const T & > pattern, WidthPolicy policy={})
Build a reusable column formatter without a formatting lambda.
Definition text_format.hpp:76
std::expected< std::array< TableColumn< T >, 1+sizeof...(Rest)>, TextError > tableColumns(WidthPolicy policy, TableColumnSpec< T > first, Rest &&...rest)
Assemble a fixed schema and allocate deterministic table-local identities.
Definition table_column.hpp:265
TableColumn< T > tableColumn(TableColumnOptions options, Projection projection, Formatter formatter)
Compose an owning typed column from explicit projection and text formatting.
Definition table_column.hpp:84
@ STATE
Create and retain a scene-owned property.
Definition managed_diagnostics.hpp:50
@ MOUNT
Create the scene root or attach and register a managed widget.
Definition managed_diagnostics.hpp:49
TreeError
Checked tree failures; rejected operations never start the requested callback.
Definition widget_types.hpp:26
@ INVALID_ARGUMENT
An option, enum value or operation argument is invalid.
Definition widget_types.hpp:27
Original error plus independent runner/restoration and cleanup failures.
Definition managed_diagnostics.hpp:62
std::optional< ApplicationError > application
Runner error, including terminal restoration.
Definition managed_diagnostics.hpp:67
Owning error value, independent of the failed input's lifetime.
Definition text.hpp:87

Source: complete work queue program.

The work queue preserves its saved name while its table viewport changes

Still image: resizable work queue.

A profile form

The form below keeps the name field between 16 and 40 cells wide. It fills available width up to that maximum. The save button fits its caption: F2 switches the demo captions between English and Russian, so the button changes from 8 to 21 cells in a sufficiently wide terminal. Save copies the current name into the saved-value label.

Terminal resize lays out the same mounted scene again. At viewport widths 80, 32 and 20 the field occupies 40, 32 and 20 cells. Below its hard minimum, the 16-cell allocation is clipped by the viewport. Editing and saved values survive layout changes. The layout does not implicitly change from rows to columns.

The application owns a small English/Russian catalog and supplies a TextResolver for the initial i18n captions. F2 changes the selected language and explicitly refreshes all four captions with text(resolver) = i18n(key). Changing the language or catalog alone does not refresh mounted controls. The catalog, selected language and resolver remain alive until the synchronous runApp call returns.

C++ builders

// Copyright (c) 2026 ttldtor.
// SPDX-License-Identifier: BSL-1.0
#include <portals/ui_style.hpp>
#include <expected>
#include <string>
#include <string_view>
int main() {
using namespace portals;
struct Entry {
std::string_view key, english, russian;
};
constexpr Entry MESSAGES[] = {
{"profile.title", "Profile", "Профиль"},
{"profile.name", "Name", "Имя"},
{"profile.saved", "Saved name", "Сохранённое имя"},
{"profile.save", "Save", "Сохранить профиль"},
};
bool russian = false;
ui::TextResolver resolver = [&](std::string_view key) -> std::expected<std::string, TextResourceError> {
for (const auto &entry : MESSAGES) {
if (entry.key == key) {
return std::string(russian ? entry.russian : entry.english);
}
}
return std::unexpected(TextResourceError::MISSING_RESOURCE);
};
ui::Ref<Label> title, nameLabel, savedLabel, savedValue;
// clang-format off
auto scene = ui::scene(ui::vbox(
ui::label(i18n("profile.title"), {}, {}, resolver).reference(title),
ui::label(i18n("profile.name"), {}, {}, resolver).reference(nameLabel),
ui::lineEdit(name, "Ada").flexX().minWidth(16).maxWidth(40),
ui::button(i18n("profile.save"), {}, {}, resolver).reference(save).fitWidth(),
ui::label(i18n("profile.saved"), {}, {}, resolver).reference(savedLabel),
ui::label(savedValue, ""),
ui::label("F2: EN/RU | F10: quit")));
return scene
| ui::theme(nordTheme())
| ui::style("LineEdit { background: #3b4252; }")
| ui::onClick(save, [name, savedValue] {
savedValue.text() = name.text();
})
| ui::onKey("F2", [title, nameLabel, savedLabel, save, &russian, &resolver] {
russian = !russian;
title.text(resolver) = i18n("profile.title");
nameLabel.text(resolver) = i18n("profile.name");
savedLabel.text(resolver) = i18n("profile.saved");
save.text(resolver) = i18n("profile.save");
})
| ui::onKey("F10 | Ctrl+C", ui::quit)
| ui::runApp();
// clang-format on
}
@ MISSING_RESOURCE
The caller's resolver could not find the requested resource key.
Definition text_resource.hpp:10
constexpr TextValue i18n(std::string_view key)
Copy a resource key for later resolution through an explicit caller.
Definition text_value.hpp:227

Equivalent scene and PSS

// Copyright (c) 2026 ttldtor.
// SPDX-License-Identifier: BSL-1.0
#include <portals/ui_style.hpp>
#include <expected>
#include <string>
#include <string_view>
int main() {
using namespace portals;
struct Entry {
std::string_view key, english, russian;
};
constexpr Entry MESSAGES[] = {
{"profile.title", "Profile", "Профиль"},
{"profile.name", "Name", "Имя"},
{"profile.saved", "Saved name", "Сохранённое имя"},
{"profile.save", "Save", "Сохранить профиль"},
};
bool russian = false;
ui::TextResolver resolver = [&](std::string_view key) -> std::expected<std::string, TextResourceError> {
for (const auto &entry : MESSAGES) {
if (entry.key == key) {
return std::string(russian ? entry.russian : entry.english);
}
}
return std::unexpected(TextResourceError::MISSING_RESOURCE);
};
auto scene = ui::scene(R"scene(
VBox {
Label#title { text = i18n("profile.title") }
Label#nameLabel { text = i18n("profile.name") }
LineEdit#name { text = "Ada", flexX = 1, minWidth = 16, maxWidth = 40 }
Button#save { text = i18n("profile.save") }
Label#savedLabel { text = i18n("profile.saved") }
Label#savedValue { "" }
Label { "F2: EN/RU | F10: quit" }
}
)scene",
{.resolver = resolver});
const auto title = scene.get<Label>("title");
const auto nameLabel = scene.get<Label>("nameLabel");
const auto savedLabel = scene.get<Label>("savedLabel");
const auto savedValue = scene.get<Label>("savedValue");
const auto name = scene.get<LineEdit>("name");
const auto save = scene.get<Button>("save");
// clang-format off
return scene
| ui::theme(nordTheme())
| ui::style(R"pss(
Button { width: fit-content; }
LineEdit { background: #3b4252; }
)pss")
| ui::onClick(save, [name, savedValue] {
savedValue.text() = name.text();
})
| ui::onKey("F2", [title, nameLabel, savedLabel, save, &russian, &resolver] {
russian = !russian;
title.text(resolver) = i18n("profile.title");
nameLabel.text(resolver) = i18n("profile.name");
savedLabel.text(resolver) = i18n("profile.saved");
save.text(resolver) = i18n("profile.save");
})
| ui::onKey("F10 | Ctrl+C", ui::quit)
| ui::runApp();
// clang-format on
}
One-line button; registration is an explicit caller-owned ActionBinding.
Definition controls.hpp:161
const GraphemeText & text() const
Inspect the control's owning Unicode text on UI.
Noninteractive Unicode label; text remains data, including control characters.
Definition controls.hpp:142
UI-owned Unicode draft; mutate only through its scoped binding between frames. Cursor/anchor are UTF-...
Definition line_edit.hpp:205
const GraphemeText & text() const
Borrow validated draft only inside tree.read.
DynamicRef get(std::string_view name, std::source_location origin=std::source_location::current())

Bracketed buttons draw their contour at the allocated left and right edges and center the caption inside it. Width includes the contour and its inner padding; in a narrow allocation the caption clips inside the contour.

Profile form: changing captions and saving a name

Complete sources: C++ form and scene/PSS form. Both link portals::core.

Fixed children preserve their clamped preferred extent. Automatic children use their preferred extent. Flex children also start at their clamped preferred extent, then share spare space in proportion to weights. Each round assigns integer quotients and gives remaining cells in stable child order, skipping children whose maximum has been reached. Capped shares are redistributed; when all flex maxima are reached, unused space remains. Equal weights in 11 cells therefore produce widths 6 and 5, in insertion order.

When space is short, later automatic/flex children yield preferred cells first, down to their minima. Fixed extents and all minima survive. LayoutOverflow::CLIP preserves these extents even when children/gaps/padding exceed the available space; ancestor clips remove the overflow from painting and hit testing. There is no negative size or implicit compression below minimum. Representational overflow is an explicit INVALID_GEOMETRY, rather than wrapping coordinates.

Padding is applied on each side; gaps occur only between participating children. Main alignment applies to the remaining group space after allocation. Start and stretch start at the leading inset, center gives floor(free/2) before the group, and end consumes all spare space before it. Cross stretch (or cross flex) fills the available extent subject to bounds; fixed remains fixed. Cross start/center/end aligns the resulting child extent using the same floor rule. Underflow aligns at the leading inset because there is no spare space.

Flexible spacers and fixed spacing

Use ui::spacer(weight) to share unused space in a direct HBox or VBox, and ui::spacing(cells) for a fixed gap. The parent selects the main axis; the cross-axis extent is zero. Spacers and spacing are invisible and do not paint, accept input, receive focus, or schedule timers. They reuse the existing weighted FLEX and FIXED layout solver. If fixed content and gaps exceed the available extent, fixed spacing remains fixed and is clipped; flexible space shrinks to zero. A spacer cannot be the scene root or a direct child of Grid, Overlay, or a plain widget. The parent's configured gap still applies between children, including either side of a spacer or spacing node.

The C++ factory accepts a positive signed 32-bit weight (default 1) or a nonnegative signed 32-bit cell count. Invalid values and parents produce a typed error through runApp. Runtime scene descriptions use Spacer{weight=2} and Spacing{cells=1}. These weight and cells fields belong to the spacer syntax; omitted runtime values default to weight 1 and cells 0. They are not Widget or ControlSettings defaults.

Their extent is selected by the factory arguments. The usual .width(), .minWidth(), and axis-flex modifiers are not available on these recipes. Non-default sizing policies applied through low-level styles are rejected instead of silently overriding the spacer contract.

The complete example keeps a profile form near the top, its actions at the bottom as the terminal resizes, and allocates the footer's flexible area at a 2:1 ratio. It also shows fixed one- and two-cell gaps, plus Save, Exit, and F10.

The animation shows layout changes in a Linux PTY: 80×18 → 50×12 → 34×10 → 80×18. The capture canvas stays fixed; this is a resize demonstration. Static frame. Run the full example to interact with Save and Exit.

Flexible spacers and fixed gaps while resizing
\include guide_spacers.cpp

Frame ownership and errors

layoutTree is an external two-phase owner-thread traversal. It obtains owning structure/policy/measurement snapshots through inspect and read, measures children before parents, then calls guarded arrange on parents before children. Its temporary traversal table dies when the pass returns; it is not another retained tree. A plain parent supports a single-child viewport passthrough; multiple children require a Layout container.

The caller must invoke layoutTree inside an already active tree.frame. The pass does not create a frame. This precondition is contractual: the current tree API has no active-frame query. One frame can encompass layout, paint and rendering of borrowed commands:

A preliminary pass may instead capture an owning LayoutSnapshot, as the layout-driven view preparation runner does. It does not retain widget borrows or render commands; final layout, paint and rendering still share one frame.

// Between frames, after a viewport change:
auto invalidation =
tree.invalidate(root, portals::Invalidation::LAYOUT);
if (!invalidation) {
return invalidation;
}
std::expected<void, portals::TreeError> layout;
auto frame = tree.frame([&] {
layout = portals::layoutTree(tree, root, viewport, viewport);
if (!layout) {
return;
}
// Paint the arranged tree and render borrowed commands
// before returning.
});
std::expected< void, TreeError > layoutTree(WidgetTree &tree, Node< Widget > node, CellRect local, CellRect viewport)
Measure and arrange a subtree inside an active tree frame.
@ LAYOUT
Layout and painting are required; old arranged geometry becomes invalid.
Definition widget_types.hpp:44

setSizePolicy and setLinearOptions validate owning values, edit on the UI owner between frames, and request layout invalidation. Construction and other custom policy sources must follow the same invalidation discipline. Viewport changes likewise require invalidate(layout) before entering the next frame. After a failed pass the coordinator must abort use of that pass, including paint and hit testing; the solver does not promise transactional rollback or automatic invalidation from inside a frame. Invalidated geometry is never a valid old layout.

All tree errors propagate; arithmetic failures return INVALID_GEOMETRY, library allocation failures return NO_MEMORY, and thrown custom callbacks follow tree.read/measure/arrange's CALLBACK_FAILED boundary. No callback or span is retained. Pure Layout and LayoutItem callbacks run inside a checked read borrow in the enclosing frame and must not call tree operations, recursively dispatch layout, mutate models or perform I/O. A scoped thread-local guard technically rejects recursive layoutTree calls with WOULD_BLOCK. The tree technically protects its ordinary Widget hooks and rejects editing inside frames. Arbitrary model mutation/I/O and direct tree calls from a custom pure callback remain contract violations; the library does not claim to sandbox user C++ code.

Observe final arranged bounds

Register ui::onLayout(ref, callback) on a scene to receive the initial valid geometry and subsequent changes to its local, surface or clip bounds. The scene owns the registration and captures. The callback runs on the UI thread during a subsequent scheduler dispatch, after the successful final layout, paint and owning render have left the tree frame. Preliminary view-preparation passes do not notify. This event identifies arranged geometry; terminal output may still be pending.

// Copyright (c) 2026 ttldtor.
// SPDX-License-Identifier: BSL-1.0
#include <portals/ui.hpp>
int main() {
using namespace portals;
// clang-format off
return [] {
ui::Ref<Column> content;
ui::Ref<Label> dimensions;
return ui::scene(ui::vbox(ui::label("Resize the terminal | F10 quit"), ui::label(dimensions, ""))
.reference(content))
| ui::onLayout(content, [dimensions](const NodeGeometry &geometry) {
const auto size = geometry.local.size();
dimensions.text() = text("{} columns, {} rows", size.width, size.height);
})
| ui::onKey("F10 | Ctrl+C", ui::quit);
} | ui::runApp();
// clang-format on
}
ui::ValueText text(std::format_string< const ui::detail::TextArgumentValue< Args > &... > pattern, Args &&...args)
Declare live formatted text over explicit scalar roots, fields or value properties.
Definition ui_value_text.hpp:567
Owning arranged geometry; invalid geometry must never be used for hit-testing.
Definition widget_types.hpp:48

geometry.local is parent-relative; surface includes ancestor translations; clip intersects the viewport and ancestor clips. Each NodeGeometry owns its values: copy the callback argument to retain it. Equal bounds do not notify or request another frame. A callback may change controls or remove/close its scene; its executing capture survives retirement. Changes request later work through the normal runner. At EOF the existing frame cap remains in force: callback mutations may remain dirty without another final frame or notification.

For a checked read, use ref.geometry() or ref.size(), returning std::expected<NodeGeometry, ManagedError> and std::expected<CellSize, ManagedError>. Size is the local arranged extent. Reading never starts layout or reports an error. Before a successful final frame, while hidden, or after layout invalidation or rearrangement, reads return TreeError::INVALID_GEOMETRY until the next final publication. Equal-valued replacement geometry still revokes the old read. Unpublished/destroyed references return CLOSED, removed identities retain their typed stale-node error, and foreign threads return WRONG_THREAD before owner access. Disabled controls keep their geometry.

Hidden ancestors cancel pending observations. Showing a hidden subtree produces a new initial valid observation, including hide/show between final frames. Removal and close cancel queued observations; already running callbacks finish safely. Runtime registration through ref.onLayout(callback) follows the same contract and first queues its current final value after the current dispatch, if one is available.

The existing scheduler DATA capacity, subscription capacity and data budget bound the queue and deliveries. ManagedOptions::maxLayoutHandlers defaults to 256. Newest pending values replace older ones. Queue-full recovery makes at most maxLayoutPublicationRetries attempts (default 3) without requesting redraw. Exhaustion cancels that pending value and reports SchedulerError::WOULD_BLOCK once through the managed error channel; it does not mark it delivered. A later final frame can begin a fresh attempt. Callback failures retain their original typed cause and existing scene-stop policy. Registering against another scene or after retirement fails through the normal checked registration channel.

Extending layouts and controls

Controls can derive from Widget and provide intrinsic measure only, or derive from SizedWidget for configurable policies. Grid/Overlay can implement Layout: childAvailable supplies measurement bounds, measureChildren aggregates owning MeasuredChild values (including stable NodeId for matching placements after hiding siblings), and arrangeChildren returns exactly one owning local rectangle per visible child. The interface pointer remains inside tree.read. A custom solver must follow the frame/purity/error contract above. No Node downcast or core Widget header change is required.

Styling reference

Rows, columns and spacing are layout objects. Their ordinary paint path adds no background or text, so a background declaration on a layout parent is not a way to fill its empty gaps or recolor descendants. Give the layout .id("layout") when targeting its allocation, and target painted children by their own type, class, ID or exact Ref. PSS has no descendant selectors or automatic paint inheritance.

The complete sizing properties are width, height, min-width, max-width, min-height, max-height, with values and hard-bound rules below. Missing settings preserve the recipe/control policy; colors and states do not define spacing. LinearOptions::gap, padding, cross_align configure layout instead of PSS declarations; default gap/padding are zero and cross alignment is stretch. ui::spacing(n) reserves fixed main-axis cells; ui::spacer() distributes remaining space as described below. These objects have no own glyphs or focus states.

#layout { width: fit-content; max-width: 60; }
Label { foreground: #dce1e8; }

Use a painted control or explicit surface for background coverage. An attached frame is styled separately through the frame reference.