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

UI-owned focus and synchronous bubbling over an existing WidgetTree. Tree and Scheduler must outlive the router. Destroy on its creating UI thread outside a router callback; violation terminates. All operations reject wrong-thread calls before touching user state. Dispatch/invoke/bind reject nested dispatch with WOULD_BLOCK. References borrowed by handlers cannot escape. No terminal bytes or queue are produced. Allocation failures become NO_MEMORY; callback exceptions become CALLBACK_FAILED. Focus changes request paint; geometry invalidation never disables keyboard access. More...

#include <action.hpp>

Public Member Functions

 ~EventRouter ()
 Disconnect and reclaim all captures on UI; tree must still exist.
 EventRouter (const EventRouter &)=delete
EventRouter & operator= (const EventRouter &)=delete
std::expected< void, TreeError > setPointerCaptureCapabilities (PointerCaptureCapabilities capabilities)
 Declare host motion/release guarantees, without terminal I/O.
std::expected< PointerCapture, TreeError > capturePointer (Node< Widget > owner, Node< Widget > focusRoot={})
 Capture LEFT continuation from this owner's currently admitted LEFT PRESS handler.
std::expected< Node< Widget >, TreeError > pointerCapture ()
 Revalidate action identity and visible/enabled ancestry without consulting geometry.
std::expected< void, TreeError > cancelPointerCapture (bool requestPaint=true)
 Explicitly end capture for host resize, stop, capability loss or application policy.
template<class T, class Callback>
std::expected< ActionBinding, TreeError > bind (Node< T > node, Callback &&callback, bool focusable=true)
 Register one typed handler; the scoped token owns disconnect responsibility. Callback must be copy-constructible and return EventReply. Invocation uses tree.edit, retaining the widget and callback captures even if either is removed during the call. Duplicate registration is INVALID_ARGUMENT; full registry is NODE_LIMIT. Removed or disconnected records are reclaimed before accepting a new registration.
template<class T, class Callback, class FocusCallback>
requires std::invocable<FocusCallback &, T &, bool>
std::expected< ActionBinding, TreeError > bind (Node< T > node, Callback &&callback, FocusCallback &&focusCallback, bool focusable=true)
 Register input and optional synchronous focus delivery in one scoped registration. Focus loss precedes gain and the next routed input. Delivery does not bubble; a live hidden or disabled previous target still receives loss. Removed/disconnected targets are skipped. Callbacks may remove nodes; nested focus changes or input delivery return WOULD_BLOCK. A callback error does not undo the published focus or model effects.
std::expected< ActionBinding, TreeError > focusScope (Node< Widget > root, Node< Widget > defaultTarget={})
 Declare a nested focus scope using an existing owning disconnect token. Scope and action records share max_registrations. A scope can share its root with an action.
std::expected< void, TreeError > focusDefault (Node< Widget > node)
 Set the default of the nearest live enclosing scope without changing current focus.
std::expected< Node< Widget >, TreeError > enterScope (Node< Widget > root)
 Enter a declared scope at its eligible last/default/preorder target.
std::expected< Node< Widget >, TreeError > enterFocusScope (Node< Widget > root)
 Enter a scope while saving exact focus and ancestry for a later return. This focus-only stack does not shield input or restrict global Tab traversal.
std::expected< Node< Widget >, TreeError > leaveFocusScope (Node< Widget > root)
 Leave the top scope and restore eligible saved focus, scope fallback or global fallback. Ended outer records unwind together. Hidden/disabled/removed/disconnected scope roots also unwind lazily on the next focus query or input dispatch. Saved identities include generations.
std::expected< Node< Widget >, TreeError > focused ()
 Recover focus if needed; empty Node means no eligible focusable registration. Recovery tries containing scopes, then global history and the first preorder node. If its callbacks retire the selected target, return empty; the next call may recover again.
std::expected< void, TreeError > setFocus (Node< Widget > node)
 Focus a live eligible registered node, or return INVALID_ARGUMENT; requests paint.
std::expected< Node< Widget >, TreeError > traverse (bool reverse=false)
 Traverse eligible registrations in tree preorder with wrap; reverse implements Shift+Tab. Scope boundaries preserve the full global order; remembered/default entry is explicit via enterScope. A managed modal restricts traversal to its active subtree.
std::expected< Node< Widget >, TreeError > hitTest (CellPoint point)
 Hit target in paint order; descendants and later sibling subtrees take precedence. Only fresh, clipped geometry participates. Returns an empty Node for a miss. Nonregistered nodes may be targets and bubble to ancestors.
std::expected< DispatchResult, TreeError > dispatch (const InputEvent &event)
 Deliver decoded input synchronously; replies/issues are ignored. Unmodified Tab/Shift+Tab traverse. Enter/Escape/arrows/Home/End/Backspace/Delete map to actions; release and other keys remain KeyEvent. Text (including space), paste and mouse retain type. Left press focuses the nearest focusable target ancestor before bubbling the mouse event. If focus callbacks retire the original hit, suppress delivery without retargeting it. Managed nonmodal pointer input does not steal focus. A modal consumes outside physical input, and layer bubbling stops at the structural dialog root.
std::expected< DispatchResult, TreeError > invoke (Node< Widget > target, ActionEvent action)
 Invoke the same handler path with a semantic command; target need not be focusable. Foreign/stale targets return their tree error. Ineligible targets return DispatchStatus::NO_TARGET. A managed modal rejects an explicit outside target with INVALID_ARGUMENT.

Static Public Member Functions

static std::expected< std::unique_ptr< EventRouter >, TreeError > create (WidgetTree &tree, EventRouterOptions options={})
 Validate the tree's owner thread and create a bounded router.

Friends

class ManagedScene
struct detail::RowTreeAccess
struct detail::EventRouterAccess

Detailed Description

UI-owned focus and synchronous bubbling over an existing WidgetTree. Tree and Scheduler must outlive the router. Destroy on its creating UI thread outside a router callback; violation terminates. All operations reject wrong-thread calls before touching user state. Dispatch/invoke/bind reject nested dispatch with WOULD_BLOCK. References borrowed by handlers cannot escape. No terminal bytes or queue are produced. Allocation failures become NO_MEMORY; callback exceptions become CALLBACK_FAILED. Focus changes request paint; geometry invalidation never disables keyboard access.

Member Function Documentation

◆ bind() [1/2]

template<class T, class Callback>
std::expected< ActionBinding, TreeError > portals::EventRouter::bind ( Node< T > node,
Callback && callback,
bool focusable = true )
inline

Register one typed handler; the scoped token owns disconnect responsibility. Callback must be copy-constructible and return EventReply. Invocation uses tree.edit, retaining the widget and callback captures even if either is removed during the call. Duplicate registration is INVALID_ARGUMENT; full registry is NODE_LIMIT. Removed or disconnected records are reclaimed before accepting a new registration.

Template Parameters
TWidget or a publicly derived extension type represented by node.
CallbackCopy-constructible callable invocable as an lvalue with T& and const RoutedEvent&, returning exactly EventReply.
Parameters
nodeLive target; hidden or disabled nodes can register but cannot receive input until eligible.
callbackOwned handler; borrowed widget/event references must not escape the invocation.
focusableWhether this registration participates in keyboard focus and traversal.
Returns
Disconnect token; tree validation errors, WOULD_BLOCK during dispatch/frame/collection, INVALID_ARGUMENT for a duplicate, NODE_LIMIT for capacity, NO_MEMORY, or CALLBACK_FAILED.

◆ bind() [2/2]

template<class T, class Callback, class FocusCallback>
requires std::invocable<FocusCallback &, T &, bool>
std::expected< ActionBinding, TreeError > portals::EventRouter::bind ( Node< T > node,
Callback && callback,
FocusCallback && focusCallback,
bool focusable = true )
inline

Register input and optional synchronous focus delivery in one scoped registration. Focus loss precedes gain and the next routed input. Delivery does not bubble; a live hidden or disabled previous target still receives loss. Removed/disconnected targets are skipped. Callbacks may remove nodes; nested focus changes or input delivery return WOULD_BLOCK. A callback error does not undo the published focus or model effects.

Template Parameters
TRegistered widget type.
CallbackOwning copyable input handler returning EventReply.
FocusCallbackOwning copyable callable returning expected<void, TreeError>.
Parameters
nodeLive target of both callbacks.
callbackInput handler; widget/event borrows expire upon return.
focusCallbackOptional handler taking (T&, bool), true for gain and false for loss.
focusableWhether the node participates in focus selection.
Returns
One disconnect token or the same checked registration errors as input-only bind.

◆ cancelPointerCapture()

std::expected< void, TreeError > portals::EventRouter::cancelPointerCapture ( bool requestPaint = true)

Explicitly end capture for host resize, stop, capability loss or application policy.

Parameters
requestPaintWhether a surviving owner needs one PAINT; false is appropriate during stop/cleanup.
Returns
Success or tree/router/invalidation error. Capture is unhooked before a paint error; a CLOSED tree also retires it without paint before returning CLOSED.
Note
UI-only; allowed from the current input handler, without nested dispatch or user callbacks.

◆ capturePointer()

std::expected< PointerCapture, TreeError > portals::EventRouter::capturePointer ( Node< Widget > owner,
Node< Widget > focusRoot = {} )

Capture LEFT continuation from this owner's currently admitted LEFT PRESS handler.

Parameters
ownerLive full identity of the currently executing action registration, inside any active managed modal.
focusRootOptional live ancestor containing owner, defaulting to owner. Only a subsequent focus transition outside this subtree cancels capture; existing external/empty focus is permitted.
Returns
Weak cancellation token; tree/session/thread errors, INVALID_ARGUMENT for absent capabilities/wrong owner/root, WOULD_BLOCK outside that press or while another capture is active, NO_MEMORY, or IDENTITY_EXHAUSTED after the tree's input-generation stamp is exhausted. Failure publishes no new capture. Pure LAYOUT invalidation does not cancel capture. Any visibility/enabled/removal mutation conservatively cancels it, including unrelated nodes; this protects hide/show and disable/enable pairs without a per-ancestor history observer. A newly admitted modal also cancels an outside owner even when focusRoot spans the host.
Note
UI-only; callable and widget borrows never escape their existing admission.

◆ create()

std::expected< std::unique_ptr< EventRouter >, TreeError > portals::EventRouter::create ( WidgetTree & tree,
EventRouterOptions options = {} )
static

Validate the tree's owner thread and create a bounded router.

Parameters
treeBorrowed live tree whose UI thread owns this router; it must outlive the router.
optionsPositive maximum number of live registrations.
Returns
New router, the tree's root-access error, INVALID_ARGUMENT for zero capacity, or NO_MEMORY.

◆ dispatch()

std::expected< DispatchResult, TreeError > portals::EventRouter::dispatch ( const InputEvent & event)

Deliver decoded input synchronously; replies/issues are ignored. Unmodified Tab/Shift+Tab traverse. Enter/Escape/arrows/Home/End/Backspace/Delete map to actions; release and other keys remain KeyEvent. Text (including space), paste and mouse retain type. Left press focuses the nearest focusable target ancestor before bubbling the mouse event. If focus callbacks retire the original hit, suppress delivery without retargeting it. Managed nonmodal pointer input does not steal focus. A modal consumes outside physical input, and layer bubbling stops at the structural dialog root.

Parameters
eventDecoded input borrowed for this call; handlers must not retain references.
Returns
Initial target, consuming handler and delivery status; NO_TARGET for a miss/ignored decoder event, tree/router errors, WOULD_BLOCK for nested delivery, NO_MEMORY, or CALLBACK_FAILED.

◆ enterFocusScope()

std::expected< Node< Widget >, TreeError > portals::EventRouter::enterFocusScope ( Node< Widget > root)

Enter a scope while saving exact focus and ancestry for a later return. This focus-only stack does not shield input or restrict global Tab traversal.

Parameters
rootEligible declared scope, absent from the existing return stack.
Returns
Selected observer (possibly empty), INVALID_ARGUMENT for duplicate/ineligible entry, or typed tree/allocation/callback errors. Before publication failure preserves the stack; after publication callback errors retain both the new focus and its return record.

◆ enterScope()

std::expected< Node< Widget >, TreeError > portals::EventRouter::enterScope ( Node< Widget > root)

Enter a declared scope at its eligible last/default/preorder target.

Parameters
rootLive registered scope root; hidden/disabled subtrees select empty focus.
Returns
Selected observer, empty for no eligible member or callback retirement, or typed error. Callback errors preserve already published focus, exactly like setFocus. A managed modal rejects an outside root with INVALID_ARGUMENT; dialog staging reentry is WOULD_BLOCK.

◆ focusDefault()

std::expected< void, TreeError > portals::EventRouter::focusDefault ( Node< Widget > node)

Set the default of the nearest live enclosing scope without changing current focus.

Parameters
nodeLive descendant to use when its scope has no eligible remembered target.
Returns
Success, INVALID_ARGUMENT without a scope, or tree/router validation errors.

◆ focused()

std::expected< Node< Widget >, TreeError > portals::EventRouter::focused ( )

Recover focus if needed; empty Node means no eligible focusable registration. Recovery tries containing scopes, then global history and the first preorder node. If its callbacks retire the selected target, return empty; the next call may recover again.

Returns
Eligible focused node (possibly recovered), an empty observer if none exists, or tree/router/callback errors or NO_MEMORY. Recovery requests paint when focus changes.

◆ focusScope()

std::expected< ActionBinding, TreeError > portals::EventRouter::focusScope ( Node< Widget > root,
Node< Widget > defaultTarget = {} )

Declare a nested focus scope using an existing owning disconnect token. Scope and action records share max_registrations. A scope can share its root with an action.

Parameters
rootLive subtree root; duplicate scopes return INVALID_ARGUMENT.
defaultTargetOptional live descendant (including root), skipped while ineligible or stale.
Returns
Scoped token, validation error, NODE_LIMIT or NO_MEMORY; failure publishes no scope.

◆ hitTest()

std::expected< Node< Widget >, TreeError > portals::EventRouter::hitTest ( CellPoint point)

Hit target in paint order; descendants and later sibling subtrees take precedence. Only fresh, clipped geometry participates. Returns an empty Node for a miss. Nonregistered nodes may be targets and bubble to ancestors.

Parameters
pointSurface cell coordinate tested against arranged rectangles and ancestor clips.
Returns
Last hit in preorder (later siblings cover earlier ones), empty on a miss, or tree/router validation errors or NO_MEMORY.

◆ invoke()

std::expected< DispatchResult, TreeError > portals::EventRouter::invoke ( Node< Widget > target,
ActionEvent action )

Invoke the same handler path with a semantic command; target need not be focusable. Foreign/stale targets return their tree error. Ineligible targets return DispatchStatus::NO_TARGET. A managed modal rejects an explicit outside target with INVALID_ARGUMENT.

Parameters
targetExplicit live destination; focus is unchanged.
actionOwning semantic command and modifier intent to bubble along the original ancestry.
Returns
Initial target, consuming handler and delivery status; tree/router errors, WOULD_BLOCK for nested delivery, NO_MEMORY, or CALLBACK_FAILED.

◆ leaveFocusScope()

std::expected< Node< Widget >, TreeError > portals::EventRouter::leaveFocusScope ( Node< Widget > root)

Leave the top scope and restore eligible saved focus, scope fallback or global fallback. Ended outer records unwind together. Hidden/disabled/removed/disconnected scope roots also unwind lazily on the next focus query or input dispatch. Saved identities include generations.

Parameters
rootExact top activation root; other roots return INVALID_ARGUMENT.
Returns
Selected observer (possibly empty), validation/allocation/callback errors. A published return consumes its record even when a blur callback fails. Nested focus delivery is WOULD_BLOCK.

◆ pointerCapture()

std::expected< Node< Widget >, TreeError > portals::EventRouter::pointerCapture ( )

Revalidate action identity and visible/enabled ancestry without consulting geometry.

Returns
Effective captured observer, empty when absent/retired, or a tree/router/paint error. Retired records are unhooked before invalidation; no cancellation callback is invoked.
Note
UI-only; no terminal focus-loss detection or polling is implied.

◆ setFocus()

std::expected< void, TreeError > portals::EventRouter::setFocus ( Node< Widget > node)

Focus a live eligible registered node, or return INVALID_ARGUMENT; requests paint.

Parameters
nodeLive, eligible node with a focusable registration.
Returns
Success, INVALID_ARGUMENT for an ineligible/unregistered/nonfocusable node, tree/router validation errors, or the first loss/gain callback error; published focus is not rolled back. Managed modal confinement rejects outside nodes; reentry during dialog staging is WOULD_BLOCK.

◆ setPointerCaptureCapabilities()

std::expected< void, TreeError > portals::EventRouter::setPointerCaptureCapabilities ( PointerCaptureCapabilities capabilities)

Declare host motion/release guarantees, without terminal I/O.

Parameters
capabilitiesOwning capability value; defaults are all false until explicitly declared.
Returns
Success, tree/router validation errors or WOULD_BLOCK during input/focus delivery. A changed capability value cancels an active capture before further delivery. A paint failure preserves the new declaration and retired capture, just like already-published focus effects.
Note
UI-only; no callback, queue, timer or terminal mode is created.

◆ traverse()

std::expected< Node< Widget >, TreeError > portals::EventRouter::traverse ( bool reverse = false)

Traverse eligible registrations in tree preorder with wrap; reverse implements Shift+Tab. Scope boundaries preserve the full global order; remembered/default entry is explicit via enterScope. A managed modal restricts traversal to its active subtree.

Parameters
reverseTraverse backward when true, forward otherwise; wrap at either end.
Returns
Newly focused node, empty if none exists or callbacks retire it, or tree/router/callback errors.

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