Portals0.7.0 · dev (544a5c68c72e · 2026-11-28 UTC)
Loading...
Searching...
No Matches
portals::WidgetTree Class Reference

Exclusive parent/child ownership on Scheduler's UI thread. Scheduler must outlive this object. Destruction on another thread or inside a tree callback terminates; request close instead. All operations check affinity first. Logical removal is immediate and allocation-free, reclamation waits for the outermost borrow. References cannot escape edit/withScope/frame callbacks. Library allocations become NO_MEMORY; callback exceptions become CALLBACK_FAILED without undoing user effects. More...

#include <widget.hpp>

Public Types

using ErrorSink = void (*)(void *, NodeId, TreeError) noexcept
 Nonthrowing UI error sink; context is borrowed until tree destruction.

Public Member Functions

 ~WidgetTree ()
 Close and reclaim on UI, outside all callbacks.
 WidgetTree (const WidgetTree &)=delete
WidgetTree & operator= (const WidgetTree &)=delete
std::expected< Node< Widget >, TreeError > root () const
 Checked observing root; stale after root removal.
std::expected< NodeSnapshot, TreeError > inspect (Node< Widget > node) const
 Copy live structure; may allocate.
std::expected< bool, TreeError > contains (Node< Widget > ancestor, Node< Widget > node) const
 Test inclusive ancestry without allocating or invoking callbacks.
std::expected< void, TreeError > remove (Node< Widget > node)
 Invalidate subtree/scopes now, reclaim at safe point.
std::expected< void, TreeError > close ()
 Idempotent coordinated shutdown, including during edit.
template<class T, class Callback>
std::expected< void, TreeError > read (Node< T > node, Callback &&callback)
 Borrow a const extension object, including inside frame traversal. The external layout owner can read its custom layout interface, then measure/arrange children using inspect snapshots. No reference may escape; callback returns void.
template<class T, class... Args>
requires std::derived_from<T, Widget>
std::expected< Node< T >, TreeError > emplace (Node< Widget > parent, Args &&...args)
 Construct and exclusively attach a new child; constructors run only after validation. No attach/reparent exists, so cycles cannot be formed. Structural insertion during lifecycle or frame callbacks returns WOULD_BLOCK. A committed mount exception is reported to the sink; insertion still succeeds. Mount can remove itself, so a successful handle can already be stale.
template<class T, class... Args>
requires std::derived_from<T, Widget>
std::expected< Node< T >, TreeError > emplaceChecked (Node< Widget > parent, Args &&...args)
 Checked construction, including mount and deferred reclamation. Uses the validation and construction boundary of emplace. Mount exceptions reach the error sink and retire the attempted subtree. External effects of constructors, lifecycle hooks and the sink are not rolled back.
template<class T, class Callback>
std::expected< void, TreeError > edit (Node< T > node, Callback &&callback)
 Borrow T only during a void callback; nested edit/removal is supported. Forbidden during measure/arrange/paint. No automatic invalidation: request it explicitly.
template<class Callback>
std::expected< void, TreeError > withScope (Node< Widget > node, Callback &&callback)
 Borrow the node-owned scope for registration with the existing Scheduler. Registrations borrowing widgets must use edit for their entire external callback, or connect/at below. The const scope must not be retained or moved out of the node.
template<class Value, class T, class Callback>
std::expected< SchedulerConnection< Value >, TreeError > connect (Node< T > node, Callback &&callback, SchedulerLane lane=SchedulerLane::DATA, SchedulerOverflow overflow=SchedulerOverflow::REJECT)
 Node-scoped typed delivery; the whole callback borrows T until return. Owns callback captures, returns the ordinary Scheduler token/publisher; no second bus. Exceptions report to the tree sink and disconnect through Scheduler's error boundary.
template<class T, class Callback>
std::expected< Subscription, TreeError > at (Node< T > node, SchedulerTime deadline, Callback &&callback)
 Node-scoped one-shot timer, with the same checked borrow as connect.
std::expected< void, TreeError > setVisible (Node< Widget > node, bool visible)
 No-op if equal; otherwise layout.
std::expected< void, TreeError > setEnabled (Node< Widget > node, bool enabled)
 No-op if equal; otherwise paint.
std::expected< bool, TreeError > inputEligible (Node< Widget > node) const
 Live/visible/enabled ancestors; hit-test also needs valid geometry.
std::expected< void, TreeError > invalidate (Node< Widget > node, Invalidation kind)
 Coalesce one frame request.
std::expected< Invalidation, TreeError > consumeFrameRequest ()
 Clear pending flags before processing the frame.
Diagnostics * diagnostics () const noexcept
 Borrow the scheduler recorder without changing ownership.
DiagnosticContext diagnosticFrame () const noexcept
 Get the most recently consumed frame's causal token on the UI thread. Pass this token to FrameWriter::submit after rendering. Multiple invalidations share a frameId and each retains its own causal record; the token identifies the first recorded cause.
std::expected< CellSize, TreeError > measure (Node< Widget > node, CellSize available)
 Guarded extension call.
std::expected< void, TreeError > arrange (Node< Widget > node, CellRect local, CellRect viewport)
 Arrange local geometry against the arranged parent and root viewport; invalidate on failure. The layout owner calls parent before children. Root uses viewport; descendants inherit clip.
std::expected< void, TreeError > arrange (Node< Widget > node, CellRect local, CellRect viewport, CellRect contentClip)
 Arrange with an additional surface clip, inherited by this node's descendants.
std::expected< void, TreeError > paint (Node< Widget > node, PaintContext &context)
 Requires an active frame borrow.
template<class Callback>
std::expected< void, TreeError > frame (Callback &&callback)
 Keep widget/text storage alive through traversal AND rendering of borrowed commands. Run layout/paint and renderFullFrame before returning. Tree/domain edit is rejected; inspect, measure, arrange and paint remain available. Callback must return void.

Static Public Member Functions

static std::expected< std::unique_ptr< WidgetTree >, TreeError > create (Scheduler &scheduler, WidgetTreeOptions options={}, ErrorSink sink=nullptr, void *context=nullptr)
 Create a mounted plain root and bounded registry; no partial tree on failure.

Friends

struct detail::LayoutTraversalAccess
struct detail::RowTreeAccess
class EventRouter
class RadioGroup
class LayoutSnapshot
class ManagedScene
class StyleEngine

Detailed Description

Exclusive parent/child ownership on Scheduler's UI thread. Scheduler must outlive this object. Destruction on another thread or inside a tree callback terminates; request close instead. All operations check affinity first. Logical removal is immediate and allocation-free, reclamation waits for the outermost borrow. References cannot escape edit/withScope/frame callbacks. Library allocations become NO_MEMORY; callback exceptions become CALLBACK_FAILED without undoing user effects.

Member Function Documentation

◆ arrange() [1/2]

std::expected< void, TreeError > portals::WidgetTree::arrange ( Node< Widget > node,
CellRect local,
CellRect viewport )

Arrange local geometry against the arranged parent and root viewport; invalidate on failure. The layout owner calls parent before children. Root uses viewport; descendants inherit clip.

Parameters
nodeLive widget whose geometry is replaced.
localParent-relative rectangle; for the root it is already in surface coordinates.
viewportRoot clipping rectangle; descendants inherit their parent's clip instead.
Returns
Success (including hidden nodes), tree validation errors, WOULD_BLOCK for a nested hook, INVALID_GEOMETRY for an unarranged parent/translation overflow, CALLBACK_FAILED, or the hook's error.

◆ arrange() [2/2]

std::expected< void, TreeError > portals::WidgetTree::arrange ( Node< Widget > node,
CellRect local,
CellRect viewport,
CellRect contentClip )

Arrange with an additional surface clip, inherited by this node's descendants.

Parameters
nodeLive widget whose geometry is replaced after its arranged parent.
localParent-relative allocation; root coordinates are already on the surface.
viewportRoot surface clip, with the unchanged three-argument semantics.
contentClipExtra surface-cell clip intersected with the ordinary inherited/root clip.
Returns
The same checked errors as three-argument arrange; clipping never changes allocation. The additional clip narrows this node's geometry.clip and therefore its paint and hit-test footprint and all descendant clips. Transforms remain checked before geometry publication.

◆ at()

template<class T, class Callback>
std::expected< Subscription, TreeError > portals::WidgetTree::at ( Node< T > node,
SchedulerTime deadline,
Callback && callback )
inline

Node-scoped one-shot timer, with the same checked borrow as connect.

Template Parameters
TWidget or a publicly derived extension type represented by node.
CallbackCopy-constructible callable accepting T& as an lvalue; its return value is ignored.
Parameters
nodeLive receiver whose scope cancels the timer on removal.
deadlineAbsolute millisecond deadline in the scheduler clock.
callbackCallable copied/moved into the scheduler; widget references must not escape.
Returns
Scoped timer token; tree validation errors, WOULD_BLOCK during a frame, translated scheduler registration errors, or NO_MEMORY.
Note
Non-allocation exceptions from callback construction/move propagate.

◆ close()

std::expected< void, TreeError > portals::WidgetTree::close ( )

Idempotent coordinated shutdown, including during edit.

Returns
Success once the tree is logically closed; WRONG_THREAD or WOULD_BLOCK during a frame otherwise.

◆ connect()

template<class Value, class T, class Callback>
std::expected< SchedulerConnection< Value >, TreeError > portals::WidgetTree::connect ( Node< T > node,
Callback && callback,
SchedulerLane lane = SchedulerLane::DATA,
SchedulerOverflow overflow = SchedulerOverflow::REJECT )
inline

Node-scoped typed delivery; the whole callback borrows T until return. Owns callback captures, returns the ordinary Scheduler token/publisher; no second bus. Exceptions report to the tree sink and disconnect through Scheduler's error boundary.

Template Parameters
ValueTransitively immutable snapshot type supporting destruction on any releasing thread.
TWidget or a publicly derived extension type represented by node.
CallbackCopy-constructible callable accepting T& and std::shared_ptr<const Value> as an lvalue; its return value is ignored.
Parameters
nodeLive receiver whose scope cancels delivery on removal.
callbackCallable copied/moved into the scheduler; widget references must not escape.
laneScheduler queue whose capacity and budget apply.
overflowQueue rejection or sender-local pending data replacement policy.
Returns
Scoped subscription and worker-safe publisher; tree validation errors, WOULD_BLOCK during a frame, translated scheduler registration errors, or NO_MEMORY.
Note
Non-allocation exceptions from callback construction/move propagate.

◆ consumeFrameRequest()

std::expected< Invalidation, TreeError > portals::WidgetTree::consumeFrameRequest ( )

Clear pending flags before processing the frame.

Returns
Previously pending invalidation, cleared to none; WRONG_THREAD, closed, or WOULD_BLOCK during a frame.

◆ contains()

std::expected< bool, TreeError > portals::WidgetTree::contains ( Node< Widget > ancestor,
Node< Widget > node ) const

Test inclusive ancestry without allocating or invoking callbacks.

Parameters
ancestorLive candidate ancestor in this tree.
nodeLive candidate descendant in this tree.
Returns
True for the same node or a descendant, false otherwise; tree validation errors on invalid handles. UI-affine and permitted during a frame. Work is proportional to the descendant's depth.

◆ create()

std::expected< std::unique_ptr< WidgetTree >, TreeError > portals::WidgetTree::create ( Scheduler & scheduler,
WidgetTreeOptions options = {},
ErrorSink sink = nullptr,
void * context = nullptr )
static

Create a mounted plain root and bounded registry; no partial tree on failure.

Parameters
schedulerBorrowed UI executor that must outlive the tree; call on its owner thread.
optionsPositive registry and depth bounds; max_depth must not exceed 256.
sinkOptional nonthrowing UI failure sink; recursive reports are suppressed.
contextBorrowed sink context that must outlive the tree.
Returns
Tree with a mounted root, or INVALID_ARGUMENT, NO_MEMORY, IDENTITY_EXHAUSTED, or the translated scheduler scope-creation error.

◆ diagnosticFrame()

DiagnosticContext portals::WidgetTree::diagnosticFrame ( ) const
noexcept

Get the most recently consumed frame's causal token on the UI thread. Pass this token to FrameWriter::submit after rendering. Multiple invalidations share a frameId and each retains its own causal record; the token identifies the first recorded cause.

Returns
Last consumed frame metadata, or an empty token while recording is disabled.

◆ diagnostics()

Diagnostics * portals::WidgetTree::diagnostics ( ) const
noexcept

Borrow the scheduler recorder without changing ownership.

Returns
Configured recorder or null. The tree's scheduler retains it.

◆ edit()

template<class T, class Callback>
std::expected< void, TreeError > portals::WidgetTree::edit ( Node< T > node,
Callback && callback )
inline

Borrow T only during a void callback; nested edit/removal is supported. Forbidden during measure/arrange/paint. No automatic invalidation: request it explicitly.

Template Parameters
TWidget or a publicly derived extension type represented by the checked observer.
CallbackCallable accepting T& and returning void.
Parameters
nodeLive widget to borrow for the duration of the callback.
callbackSynchronous editor; must not retain references and must request its own invalidation.
Returns
Success, tree validation errors, WOULD_BLOCK during a frame, or CALLBACK_FAILED on an exception.

◆ emplace()

template<class T, class... Args>
requires std::derived_from<T, Widget>
std::expected< Node< T >, TreeError > portals::WidgetTree::emplace ( Node< Widget > parent,
Args &&... args )
inline

Construct and exclusively attach a new child; constructors run only after validation. No attach/reparent exists, so cycles cannot be formed. Structural insertion during lifecycle or frame callbacks returns WOULD_BLOCK. A committed mount exception is reported to the sink; insertion still succeeds. Mount can remove itself, so a successful handle can already be stale.

Template Parameters
TPublicly derived Widget constructible from the forwarded Args.
ArgsArgument types accepted by T's constructor; perfect-forwarded without library copies.
Parameters
parentLive parent whose ownership will contain the new child.
argsConstructor arguments forwarded only after insertion checks.
Returns
Observing child handle; tree validation/capacity/depth/identity failures, WOULD_BLOCK at forbidden boundaries, NO_MEMORY for allocation, or CALLBACK_FAILED for a constructor exception.

◆ emplaceChecked()

template<class T, class... Args>
requires std::derived_from<T, Widget>
std::expected< Node< T >, TreeError > portals::WidgetTree::emplaceChecked ( Node< Widget > parent,
Args &&... args )
inline

Checked construction, including mount and deferred reclamation. Uses the validation and construction boundary of emplace. Mount exceptions reach the error sink and retire the attempted subtree. External effects of constructors, lifecycle hooks and the sink are not rolled back.

Template Parameters
TPublicly derived Widget constructible from Args.
ArgsConstructor argument types, perfectly forwarded without library copies.
Parameters
parentLive parent that will own the child.
argsConstructor arguments forwarded after insertion checks.
Returns
Live child or an emplace error; mount exceptions return CALLBACK_FAILED. Removal during mount or deferred cleanup returns STALE_NODE; tree closure returns CLOSED.

◆ frame()

template<class Callback>
std::expected< void, TreeError > portals::WidgetTree::frame ( Callback && callback)
inline

Keep widget/text storage alive through traversal AND rendering of borrowed commands. Run layout/paint and renderFullFrame before returning. Tree/domain edit is rejected; inspect, measure, arrange and paint remain available. Callback must return void.

Template Parameters
CallbackCallable without arguments returning void.
Parameters
callbackSynchronous traversal and rendering operation; frame borrows must not escape.
Returns
Success, WRONG_THREAD, closed, WOULD_BLOCK for nesting/active borrows/reclamation, or CALLBACK_FAILED for an exception; previously performed user effects are not rolled back.

◆ inputEligible()

std::expected< bool, TreeError > portals::WidgetTree::inputEligible ( Node< Widget > node) const

Live/visible/enabled ancestors; hit-test also needs valid geometry.

Parameters
nodeLive node whose ancestry is checked.
Returns
True when the node and all ancestors are visible and enabled, false otherwise; tree validation errors for an invalid observer. Geometry is not consulted.

◆ inspect()

std::expected< NodeSnapshot, TreeError > portals::WidgetTree::inspect ( Node< Widget > node) const

Copy live structure; may allocate.

Parameters
nodeChecked identity whose live structure is copied.
Returns
Owning snapshot of children, parent, flags and geometry; tree validation errors or NO_MEMORY on failure.

◆ invalidate()

std::expected< void, TreeError > portals::WidgetTree::invalidate ( Node< Widget > node,
Invalidation kind )

Coalesce one frame request.

Parameters
nodeLive node authorizing invalidation of the tree.
kindWork to coalesce; layout invalidates all arranged geometry and includes paint.
Returns
Success, tree validation errors, WOULD_BLOCK during a frame, or INVALID_ARGUMENT for an unknown kind.

◆ measure()

std::expected< CellSize, TreeError > portals::WidgetTree::measure ( Node< Widget > node,
CellSize available )

Guarded extension call.

Parameters
nodeLive widget to measure; hidden ancestry returns an empty size without invoking its hook.
availableCell constraints normalized before calling the extension.
Returns
Normalized desired size; tree validation errors, WOULD_BLOCK for nested extension calls, CALLBACK_FAILED for thrown exceptions, or the hook's error.

◆ paint()

std::expected< void, TreeError > portals::WidgetTree::paint ( Node< Widget > node,
PaintContext & context )

Requires an active frame borrow.

Parameters
nodeLive, arranged widget to paint; hidden ancestry skips the hook.
contextSink borrowed for this hook and the enclosing frame only.
Returns
Success, tree validation errors, WOULD_BLOCK outside a frame or inside another hook, INVALID_GEOMETRY, CALLBACK_FAILED, or the hook's error.

◆ read()

template<class T, class Callback>
std::expected< void, TreeError > portals::WidgetTree::read ( Node< T > node,
Callback && callback )
inline

Borrow a const extension object, including inside frame traversal. The external layout owner can read its custom layout interface, then measure/arrange children using inspect snapshots. No reference may escape; callback returns void.

Template Parameters
TWidget or a publicly derived extension type represented by the checked observer.
CallbackCallable accepting const T& and returning void.
Parameters
nodeLive widget to borrow without permitting tree mutation through this reference.
callbackSynchronous reader; must not retain the widget reference.
Returns
Success after callback return, tree validation errors before invocation, or CALLBACK_FAILED on an exception.

◆ remove()

std::expected< void, TreeError > portals::WidgetTree::remove ( Node< Widget > node)

Invalidate subtree/scopes now, reclaim at safe point.

Parameters
nodeRoot of the subtree to invalidate and eventually destroy.
Returns
Success after logical removal and layout invalidation; tree validation errors, or WOULD_BLOCK during a frame.

◆ root()

std::expected< Node< Widget >, TreeError > portals::WidgetTree::root ( ) const

Checked observing root; stale after root removal.

Returns
Observing root handle, or WRONG_THREAD, closed, or STALE_NODE if the root was removed.

◆ setEnabled()

std::expected< void, TreeError > portals::WidgetTree::setEnabled ( Node< Widget > node,
bool enabled )

No-op if equal; otherwise paint.

Parameters
nodeLive node whose flag is changed.
enabledWhether this node and its subtree can receive input; layout/paint remain available.
Returns
Success, including equal-value no-op, or tree validation errors including WOULD_BLOCK during a frame.
Note
Affinity, lifetime and frame checks also apply when the requested flag already matches.

◆ setVisible()

std::expected< void, TreeError > portals::WidgetTree::setVisible ( Node< Widget > node,
bool visible )

No-op if equal; otherwise layout.

Parameters
nodeLive node whose flag is changed.
visibleWhether this node and its subtree participate in layout, paint and input.
Returns
Success, including equal-value no-op, or tree validation errors including WOULD_BLOCK during a frame.
Note
Affinity, lifetime and frame checks also apply when the requested flag already matches.

◆ withScope()

template<class Callback>
std::expected< void, TreeError > portals::WidgetTree::withScope ( Node< Widget > node,
Callback && callback )
inline

Borrow the node-owned scope for registration with the existing Scheduler. Registrations borrowing widgets must use edit for their entire external callback, or connect/at below. The const scope must not be retained or moved out of the node.

Template Parameters
CallbackCallable accepting const UiScope&; its return value is ignored.
Parameters
nodeLive node whose scope is borrowed outside a frame.
callbackSynchronous registration code; must not retain the scope reference.
Returns
Success, tree validation errors, WOULD_BLOCK during a frame, or CALLBACK_FAILED on an exception.

The documentation for this class was generated from the following file: