Portals0.7.0 · dev (544a5c68c72e · 2026-11-28 UTC)
Loading...
Searching...
No Matches
widget.hpp
1// Copyright (c) 2026 ttldtor.
2// SPDX-License-Identifier: BSL-1.0
3#pragma once
4
5#include <portals/scheduler.hpp>
6#include <portals/style_types.hpp>
7#include <portals/widget_types.hpp>
8
9#include <concepts>
10#include <functional>
11#include <memory>
12#include <type_traits>
13#include <utility>
14#include <vector>
15
16namespace portals {
17namespace ui::detail {
18struct NamedAccess;
19}
20
21namespace detail {
23struct RowTreeAccess;
24} // namespace detail
25class WidgetTree;
26class StyleEngine;
27
32class Widget {
33public:
35 virtual ~Widget() = default;
37 virtual void mount();
39 virtual void unmount();
44 virtual std::expected<CellSize, TreeError> measure(CellSize available);
49 virtual std::expected<void, TreeError> arrange(CellRect local);
54 virtual std::expected<void, TreeError> paint(PaintContext &context);
64
70 virtual bool styleReadOnly() const noexcept;
71
78 const std::shared_ptr<const StyleSnapshot> &computedStyle() const noexcept;
79
81 std::uint64_t styleRevision() const noexcept;
82
83private:
84 friend class StyleEngine;
85 std::shared_ptr<const StyleSnapshot> computedStyle_;
86 std::uint64_t styleRevision_{};
87};
88
92template <class T = Widget> class Node {
93public:
95 Node() = default;
96
101 template <class U>
102 requires std::derived_from<U, T>
103 Node(Node<U> other) : id_(other.id()) {
104 }
105
109 NodeId id() const noexcept {
110 return id_;
111 }
112
117 bool operator==(const Node &other) const noexcept = default;
118
119private:
120 friend class WidgetTree;
121 friend struct ui::detail::NamedAccess;
122
123 explicit Node(NodeId id) : id_(id) {
124 }
125
126 NodeId id_{};
127};
128
134
141
148
158
163 std::vector<Node<Widget>> children = std::vector<Node<Widget>>(0);
165 bool visible{true};
166 bool enabled{true};
167 std::optional<ParentLayoutEdge> parentLayoutEdge;
168 std::optional<std::uint64_t> geometryEpoch;
169 bool regionalInputOpen{true};
170};
171
179class WidgetTree {
180public:
182 using ErrorSink = void (*)(void *, NodeId, TreeError) noexcept;
191 static std::expected<std::unique_ptr<WidgetTree>, TreeError>
192 create(Scheduler &scheduler, WidgetTreeOptions options = {}, ErrorSink sink = nullptr, void *context = nullptr);
195 WidgetTree(const WidgetTree &) = delete;
196 WidgetTree &operator=(const WidgetTree &) = delete;
200 std::expected<Node<Widget>, TreeError> root() const;
205 std::expected<NodeSnapshot, TreeError> inspect(Node<Widget> node) const;
212 std::expected<bool, TreeError> contains(Node<Widget> ancestor, Node<Widget> node) const;
218 std::expected<void, TreeError> remove(Node<Widget> node);
222 std::expected<void, TreeError> close();
223
234 template <class T, class Callback> std::expected<void, TreeError> read(Node<T> node, Callback &&callback) {
235 static_assert(std::is_void_v<std::invoke_result_t<Callback, const T &>>);
236
237 auto value = access(node.id(), false);
238
239 if (!value) {
240 return std::unexpected(value.error());
241 }
242
243 Borrow guard(*this);
244
245 try {
246 std::invoke(std::forward<Callback>(callback), static_cast<const T &>(**value));
247
248 return {};
249 } catch (...) {
250 report(node.id(), TreeError::CALLBACK_FAILED);
251
252 return std::unexpected(TreeError::CALLBACK_FAILED);
253 }
254 }
255
267 template <class T, class... Args>
268 requires std::derived_from<T, Widget>
269 std::expected<Node<T>, TreeError> emplace(Node<Widget> parent, Args &&...args) {
270 return emplaceImpl<T>(parent, false, std::forward<Args>(args)...);
271 }
272
283 template <class T, class... Args>
284 requires std::derived_from<T, Widget>
285 std::expected<Node<T>, TreeError> emplaceChecked(Node<Widget> parent, Args &&...args) {
286 auto node = emplaceImpl<T>(parent, true, std::forward<Args>(args)...);
287
288 if (!node) {
289 return node;
290 }
291
292 // Reclamation after mount may run another widget's unmount and retire this child.
293 auto live = access(node->id(), false);
294
295 if (!live) {
296 return std::unexpected(live.error());
297 }
298
299 return node;
300 }
301
310 template <class T, class Callback> std::expected<void, TreeError> edit(Node<T> node, Callback &&callback) {
311 static_assert(std::is_void_v<std::invoke_result_t<Callback, T &>>);
312
313 auto value = access(node.id(), true);
314
315 if (!value) {
316 return std::unexpected(value.error());
317 }
318
319 Borrow guard(*this);
320
321 try {
322 std::invoke(std::forward<Callback>(callback), static_cast<T &>(**value));
323
324 return {};
325 } catch (...) {
326 report(node.id(), TreeError::CALLBACK_FAILED);
327
328 return std::unexpected(TreeError::CALLBACK_FAILED);
329 }
330 }
331
340 template <class Callback> std::expected<void, TreeError> withScope(Node<Widget> node, Callback &&callback) {
341 auto value = access(node.id(), true);
342
343 if (!value) {
344 return std::unexpected(value.error());
345 }
346
347 Borrow guard(*this);
348
349 try {
350 std::invoke(std::forward<Callback>(callback), scope(node.id()));
351
352 return {};
353 } catch (...) {
354 report(node.id(), TreeError::CALLBACK_FAILED);
355
356 return std::unexpected(TreeError::CALLBACK_FAILED);
357 }
358 }
359
375 template <class Value, class T, class Callback>
376 std::expected<SchedulerConnection<Value>, TreeError> connect(Node<T> node, Callback &&callback,
379 auto value = access(node.id(), true);
380
381 if (!value) {
382 return std::unexpected(value.error());
383 }
384
385 Borrow guard(*this);
386
387 try {
388 auto result = scheduler().connect<Value>(
389 scope(node.id()),
390 [this, node, function = std::forward<Callback>(callback)](std::shared_ptr<const Value> item) mutable {
391 auto status = edit(node, [&](T &widget) {
392 std::invoke(function, widget, std::move(item));
393 });
394
395 if (!status && status.error() == TreeError::CALLBACK_FAILED) {
397 }
398 },
399 lane, overflow);
400
401 if (!result) {
402 return std::unexpected(fromScheduler(result.error()));
403 }
404
405 return std::move(*result);
406 } catch (const std::bad_alloc &) {
407 return std::unexpected(TreeError::NO_MEMORY);
408 }
409 }
410
421 template <class T, class Callback>
422 std::expected<Subscription, TreeError> at(Node<T> node, SchedulerTime deadline, Callback &&callback) {
423 auto value = access(node.id(), true);
424
425 if (!value) {
426 return std::unexpected(value.error());
427 }
428
429 Borrow guard(*this);
430
431 try {
432 auto result =
433 scheduler().at(scope(node.id()), deadline, [this, node, function = std::forward<Callback>(callback)]() mutable {
434 auto status = edit(node, [&](T &widget) {
435 std::invoke(function, widget);
436 });
437
438 if (!status && status.error() == TreeError::CALLBACK_FAILED) {
440 }
441 });
442
443 if (!result) {
444 return std::unexpected(fromScheduler(result.error()));
445 }
446
447 return std::move(*result);
448 } catch (const std::bad_alloc &) {
449 return std::unexpected(TreeError::NO_MEMORY);
450 }
451 }
452
460 std::expected<void, TreeError> setVisible(Node<Widget> node, bool visible);
468 std::expected<void, TreeError> setEnabled(Node<Widget> node, bool enabled);
474 std::expected<bool, TreeError> inputEligible(Node<Widget> node) const;
480 std::expected<void, TreeError> invalidate(Node<Widget> node, Invalidation kind);
484 std::expected<Invalidation, TreeError> consumeFrameRequest();
488 Diagnostics *diagnostics() const noexcept;
501 std::expected<CellSize, TreeError> measure(Node<Widget> node, CellSize available);
510 std::expected<void, TreeError> arrange(Node<Widget> node, CellRect local, CellRect viewport);
520 std::expected<void, TreeError> arrange(Node<Widget> node, CellRect local, CellRect viewport, CellRect contentClip);
521
528 std::expected<void, TreeError> paint(Node<Widget> node, PaintContext &context);
529
538 template <class Callback> std::expected<void, TreeError> frame(Callback &&callback) {
539 static_assert(std::is_void_v<std::invoke_result_t<Callback>>);
540
541 auto allowed = beginFrame();
542
543 if (!allowed) {
544 return allowed;
545 }
546
547 Borrow guard(*this, true);
549
550 try {
551 std::invoke(std::forward<Callback>(callback));
552
553 return {};
554 } catch (...) {
555 report({}, TreeError::CALLBACK_FAILED);
556
557 return std::unexpected(TreeError::CALLBACK_FAILED);
558 }
559 }
560
561private:
562 friend struct detail::LayoutTraversalAccess;
563 friend struct detail::RowTreeAccess;
564 friend class EventRouter;
565 friend class RadioGroup;
566 friend class LayoutSnapshot;
567 // Allocation-free ancestry for the existing router; no record pointer escapes.
568 std::expected<Node<Widget>, TreeError> inputParent(Node<Widget> node) const;
569 // Allocation-free full identity/visible ancestry admission; disabled nodes remain revealable.
570 std::expected<bool, TreeError> revealVisible(Node<Widget> node) const;
571 std::expected<std::uint64_t, TreeError> inputRevision(Node<Widget> node) const;
572 std::expected<bool, TreeError> inputEligible(Node<Widget> node, Node<Widget> reveal) const;
573 friend class ManagedScene;
574 // Managed overlay publication only: exact same-parent permutation and one visibility bit.
575 std::expected<void, TreeError> commitOverlay(Node<Widget> host, Node<Widget> body, Node<Widget> layer,
576 std::span<const Node<Widget>> order, bool visible);
577
578 // Allocation-free owning observation for the managed final-layout bridge; no children or record pointers escape.
579 struct GeometryObservation {
580 NodeGeometry geometry;
581 std::uint64_t visibilityRevision{};
582 bool visible{};
583 };
584
585 std::expected<GeometryObservation, TreeError> observeGeometry(Node<Widget> node) const;
586 // Paint consumes already-arranged geometry inside its existing frame/hook. Final-layout
587 // observers use observeGeometry outside frames; neither path performs layout or allocates.
588 std::expected<NodeGeometry, TreeError> paintGeometry(Node<Widget> node) const;
589 std::expected<std::uint64_t, TreeError> geometryRevision() const;
590 std::uint64_t inputGeneration() const noexcept;
591 struct State;
592
593 friend class StyleEngine;
594
595 struct Borrow {
596 explicit Borrow(WidgetTree &tree, bool frame = false);
597 ~Borrow();
598 WidgetTree &tree;
599 bool frame;
600 };
601
602 explicit WidgetTree(std::unique_ptr<State> state);
603 std::expected<Widget *, TreeError> access(NodeId id, bool mutation) const;
604 std::expected<void, TreeError> canInsert(NodeId parent) const;
605 std::expected<NodeId, TreeError> attach(NodeId parent, std::unique_ptr<Widget> widget, bool checked);
606
607 template <class T, class... Args>
608 std::expected<Node<T>, TreeError> emplaceImpl(Node<Widget> parent, bool checked, Args &&...args) {
609 auto allowed = canInsert(parent.id());
610
611 if (!allowed) {
612 return std::unexpected(allowed.error());
613 }
614
615 Borrow guard(*this);
616
617 try {
618 auto value = std::make_unique<T>(std::forward<Args>(args)...);
619 auto id = attach(parent.id(), std::move(value), checked);
620
621 if (!id) {
622 return std::unexpected(id.error());
623 }
624
625 return Node<T>(*id);
626 } catch (const std::bad_alloc &) {
627 return std::unexpected(TreeError::NO_MEMORY);
628 } catch (...) {
629 report(parent.id(), TreeError::CALLBACK_FAILED);
630
631 return std::unexpected(TreeError::CALLBACK_FAILED);
632 }
633 }
634
635 std::expected<CellSize, TreeError> measureImpl(Node<Widget> node, CellSize available,
636 Node<Widget> measurementRoot = {});
637 std::expected<void, TreeError> arrangeImpl(Node<Widget> node, CellRect local, CellRect viewport,
638 std::optional<CellRect> contentClip,
639 const ParentLayoutEdge *parentEdge = nullptr);
640 std::expected<void, TreeError> beginFrame() const;
641 const UiScope &scope(NodeId id) const;
642 Scheduler &scheduler() const;
643 static TreeError fromScheduler(SchedulerError error);
644 void report(NodeId id, TreeError error) noexcept;
645 void reclaim() noexcept;
646 std::unique_ptr<State> state_;
647};
648} // namespace portals
An owning, invariant-preserving half-open cell rectangle.
Definition geometry.hpp:81
Stack-only causal context on one thread; restores the previous scope on every exit....
Definition diagnostics.hpp:210
Explicit, thread-safe metadata recorder. Disabled by default; no clocks or I/O. enable/disable/snapsh...
Definition diagnostics.hpp:141
UI-owned focus and synchronous bubbling over an existing WidgetTree. Tree and Scheduler must outlive ...
Definition action.hpp:169
Owning immutable identities and local sizes from one completed layout pass. Copies share immutable va...
Definition layout_snapshot.hpp:43
Additive lifecycle owner over one existing Application subtree. UI affine and nonmovable....
Definition managed.hpp:530
Copyable typed observer; never owns or exposes an unchecked widget pointer.
Definition widget.hpp:92
Node(Node< U > other)
Safe observing upcast; downcasts are unavailable.
Definition widget.hpp:103
Node()=default
Empty observer; checked access fails.
bool operator==(const Node &other) const noexcept=default
Compare identity.
NodeId id() const noexcept
Copy the stable diagnostic identity.
Definition widget.hpp:109
Borrowed synchronous command sink supplied by the frame owner. submit must consume commands immediate...
Definition widget_types.hpp:66
Ordinary one-focus-stop, model-owned resident radio group with clipped row painting.
Definition radio_group.hpp:86
One UI executor; call dispatch only between frames, never during layout/paint. create captures its ca...
Definition scheduler.hpp:238
UI-owned style transaction coordinator; tree must outlive this nonmovable object. Bindings own metada...
Definition style.hpp:383
Immutable resident presentation with independently sparse extension blocks. Widget bindings share equ...
Definition style_types.hpp:231
UI-owned scope disconnecting all its subscriptions and timers, in any token order....
Definition scheduler.hpp:154
Exclusive parent/child ownership on Scheduler's UI thread. Scheduler must outlive this object....
Definition widget.hpp:179
std::expected< Node< T >, TreeError > emplace(Node< Widget > parent, Args &&...args)
Construct and exclusively attach a new child; constructors run only after validation....
Definition widget.hpp:269
std::expected< bool, TreeError > contains(Node< Widget > ancestor, Node< Widget > node) const
Test inclusive ancestry without allocating or invoking callbacks.
std::expected< Subscription, TreeError > at(Node< T > node, SchedulerTime deadline, Callback &&callback)
Node-scoped one-shot timer, with the same checked borrow as connect.
Definition widget.hpp:422
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/arra...
Definition widget.hpp:310
std::expected< NodeSnapshot, TreeError > inspect(Node< Widget > node) const
Copy live structure; may allocate.
std::expected< Node< Widget >, TreeError > root() const
Checked observing root; stale after root removal.
std::expected< void, TreeError > paint(Node< Widget > node, PaintContext &context)
Requires an active frame borrow.
std::expected< void, TreeError > invalidate(Node< Widget > node, Invalidation kind)
Coalesce one frame request.
std::expected< void, TreeError > withScope(Node< Widget > node, Callback &&callback)
Borrow the node-owned scope for registration with the existing Scheduler. Registrations borrowing wid...
Definition widget.hpp:340
std::expected< CellSize, TreeError > measure(Node< Widget > node, CellSize available)
Guarded extension call.
std::expected< Invalidation, TreeError > consumeFrameRequest()
Clear pending flags before processing the frame.
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....
std::expected< Node< T >, TreeError > emplaceChecked(Node< Widget > parent, Args &&...args)
Checked construction, including mount and deferred reclamation. Uses the validation and construction ...
Definition widget.hpp:285
std::expected< void, TreeError > remove(Node< Widget > node)
Invalidate subtree/scopes now, reclaim at safe point.
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,...
Definition widget.hpp:376
DiagnosticContext diagnosticFrame() const noexcept
Get the most recently consumed frame's causal token on the UI thread. Pass this token to FrameWriter:...
std::expected< void, TreeError > close()
Idempotent coordinated shutdown, including during edit.
std::expected< bool, TreeError > inputEligible(Node< Widget > node) const
Live/visible/enabled ancestors; hit-test also needs valid geometry.
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...
Definition widget.hpp:234
Diagnostics * diagnostics() const noexcept
Borrow the scheduler recorder without changing ownership.
~WidgetTree()
Close and reclaim on UI, outside all callbacks.
void(*)(void *, NodeId, TreeError) noexcept ErrorSink
Nonthrowing UI error sink; context is borrowed until tree destruction.
Definition widget.hpp:182
std::expected< void, TreeError > frame(Callback &&callback)
Keep widget/text storage alive through traversal AND rendering of borrowed commands....
Definition widget.hpp:538
std::expected< void, TreeError > setEnabled(Node< Widget > node, bool enabled)
No-op if equal; otherwise paint.
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.
std::expected< void, TreeError > setVisible(Node< Widget > node, bool visible)
No-op if equal; otherwise layout.
UI-owned extension object. Hooks borrow their arguments for one call. Models are separate explicit ow...
Definition widget.hpp:32
virtual std::expected< void, TreeError > arrange(CellRect local)
Default accepts the owning rectangle.
virtual ComputedStyle styleDefaults() const
Read manual presentation defaults during style staging on UI.
virtual std::expected< void, TreeError > paint(PaintContext &context)
Default emits no commands.
virtual void unmount()
Called once before destruction, children first; cleanup continues on exceptions.
const std::shared_ptr< const StyleSnapshot > & computedStyle() const noexcept
Inspect the last atomically installed theme inside tree.read/frame.
virtual void mount()
Called exactly once after attachment; exceptions are reported.
virtual bool styleReadOnly() const noexcept
Read actual view-only state during style staging; false by default.
virtual ~Widget()=default
Destroy on UI after the last active tree borrow.
std::uint64_t styleRevision() const noexcept
virtual std::expected< CellSize, TreeError > measure(CellSize available)
Default desired size is empty.
Public Portals API.
Definition action.hpp:8
SchedulerError
Observable operation failures; no callback is started on rejection.
Definition scheduler.hpp:20
SchedulerOverflow
Replace only this sender's pending display snapshot; never raw domain events.
Definition scheduler.hpp:37
@ REJECT
Reject publication when the lane has no free queue slot.
Definition scheduler.hpp:38
SchedulerLane
Independent finite queues; control is serviced before data each cycle.
Definition scheduler.hpp:32
@ DATA
Ordinary immutable data publications.
Definition scheduler.hpp:33
RevealAxes
Axes an ancestor layout may move when revealing this child.
Definition widget.hpp:130
@ HORIZONTAL_ONLY
Keep a sticky region's vertical position.
Definition widget.hpp:132
@ BOTH
Reveal horizontally and vertically.
Definition widget.hpp:131
@ CLOSED
Owner, node scope, scheduler or completion endpoint is closed.
Definition async.hpp:28
RegionalInput
Proposed input admission for a layout region, independent of visibility.
Definition widget.hpp:136
@ UNCHANGED
Use ordinary visible/enabled ancestry.
Definition widget.hpp:137
std::uint64_t SchedulerTime
Monotonic milliseconds; the clock must not move backwards.
Definition scheduler.hpp:18
@ UNCHANGED
An equal set succeeded, or a clean editor lost focus without attempting publication.
Definition line_edit.hpp:130
Invalidation
Accumulated work; layout always includes painting.
Definition widget_types.hpp:41
@ OPEN
Enter a run and initialize its transport and runner state.
Definition application.hpp:17
TreeError
Checked tree failures; rejected operations never start the requested callback.
Definition widget_types.hpp:26
@ CALLBACK_FAILED
A user extension or callback threw.
Definition widget_types.hpp:37
@ NO_MEMORY
Allocation failed inside the operation boundary.
Definition widget_types.hpp:33
An owning available extent in terminal columns/rows.
Definition geometry.hpp:44
Owning resolved presentation; no actions or model state are encoded.
Definition style_types.hpp:169
Fixed-size causal token; zero fields mean unobserved, never a reused identity.
Definition diagnostics.hpp:92
Owning pure layout result for one direct child.
Definition widget.hpp:143
CellRect localClip
Clip in the parent's local cell coordinates.
Definition widget.hpp:144
RevealAxes revealAxes
Allowed movement of this particular ancestor.
Definition widget.hpp:145
RegionalInput proposedInput
Admission to stage outside the layout frame.
Definition widget.hpp:146
Owning arranged geometry; invalid geometry must never be used for hit-testing.
Definition widget_types.hpp:48
Owning identity, independent of addresses; zero is never a live identity.
Definition widget_types.hpp:15
Owning snapshot of a live node; handles remain checked after subsequent mutations.
Definition widget.hpp:160
bool visible
Hidden subtrees do not participate in layout, paint or input.
Definition widget.hpp:165
NodeGeometry geometry
Owning geometry snapshot.
Definition widget.hpp:164
std::vector< Node< Widget > > children
Live children in insertion order.
Definition widget.hpp:163
bool regionalInputOpen
Committed direct-edge admission, independent of user flags.
Definition widget.hpp:169
std::optional< std::uint64_t > geometryEpoch
Successful arrangement stamp, absent after invalidation.
Definition widget.hpp:168
Node< Widget > parent
Empty only for the root.
Definition widget.hpp:161
bool enabled
Disabled subtrees retain layout/paint but do not receive input.
Definition widget.hpp:166
std::optional< ParentLayoutEdge > parentLayoutEdge
Optional specialized parent policy, copied by value.
Definition widget.hpp:167
Owning arranged edge before intersection with any ancestor's clip.
Definition widget.hpp:150
CellRect surfaceClip
Owner clip in surface coordinates, before intersection.
Definition widget.hpp:153
RevealAxes revealAxes
Reveal axes for this edge only.
Definition widget.hpp:154
std::uint64_t geometryEpoch
Child's nonreused successful arrangement stamp.
Definition widget.hpp:156
NodeId parent
Exact owner identity.
Definition widget.hpp:151
NodeId child
Exact direct child identity.
Definition widget.hpp:152
RegionalInput proposedInput
Pure proposal, not a mutation of input state.
Definition widget.hpp:155
Finite storage and recursive traversal limits, including the root node.
Definition widget_types.hpp:56
Internal checked bridge for owning layout edges and regional input. Public arrange retains its ordina...
Definition layout_traversal.hpp:137
Internal checked named publication bridge; no widget or scene ownership escapes.
Definition ui_ref.hpp:2399