Portals0.7.0 · dev (544a5c68c72e · 2026-11-28 UTC)
Loading...
Searching...
No Matches
managed.hpp
1// Copyright (c) 2026 ttldtor.
2// SPDX-License-Identifier: BSL-1.0
3#pragma once
4#include <portals/data_presentation.hpp>
5
6#include <portals/application.hpp>
7#include <portals/collection.hpp>
8#include <portals/detail/managed_origin.hpp>
9#include <portals/detail/setup_failure.hpp>
10#include <portals/dialog.hpp>
11#include <portals/editor_command.hpp>
12#include <portals/key_binding.hpp>
13#include <portals/line_edit.hpp>
14#include <portals/log_navigation.hpp>
15#include <portals/log_view.hpp>
16#include <portals/managed_diagnostics.hpp>
17#include <portals/managed_model.hpp>
18#include <portals/managed_navigation.hpp>
19#include <portals/password.hpp>
20#include <portals/primitives.hpp>
21#include <portals/radio_group.hpp>
22#include <portals/scroll_controls.hpp>
23#include <portals/slider.hpp>
24#include <portals/spin_box.hpp>
25#include <portals/spinner.hpp>
26#include <portals/status_bar.hpp>
27#include <portals/style.hpp>
28#include <portals/style_source.hpp>
29#include <portals/text_transform.hpp>
30#include <portals/toast.hpp>
31#include <portals/virtual_preparation.hpp>
32
33#include <array>
34#include <ranges>
35
36namespace portals {
37
38class ManagedScene;
39class Grid;
40enum class MessageChoice;
41
43using VisibleModelError = std::variant<ManagedError, VisibleModelReadError>;
44
45namespace ui {
46class LogSource;
47}
48
49namespace ui::detail {
50struct Access;
51struct RefAccess;
52struct SceneAccess;
53struct ClickAccess;
54struct EditorEventAccess;
55struct ChangeAccess;
56struct NamedAccess;
57struct LayoutAccess;
58struct MessageAccess;
59struct KeyHelpAccess;
60struct ThemeSelectionAccess;
61struct ThemeSelectorAccess;
62struct ActionAccess;
63struct ActionStore;
64struct ActionRegistry;
65struct AsyncAccess;
66struct MountContext;
67
69inline constexpr char PREPARED_CAPTION_TYPE{};
70
71// A linked construction scope classifies cold declarations by where they are
72// created, rather than by whichever row happens to resolve them first.
73struct RowDeclarationOriginScope {
74 explicit RowDeclarationOriginScope(std::shared_ptr<portals::detail::ManagedOrigin> value = {})
75 : origin(std::move(value)), previous(current) {
76 current = this;
77 }
78
79 ~RowDeclarationOriginScope() {
80 current = previous;
81 }
82
83 RowDeclarationOriginScope(const RowDeclarationOriginScope &) = delete;
84 std::shared_ptr<portals::detail::ManagedOrigin> origin;
85 RowDeclarationOriginScope *previous{};
86 static inline thread_local RowDeclarationOriginScope *current{};
87};
88
89struct PreparedCaptionSource {
90 virtual ~PreparedCaptionSource() = default;
91 virtual std::expected<std::shared_ptr<const PropertyChange<std::string>>, TreeError> snapshot() = 0;
92};
93
94struct ValueCaptionBinding {
95 using Bind = std::function<std::expected<void, ManagedError>(ManagedScene &, std::shared_ptr<void>, MountContext &,
96 const void *)>;
97 const void *type{};
98 std::shared_ptr<void> source;
99 std::shared_ptr<const Bind> bind;
100 std::shared_ptr<void> graph;
101 std::shared_ptr<ValueCaptionBinding> retiredNext;
102};
103
105
107struct RowAccess;
108
109struct SceneActivity {
110 virtual ~SceneActivity() = default;
111 virtual bool active() const noexcept = 0;
112 virtual void service() noexcept = 0;
113
114 virtual void prepared() noexcept {
115 }
116
117 virtual std::expected<bool, TreeError> input(const InputEvent &) {
118 return false;
119 }
120
121 virtual std::expected<void, ManagedError> commitPopup() {
122 return {};
123 }
124
125 virtual std::expected<void, ManagedError> dismissPopup() {
126 return {};
127 }
128
129 virtual void retire() noexcept {
130 }
131
132 virtual bool tryRetire() noexcept {
133 retire();
134 return true;
135 }
136
137 virtual void wakePopup() noexcept {
138 }
139
140 virtual void cancel() noexcept = 0;
141
142 virtual void layoutPrepared(const LayoutSnapshot &) noexcept {
143 }
144
145 virtual void layoutCompleted() noexcept {
146 }
147};
150} // namespace ui::detail
151
152namespace ui {
153class ActionRef;
154class TextSource;
155class ThemeChoice;
159} // namespace ui
160
161namespace ui::detail {
162std::expected<void, ManagedError> attachAction(ManagedScene &, const ActionRef &);
163std::expected<void, ManagedError> attachActionButton(ManagedScene &, Node<Button>, const ActionRef &);
164} // namespace ui::detail
165
166namespace style::ct::detail {
167struct Access;
168} // namespace style::ct::detail
169
170namespace detail {
171struct ModelViewCheckpoint;
172struct ModelViewRestoreState;
173struct ModelRestoreChannels;
174struct PreparedModelViewChange;
175class ModelViewHistory;
176struct ManagedScrollState;
177struct ScrollIntentRecord;
178struct ManagedScrollTestAccess;
179struct DialogHostRecord;
180struct DialogRecord;
181struct MessageRecord;
182struct MessageRequest;
183struct NotificationRecord;
184struct ToastCandidate;
185struct ToastTimerMarker;
186struct ToastPayload;
187struct KeyHelpRecord;
188struct ThemeSelectionRecord;
189struct ThemeSelectorRecord;
190struct ManagedSliderRecord;
191struct ManagedSpinBoxRecord;
192enum class ThemeSelectorCommand;
193enum class ThemeSelectionCommand;
194template <class T> inline constexpr bool IS_MANAGED_TREE_RESULT = false;
195template <class Value> inline constexpr bool IS_MANAGED_TREE_RESULT<std::expected<Value, TreeError>> = true;
196
200template <class T>
201concept ManagedTreeResult = IS_MANAGED_TREE_RESULT<T>;
202
206template <class T>
207concept ManagedActionResult = std::same_as<T, void> || ManagedTreeResult<T> || std::same_as<T, EditorCommandResult> ||
208 std::same_as<T, std::expected<void, ManagedError>>;
209
217template <class Callback, class... Args>
218 requires(std::same_as<std::invoke_result_t<Callback &, Args...>, void> ||
219 ManagedTreeResult<std::invoke_result_t<Callback &, Args...>>)
220std::expected<void, TreeError> invokeIgnoringValue(Callback &callback, Args &&...args) {
221 if constexpr (std::same_as<std::invoke_result_t<Callback &, Args...>, void>) {
222 std::invoke(callback, std::forward<Args>(args)...);
223 } else {
224 auto result = std::invoke(callback, std::forward<Args>(args)...);
225
226 if (!result) {
227 return std::unexpected(result.error());
228 }
229 }
230
231 return {};
232}
233
238template <class Callback, class Event>
239concept ManagedAction = requires(Callback &action, const Event &event) {
240 { action(event) } -> ManagedActionResult;
241} || requires(Callback &action) {
242 { action() } -> ManagedActionResult;
243};
244
249template <class Callback, class T>
250concept ChangeValueAction = requires(Callback &action, const T &value) {
251 { action(value) } -> ManagedActionResult;
252};
253
258template <class Callback, class T>
260 requires(Callback &action, const PropertyUpdate<T> &receipt) {
261 { action(receipt) } -> ManagedActionResult;
262 });
263
267template <class T> inline constexpr bool IS_DERIVED_EXPECTED = false;
268template <class T> inline constexpr bool IS_DERIVED_EXPECTED<std::expected<T, TreeError>> = true;
272template <class T> inline constexpr bool IS_UNSUPPORTED_DERIVED_EXPECTED = false;
273template <class T, class E>
274inline constexpr bool IS_UNSUPPORTED_DERIVED_EXPECTED<std::expected<T, E>> = !std::same_as<E, TreeError>;
275
279template <class T> struct DerivedValue {
281 using Type = T;
282};
283
287template <class T> struct DerivedValue<std::expected<T, TreeError>> {
289 using Type = T;
290};
291
294template <class T> inline constexpr bool IS_BORROWED_DERIVED_VALUE = false;
295template <class Char, class Traits>
296inline constexpr bool IS_BORROWED_DERIVED_VALUE<std::basic_string_view<Char, Traits>> = true;
297template <class T, std::size_t Extent> inline constexpr bool IS_BORROWED_DERIVED_VALUE<std::span<T, Extent>> = true;
298template <class T> inline constexpr bool IS_BORROWED_DERIVED_VALUE<std::reference_wrapper<T>> = true;
299
304template <class Callback, class In>
306
311template <class Callback, class In>
313 std::copy_constructible<std::decay_t<Callback>> && std::invocable<Callback &, const In &> &&
314 std::equality_comparable<DerivedOutput<Callback, In>> &&
315 std::constructible_from<DerivedOutput<Callback, In>, DerivedOutput<Callback, In> &&> &&
316 (!std::is_reference_v<std::invoke_result_t<Callback &, const In &>>) &&
317 (!IS_UNSUPPORTED_DERIVED_EXPECTED<std::remove_cvref_t<std::invoke_result_t<Callback &, const In &>>>) &&
318 (!std::is_pointer_v<DerivedOutput<Callback, In>>) && (!IS_BORROWED_DERIVED_VALUE<DerivedOutput<Callback, In>>) &&
319 (!std::ranges::view<DerivedOutput<Callback, In>>);
320} // namespace detail
321
325template <class T>
326using ManagedEventHandler = std::function<std::expected<EventReply, TreeError>(T &, const RoutedEvent &)>;
327
331template <class T> using ManagedPrepareHandler = std::function<std::expected<void, TreeError>(T &, Node<Widget>)>;
332
335 std::size_t maxNodes{4096};
336 std::size_t maxStates{
337 256};
338 std::size_t maxModels{64};
340 std::size_t maxKeyHandlers{64};
341 std::size_t maxClickHandlers{256};
342 std::size_t maxClickHandlersPerNode{64};
344 std::size_t maxLayoutHandlers{256};
346 3};
347 std::size_t maxObservers{256};
348 std::size_t maxObserversPerNode{64};
350 std::size_t maxMessageRequests{32};
351 std::size_t maxKeyLabelBytes{512};
352 std::size_t maxKeyDescriptionBytes{2048};
353 std::size_t maxKeyProjectionBytes{1048576};
355 std::size_t maxEditingHandlers{256};
357 std::size_t maxChangeHandlers{256};
358 std::size_t maxChangeHandlersPerNode{64};
359};
360
367template <std::equality_comparable T> class ManagedState {
368public:
370 ManagedState() = default;
371
375 std::expected<PropertyUpdate<T>, TreeError> set(const T &value) const {
376 ui::detail::SetupFailurePause setup(facade_);
378 auto model = lock();
379 ui::detail::CurrentSceneScope current(facade_);
380
381 return model ? (*model)->set(value) : std::unexpected(model.error());
382 }
383
387 std::expected<PropertyUpdate<T>, TreeError> set(T &&value) const {
388 ui::detail::SetupFailurePause setup(facade_);
390 auto model = lock();
391 ui::detail::CurrentSceneScope current(facade_);
392
393 return model ? (*model)->set(std::move(value)) : std::unexpected(model.error());
394 }
395
399 std::expected<std::shared_ptr<const PropertyChange<T>>, TreeError> snapshot() const {
400 auto model = lock();
401
402 return model ? (*model)->snapshot() : std::unexpected(model.error());
403 }
404
405private:
406 friend class ManagedScene;
407 friend class NumericState;
408 friend struct ui::detail::Access;
409 friend struct ui::detail::RowAccess;
410 friend struct detail::ManagedNavigationRecord;
411
412 std::expected<std::shared_ptr<Property<T>>, TreeError> lock() const {
413 if (owner_ != std::thread::id{} && owner_ != std::this_thread::get_id()) {
414 return std::unexpected(TreeError::WRONG_THREAD);
415 }
416
417 if (lifetime_.expired()) {
418 return std::unexpected(TreeError::CLOSED);
419 }
420
421 if (origin_) {
422 auto live = origin_->check();
423
424 if (!live) {
425 return std::unexpected(live.error());
426 }
427 }
428
429 auto model = model_.lock();
430
431 if (!model) {
432 return std::unexpected(TreeError::CLOSED);
433 }
434
435 return model;
436 }
437
438 std::weak_ptr<Property<T>> model_;
439 std::weak_ptr<ui::detail::SceneAnchor> facade_;
440 std::weak_ptr<const void> lifetime_;
441 std::thread::id owner_{};
442 NodeId scene_{};
443 std::shared_ptr<detail::ManagedOrigin> origin_;
444 // Scheduling provenance never participates in source lifetime checks.
445 std::weak_ptr<detail::ManagedOrigin> recoveryOrigin_;
446};
447
452public:
454 NumericState() = default;
455
457 std::expected<std::shared_ptr<const PropertyChange<NumericValue>>, ManagedError> snapshot() const;
458
462 std::expected<PropertyUpdate<NumericValue>, ManagedError> set(double candidate) const;
463
468 std::expected<PropertyUpdate<NumericValue>, ManagedError> configure(double initial, NumericRange range) const;
469
470private:
471 friend class ManagedScene;
472
473 explicit NumericState(ManagedState<NumericValue> state) : state_(std::move(state)) {
474 }
475
477};
478
484template <std::equality_comparable T> class ManagedSource {
485public:
487 ManagedSource() = default;
488
492 std::expected<std::shared_ptr<const PropertyChange<T>>, TreeError> snapshot() const {
493 return state_.snapshot();
494 }
495
496private:
497 friend class ManagedScene;
498 friend class ManagedNavigation;
499 friend struct ui::detail::Access;
500
501 explicit ManagedSource(ManagedState<T> state) : state_(std::move(state)) {
502 }
503
504 ManagedState<T> state_;
505};
506
508namespace detail {
509template <class Source> struct CollectionSource;
510
511template <class T>
512 requires std::copy_constructible<T> && std::equality_comparable<T>
513struct CollectionSource<ManagedSource<RowCollection<T>>> {
514 using Row = T;
515};
516
517template <class Source>
518concept ManagedCollectionSource = requires { typename CollectionSource<std::remove_cvref_t<Source>>::Row; };
519} // namespace detail
520
522
530class ManagedScene final : public ApplicationScene {
531public:
536 static std::expected<std::unique_ptr<ManagedScene>, ManagedError> create(Application &app,
537 ManagedOptions options = {});
538
541 ManagedScene(const ManagedScene &) = delete;
542 ManagedScene &operator=(const ManagedScene &) = delete;
543
545 Node<Widget> root() const noexcept {
546 return root_;
547 }
548
550 WidthPolicy widthPolicy() const noexcept {
551 return app_.widthPolicy();
552 }
553
561 std::expected<ManagedSource<GraphemeText>, ManagedError>
562 liveText(const ui::TextSource &source, PropertyOptions options = {},
563 std::source_location origin = std::source_location::current());
564
572 std::expected<void, ManagedError> remove(Node<Widget> node);
573
583 template <class T, class... Args>
584 requires std::derived_from<T, Widget>
585 std::expected<Node<T>, ManagedError> emplace(Node<Widget> parent, Args &&...args) {
586 return emplaceConfigured<T>(parent, {}, std::forward<Args>(args)...);
587 }
588
595 std::expected<Node<LogView>, ManagedError> logView(Node<Widget> parent, std::string_view initial = {},
596 LogViewConfig config = {}, ControlStyle style = {},
597 SizePolicy policy = DEFAULT_LOG_VIEW_POLICY,
598 std::optional<FrameOptions> frame = {});
602 std::expected<LogAppendReceipt, ManagedError> appendLogBatch(Node<LogView> node, std::string_view bytes);
606 std::expected<void, ManagedError> setLogModel(Node<LogView> node, ui::LogSource source);
608 std::expected<void, ManagedError> followLogTail(Node<LogView> node);
610 std::expected<void, ManagedError> clearLog(Node<LogView> node);
612 std::expected<LogStatus, ManagedError> logStatus(Node<LogView> node);
613
622 std::expected<Node<ScrollBar>, ManagedError> scrollBar(Node<Widget> parent,
623 std::shared_ptr<ScrollController> controller = {},
625 ScrollBarOptions options = {}, ControlStyle style = {},
626 bool geometryWriter = true);
627
633 std::expected<void, ManagedError> setScrollOffset(Node<Widget> node, ScrollAxis axis, ScrollOffset offset);
638 std::expected<void, ManagedError> setScrollMetrics(Node<ScrollBar> node, ScrollAxisMetrics metrics);
644 std::expected<void, ManagedError> ensureVisible(Node<Widget> node, Node<Widget> root = {});
645
654 template <std::equality_comparable T>
655 std::expected<ManagedState<T>, ManagedError> state(T initial, Invalidation kind = Invalidation::PAINT,
656 PropertyOptions options = {}) {
657 if constexpr (std::same_as<T, std::string>) {
658 // MSVC Debug string moves may allocate a proxy in noexcept; copy inside Property's checked boundary.
659 return stateFrom<T>(std::as_const(initial), kind, options);
660 } else {
661 return stateFrom<T>(std::move(initial), kind, options);
662 }
663 }
664
669 std::expected<NumericState, ManagedError> numericState(double initial = 0, NumericRange range = {});
670
683 template <class W, std::equality_comparable T, class Callback>
684 requires std::copy_constructible<std::decay_t<Callback>> &&
685 (std::same_as<std::invoke_result_t<Callback &, const T &>, void> ||
686 std::same_as<std::invoke_result_t<Callback &, const T &>, std::expected<void, TreeError>>)
687 std::expected<void, ManagedError> observe(Node<W> receiver, ManagedState<T> model, Callback &&callback) {
688 ui::detail::SetupFailureScope mask({}, nullptr, nullptr);
689 auto admitted = observerAdmission(receiver);
690 if (!admitted) {
691 return admitted;
692 }
693
694 auto property = model.lock();
695 if (!property || model.scene_ != root_.id()) {
696 return std::unexpected(
697 error(ManagedPhase::BIND, receiver, property ? TreeError::INVALID_ARGUMENT : property.error()));
698 }
699
700 try {
701 if constexpr (std::is_pointer_v<std::decay_t<Callback>> || requires { callback.operator bool(); }) {
702 if (!static_cast<bool>(callback)) {
703 return std::unexpected(error(ManagedPhase::BIND, receiver, TreeError::INVALID_ARGUMENT));
704 }
705 }
706
707 auto record = std::make_shared<ObserverRecord>();
708 record->inputOrigin = model.origin_;
709 record->recoveryOrigin = model.origin_ ? model.origin_ : model.recoveryOrigin_;
710 record->scene = this;
711 record->node = receiver;
712 prepareObserverRecord(record, *property, std::forward<Callback>(callback));
713
714 // User capture construction/destruction may have changed either identity or the budget.
715 admitted = observerAdmission(receiver);
716 property = model.lock();
717 if (!admitted) {
718 return admitted;
719 }
720 if (!property || model.scene_ != root_.id()) {
721 return std::unexpected(
722 error(ManagedPhase::BIND, receiver, property ? TreeError::INVALID_ARGUMENT : property.error()));
723 }
724 observers_.reserve(observers_.size() + 1);
725 auto token = connectObserverRecord(receiver, *property, record);
726 if (!token) {
727 return std::unexpected(error(ManagedPhase::BIND, receiver, token.error()));
728 }
729
730 auto dirty = app_.tree().invalidate(root_, Invalidation::PAINT);
731 if (!dirty) {
732 return std::unexpected(error(ManagedPhase::BIND, receiver, dirty.error()));
733 }
734 record->subscription = std::move(*token);
735 observers_.push_back(std::move(record));
736 return {};
737 } catch (const std::bad_alloc &) {
738 return std::unexpected(error(ManagedPhase::BIND, receiver, TreeError::NO_MEMORY));
739 } catch (const std::length_error &) {
740 return std::unexpected(error(ManagedPhase::BIND, receiver, TreeError::NODE_LIMIT));
741 } catch (...) {
742 return std::unexpected(error(ManagedPhase::BIND, receiver, TreeError::CALLBACK_FAILED));
743 }
744 }
745
752 template <std::equality_comparable T, class Callback>
753 requires std::copy_constructible<std::decay_t<Callback>> &&
754 (std::same_as<std::invoke_result_t<Callback &, const T &>, void> ||
755 std::same_as<std::invoke_result_t<Callback &, const T &>, std::expected<void, TreeError>>)
756 std::expected<void, ManagedError> observe(ManagedState<T> model, Callback &&callback) {
757 return observe(root_, model, std::forward<Callback>(callback));
758 }
759
768 template <class W, std::equality_comparable T, class Callback>
769 requires std::copy_constructible<std::decay_t<Callback>> &&
770 (std::same_as<std::invoke_result_t<Callback &, const T &>, void> ||
771 std::same_as<std::invoke_result_t<Callback &, const T &>, std::expected<void, TreeError>>)
772 std::expected<void, ManagedError> observe(Node<W> receiver, ManagedSource<T> source, Callback &&callback) {
773 return observe(receiver, source.state_, std::forward<Callback>(callback));
774 }
775
782 template <std::equality_comparable T, class Callback>
783 requires std::copy_constructible<std::decay_t<Callback>> &&
784 (std::same_as<std::invoke_result_t<Callback &, const T &>, void> ||
785 std::same_as<std::invoke_result_t<Callback &, const T &>, std::expected<void, TreeError>>)
786 std::expected<void, ManagedError> observe(ManagedSource<T> source, Callback &&callback) {
787 return observe(root_, source.state_, std::forward<Callback>(callback));
788 }
789
801 template <std::equality_comparable In, class Transform>
803 std::expected<ManagedSource<detail::DerivedOutput<Transform, In>>, ManagedError>
804 derive(ManagedState<In> input, Transform &&transform, Invalidation kind = Invalidation::PAINT,
805 PropertyOptions options = {}, std::source_location origin = std::source_location::current());
806
816 template <std::equality_comparable In, class Transform>
817 requires detail::ManagedDerivation<Transform, In>
818 std::expected<ManagedSource<detail::DerivedOutput<Transform, In>>, ManagedError>
820 PropertyOptions options = {}, std::source_location origin = std::source_location::current()) {
821 return derive(input.state_, std::forward<Transform>(transform), kind, options, origin);
822 }
823
828 std::expected<void, ManagedError> onClick(Node<Button> node, std::function<std::expected<void, TreeError>()> action);
829
839 template <class Callback>
841 std::expected<void, ManagedError> onClick(Node<Button> node, Callback action) {
842 if constexpr (std::same_as<Callback, ui::ActionRef>) {
843 return ui::detail::attachActionButton(*this, node, action);
844 }
845
846 try {
847 return onButtonClick(node, actionAdapter<ClickEvent>(std::move(action)),
848 std::invocable<Callback &, const ClickEvent &>);
849 } catch (const std::bad_alloc &) {
850 return std::unexpected(error(ManagedPhase::BIND, node, TreeError::NO_MEMORY));
851 } catch (...) {
852 return std::unexpected(error(ManagedPhase::BIND, node, TreeError::CALLBACK_FAILED));
853 }
854 }
855
865 template <class Callback>
867 std::expected<void, ManagedError> onKey(KeyEvent chord, Callback action) {
868 auto allowed = keyBoundary();
869
870 if (!allowed) {
871 return allowed;
872 }
873
874 if (keyHandlers_ >= options_.maxKeyHandlers) {
875 return std::unexpected(error(ManagedPhase::BIND, root_, TreeError::NODE_LIMIT));
876 }
877
878 try {
879 auto reusable = prepareReusableAction(action);
880 if (!reusable) {
881 return reusable;
882 }
883
884 auto adapter = actionAdapter<KeyEvent>(std::move(action));
885
886 if (!adapter) {
887 return std::unexpected(error(ManagedPhase::BIND, root_, TreeError::INVALID_ARGUMENT));
888 }
889
890 return registerLegacyKey(chord, std::move(adapter));
891 } catch (const std::bad_alloc &) {
892 return std::unexpected(error(ManagedPhase::BIND, root_, TreeError::NO_MEMORY));
893 } catch (...) {
894 return std::unexpected(error(ManagedPhase::BIND, root_, TreeError::CALLBACK_FAILED));
895 }
896 }
897
904 template <class Callback>
906 std::expected<KeyBinding, ManagedError> onKey(const KeySelection &selection, KeyInfo info, Callback action,
907 std::source_location origin = std::source_location::current()) {
908 auto allowed = keyBoundary();
909 if (!allowed) {
910 return std::unexpected(allowed.error());
911 }
912 auto observed = observeKeyScopes();
913 if (!observed) {
914 return std::unexpected(observed.error());
915 }
916 KeyTransaction transaction(*this);
917 try {
918 const auto &shortcut = detail::KeySelectionAccess::shortcut(selection);
919 if (!shortcut || !*shortcut) {
920 const auto cause = shortcut ? ShortcutError{ShortcutErrorKind::INVALID_CHORD, 0} : shortcut.error();
921 auto failure =
922 error(ManagedPhase::BIND, root_,
924 failure.shortcut = cause;
925 failure.registrationOrigin = origin;
926 return std::unexpected(failure);
927 }
928 auto validated = keyPreflight(info);
929 if (!validated) {
930 return std::unexpected(validated.error());
931 }
932 transaction.owner = info.owner;
933 auto reusable = prepareReusableAction(action);
934 if (!reusable) {
935 return std::unexpected(reusable.error());
936 }
937
938 return registerAnnotatedKey(selection, std::move(info), actionAdapter<KeyEvent>(std::move(action), origin),
939 origin, transaction);
940 } catch (const std::bad_alloc &) {
941 return std::unexpected(error(ManagedPhase::BIND, root_, TreeError::NO_MEMORY));
942 } catch (...) {
943 return std::unexpected(error(ManagedPhase::BIND, root_, TreeError::CALLBACK_FAILED));
944 }
945 }
946
949 std::expected<KeyBindingsSnapshot, ManagedError> keyBindings();
952 std::expected<void, ManagedError> setKeyCapabilities(KeyCapabilities capabilities);
953
968 template <class Value, class Callback>
969 requires std::same_as<std::remove_cvref_t<Value>, Shortcut> && detail::ManagedAction<Callback, KeyEvent>
970 std::expected<void, ManagedError> onKey(Value &&shortcut, Callback action, ShortcutBehavior behavior = {},
971 ShortcutOptions options = {},
972 std::source_location origin = std::source_location::current()) {
973 return onShortcutActions(std::forward<Value>(shortcut), action,
974 behavior.repeat ? detail::ShortcutActions::PRESS_REPEAT : detail::ShortcutActions::PRESS,
975 options, origin);
976 }
977
988 template <class Callback>
989 requires detail::ManagedAction<Callback, KeyEvent>
990 std::expected<void, ManagedError> onKey(const KeySelection &selection, Callback action,
991 std::source_location origin = std::source_location::current()) {
992 auto allowed = keyBoundary();
993
994 if (!allowed) {
995 return allowed;
996 }
997
998 const auto &shortcut = detail::KeySelectionAccess::shortcut(selection);
999
1000 if (!shortcut || !*shortcut) {
1001 const auto cause = shortcut ? ShortcutError{ShortcutErrorKind::INVALID_CHORD, 0} : shortcut.error();
1002 auto failure =
1003 error(ManagedPhase::BIND, root_,
1005
1006 failure.shortcut = cause;
1007 failure.registrationOrigin = origin;
1008
1009 return std::unexpected(std::move(failure));
1010 }
1011
1012 return onShortcutActions(**shortcut, action, detail::KeySelectionAccess::actions(selection),
1013 detail::KeySelectionAccess::options(selection), origin);
1014 }
1015
1019 std::expected<bool, ManagedError> checkedValue(Node<CheckBox> node);
1023 std::expected<PropertyUpdate<bool>, ManagedError> setChecked(Node<CheckBox> node, bool value);
1024
1030 std::expected<void, ManagedError> bind(Node<CheckBox> node, ManagedState<bool> model,
1031 std::function<std::expected<void, TreeError>(CheckBoxResult)> changed = {});
1032
1037 std::expected<ManagedState<RadioGroupValue>, ManagedError>
1038 radioState(std::span<const TextValue> captions, KeyTextResolver resolver = {}, CollectionLimits limits = {});
1042 std::expected<ManagedState<RadioGroupValue>, ManagedError>
1043 radioState(std::span<const RadioOption> options, KeyTextResolver resolver = {}, CollectionLimits limits = {});
1047 std::expected<ManagedState<RadioGroupValue>, ManagedError>
1048 radioState(std::initializer_list<std::string_view> captions);
1052 std::expected<void, ManagedError> bind(Node<RadioGroup> node, ManagedState<RadioGroupValue> model,
1053 std::function<std::expected<void, TreeError>(RadioGroupResult)> changed = {});
1055 std::expected<RadioGroupValue, ManagedError> radioValue(Node<RadioGroup> node);
1059 std::expected<PropertyUpdate<RadioGroupValue>, ManagedError> selectRadio(Node<RadioGroup> node,
1060 std::optional<RowId> id);
1061
1067 template <class Callback, class T>
1068 requires(std::derived_from<T, RadioGroup> && std::copy_constructible<Callback> &&
1070 std::expected<void, ManagedError> onChange(Node<T> node, Callback callback,
1071 std::source_location origin = std::source_location::current()) {
1072 auto allowed = boundary(ManagedPhase::BIND, node);
1073 if (!allowed) {
1074 return allowed;
1075 }
1076
1077 const auto lifetime = std::weak_ptr<const void>(lifetime_);
1078 try {
1079 auto entry = find(node);
1080 if (!entry || !entry->changes || !entry->changes->radio) {
1081 return std::unexpected(error(ManagedPhase::BIND, node, TreeError::INVALID_ARGUMENT));
1082 }
1083
1084 auto action = changeAdapter<RadioGroupValue>(std::move(callback), origin);
1085 if (lifetime.expired()) {
1086 return std::unexpected(error(ManagedPhase::BIND, node, TreeError::CLOSED));
1087 }
1088
1089 return registerChange(node, ChangeRecord{std::move(action), origin});
1090 } catch (const std::bad_alloc &) {
1091 return std::unexpected(error(ManagedPhase::BIND, node, TreeError::NO_MEMORY));
1092 } catch (...) {
1093 return std::unexpected(error(ManagedPhase::BIND, node, TreeError::CALLBACK_FAILED));
1094 }
1095 }
1096
1103 std::expected<void, ManagedError> bind(Node<CheckBox> node, ManagedState<CheckState> model,
1104 std::function<std::expected<void, TreeError>(CheckStateResult)> changed = {},
1105 CheckBoxOptions options = {});
1106
1116 template <class Callback, class T>
1117 requires(std::derived_from<T, CheckBox> && std::copy_constructible<Callback> &&
1118 (detail::ChangeAction<Callback, bool> || detail::ChangeAction<Callback, CheckState>))
1119 std::expected<void, ManagedError> onChange(Node<T> node, Callback callback,
1120 std::source_location origin = std::source_location::current()) {
1121 auto boolean = changeModel(node);
1122
1123 if (!boolean) {
1124 return std::unexpected(boolean.error());
1125 }
1126
1127 const auto lifetime = std::weak_ptr<const void>(lifetime_);
1128
1129 try {
1130 if (*boolean) {
1132 auto action = changeAdapter<bool>(std::move(callback), origin);
1133
1134 if (lifetime.expired()) {
1135 return std::unexpected(error(ManagedPhase::BIND, node, TreeError::CLOSED));
1136 }
1137
1138 return registerChange(node, ChangeRecord{std::move(action), origin});
1139 }
1140 } else {
1142 auto action = changeAdapter<CheckState>(std::move(callback), origin);
1143
1144 if (lifetime.expired()) {
1145 return std::unexpected(error(ManagedPhase::BIND, node, TreeError::CLOSED));
1146 }
1147
1148 return registerChange(node, ChangeRecord{std::move(action), origin});
1149 }
1150 }
1151
1152 return std::unexpected(error(ManagedPhase::BIND, node, TreeError::INVALID_ARGUMENT));
1153 } catch (const std::bad_alloc &) {
1154 return std::unexpected(error(ManagedPhase::BIND, node, TreeError::NO_MEMORY));
1155 } catch (...) {
1156 return std::unexpected(error(ManagedPhase::BIND, node, TreeError::CALLBACK_FAILED));
1157 }
1158 }
1159
1165 std::expected<void, ManagedError> bind(Node<Slider> node, NumericState model,
1166 std::function<std::expected<void, TreeError>(SliderResult)> changed = {});
1167
1172 std::expected<void, ManagedError> bind(Node<SpinBox> node, NumericState model, LineEditOptions options = {},
1173 std::uint64_t pageSteps = 10);
1174
1181 template <class Callback, class T>
1182 requires((std::derived_from<T, Slider> || std::same_as<T, SpinBox>) &&
1183 std::copy_constructible<std::decay_t<Callback>> &&
1185 requires(std::decay_t<Callback> &action, const PropertyUpdate<NumericValue> &receipt) {
1186 { action(receipt) } -> detail::ManagedActionResult;
1187 }))
1188 std::expected<void, ManagedError> onChange(Node<T> node, const Callback &callback,
1189 std::source_location origin = std::source_location::current()) {
1190 const auto lifetime = std::weak_ptr<const void>(lifetime_);
1191
1192 try {
1193 auto action = [&] {
1194 if constexpr (detail::ChangeValueAction<std::decay_t<Callback>, double>) {
1195 using OwnedCallback = std::decay_t<Callback>;
1196 OwnedCallback owned(callback);
1197
1198 if (lifetime.expired()) {
1199 return std::function<EditorCommandResult(const PropertyUpdate<NumericValue> &)>{};
1200 }
1201
1202 if constexpr (std::is_pointer_v<OwnedCallback> || requires { owned.operator bool(); }) {
1203 const bool present = static_cast<bool>(owned);
1204
1205 if (lifetime.expired() || !present) {
1206 return std::function<EditorCommandResult(const PropertyUpdate<NumericValue> &)>{};
1207 }
1208 }
1209
1210 auto converted = [callback =
1211 std::move(owned)](const PropertyUpdate<NumericValue> &receipt) mutable -> decltype(auto) {
1212 return callback(receipt.snapshot->value.value());
1213 };
1214
1215 if (lifetime.expired()) {
1216 return std::function<EditorCommandResult(const PropertyUpdate<NumericValue> &)>{};
1217 }
1218
1219 return actionAdapter<PropertyUpdate<NumericValue>>(std::move(converted), origin);
1220 } else {
1221 return actionAdapter<PropertyUpdate<NumericValue>>(callback, origin);
1222 }
1223 }();
1224
1225 if (lifetime.expired()) {
1226 return std::unexpected(error(ManagedPhase::BIND, node, TreeError::CLOSED));
1227 }
1228
1229 return registerNumericChange(node, std::move(action), origin);
1230 } catch (const std::bad_alloc &) {
1231 return std::unexpected(error(ManagedPhase::BIND, node, TreeError::NO_MEMORY));
1232 } catch (...) {
1233 return std::unexpected(error(ManagedPhase::BIND, node, TreeError::CALLBACK_FAILED));
1234 }
1235 }
1236
1243 template <class Callback, class T>
1244 requires(std::derived_from<T, Slider> && std::copy_constructible<std::decay_t<Callback>> &&
1246 std::expected<void, ManagedError> onEditingFinished(Node<T> node, const Callback &callback,
1247 std::source_location origin = std::source_location::current()) {
1248 const auto lifetime = std::weak_ptr<const void>(lifetime_);
1249
1250 try {
1251 auto action = actionAdapter<SliderOperationEvent>(callback, origin);
1252
1253 if (lifetime.expired()) {
1254 return std::unexpected(error(ManagedPhase::BIND, node, TreeError::CLOSED));
1255 }
1256
1257 return registerNumericFinished(node, std::move(action), origin);
1258 } catch (const std::bad_alloc &) {
1259 return std::unexpected(error(ManagedPhase::BIND, node, TreeError::NO_MEMORY));
1260 } catch (...) {
1261 return std::unexpected(error(ManagedPhase::BIND, node, TreeError::CALLBACK_FAILED));
1262 }
1263 }
1264
1272 std::expected<void, ManagedError> bind(Node<LineEdit> node, ManagedState<std::string> model,
1273 std::function<std::expected<void, TreeError>(LineEditResult)> result = {},
1274 std::shared_ptr<Clipboard> clipboard = {},
1275 std::function<bool(std::string_view)> validate = {});
1276
1284 std::expected<void, ManagedError> bind(Node<Password> node, ManagedState<PasswordValue> model,
1285 std::function<std::expected<void, TreeError>(PasswordResult)> result = {},
1286 std::shared_ptr<Clipboard> clipboard = {},
1287 std::function<bool(SecretView)> validate = {});
1288
1292 std::expected<PasswordValue, ManagedError> passwordValue(Node<Password> node) const;
1297 std::expected<void, ManagedError> setPasswordValue(Node<Password> node, PasswordValue value);
1298
1305 template <class Callback>
1307 std::expected<void, ManagedError> onTextEdited(Node<LineEdit> node, Callback callback,
1308 std::source_location origin = std::source_location::current()) {
1309 try {
1310 return registerEditing(node,
1311 EditorEventRecord{actionAdapter<TextEditedEvent>(std::move(callback), origin), origin});
1312 } catch (const std::bad_alloc &) {
1313 return std::unexpected(error(ManagedPhase::BIND, node, TreeError::NO_MEMORY));
1314 } catch (...) {
1315 return std::unexpected(error(ManagedPhase::BIND, node, TreeError::CALLBACK_FAILED));
1316 }
1317 }
1318
1326 template <class Callback, class T>
1327 requires(std::derived_from<T, LineEdit> && detail::ManagedAction<Callback, EditingFinishedEvent>)
1328 std::expected<void, ManagedError> onEditingFinished(Node<T> node, Callback callback,
1329 std::source_location origin = std::source_location::current()) {
1330 try {
1331 return registerEditing(
1332 node, EditorEventRecord{actionAdapter<EditingFinishedEvent>(std::move(callback), origin), origin});
1333 } catch (const std::bad_alloc &) {
1334 return std::unexpected(error(ManagedPhase::BIND, node, TreeError::NO_MEMORY));
1335 } catch (...) {
1336 return std::unexpected(error(ManagedPhase::BIND, node, TreeError::CALLBACK_FAILED));
1337 }
1338 }
1339
1348 std::expected<void, ManagedError> bindText(Node<Control> node, ManagedState<std::string> model);
1349
1354 std::expected<void, ManagedError> bindText(Node<Control> node, ManagedSource<std::string> source) {
1355 return bindText(node, source.state_);
1356 }
1357
1362 std::expected<void, ManagedError> focusScope(Node<Widget> node);
1363
1369 std::expected<void, ManagedError> overlayHost(Node<OverlayHost> host, Node<Widget> body);
1376 std::expected<void, ManagedError> dialog(Node<Dialog> node, Node<Widget> panel, Node<Widget> body);
1381 std::expected<void, ManagedError> openDialog(Node<Widget> node);
1386 std::expected<void, ManagedError> dismissDialog(Node<Widget> node);
1390 std::expected<bool, ManagedError> dialogOpened(Node<Widget> node);
1397 std::expected<void, ManagedError> dialogAnchor(Node<Widget> node, Node<Widget> anchor, DialogPlacement placement);
1398
1404 template <class Callback>
1405 requires std::copy_constructible<Callback> &&
1406 (std::same_as<std::invoke_result_t<Callback &, DialogDismissReason>, void> ||
1407 std::same_as<std::invoke_result_t<Callback &, DialogDismissReason>, std::expected<void, TreeError>>)
1408 std::expected<void, ManagedError> onDismiss(Node<Dialog> node, Callback callback) {
1409 try {
1410 return setDialogDismiss(
1411 node, ui::detail::currentSceneCallback(
1412 facadeContext(),
1413 [this, lifetime = std::weak_ptr<const void>(lifetime_),
1414 callback = std::move(callback)](DialogDismissReason reason) mutable -> std::expected<void, TreeError> {
1415 if (lifetime.expired()) {
1416 return std::unexpected(TreeError::CLOSED);
1417 }
1418 auto admitted = actionBoundary();
1419 if (!admitted) {
1420 return admitted;
1421 }
1422 ActionAdmission admission(*this);
1423 if constexpr (std::same_as<std::invoke_result_t<Callback &, DialogDismissReason>, void>) {
1424 callback(reason);
1425 return {};
1426 } else {
1427 return callback(reason);
1428 }
1429 }));
1430 } catch (const std::bad_alloc &) {
1431 return std::unexpected(error(ManagedPhase::BIND, node, TreeError::NO_MEMORY));
1432 } catch (...) {
1433 return std::unexpected(error(ManagedPhase::BIND, node, TreeError::CALLBACK_FAILED));
1434 }
1435 }
1436
1441 std::expected<void, ManagedError> focusDefault(Node<Widget> node);
1446 std::expected<void, ManagedError> focus(Node<Widget> node);
1453 std::expected<void, ManagedError> enterFocusScope(Node<Widget> node);
1459 std::expected<void, ManagedError> leaveFocusScope(Node<Widget> node);
1460
1467 template <class T>
1468 std::expected<void, ManagedError> onEvent(Node<T> node, std::type_identity_t<ManagedEventHandler<T>> callback) {
1469 ui::detail::SetupFailureScope mask({}, nullptr, nullptr);
1470 ManagedEventHandler<T> incoming;
1471
1472 incoming.swap(callback);
1473 auto entry = bindingEntry(node);
1474
1475 if (!entry) {
1476 return std::unexpected(entry.error());
1477 }
1478
1479 if (!incoming) {
1480 return std::unexpected(error(ManagedPhase::BIND, node, TreeError::INVALID_ARGUMENT));
1481 }
1482
1483 try {
1484 auto bound = app_.router().bind(
1485 node, [this, node, callback = ui::detail::currentSceneCallback(facadeContext(), std::move(incoming))](
1486 T &widget, const RoutedEvent &event) {
1487 try {
1488 auto result = callback(widget, event);
1489
1490 if (result) {
1491 return *result;
1492 }
1493
1494 remember(error(ManagedPhase::INPUT, node, result.error()));
1495 } catch (...) {
1496 remember(error(ManagedPhase::INPUT, node, TreeError::CALLBACK_FAILED));
1497 }
1498
1499 return EventReply::HANDLED;
1500 });
1501
1502 if (!bound) {
1503 return std::unexpected(error(ManagedPhase::BIND, node, bound.error()));
1504 }
1505
1506 (*entry)->binding.template emplace<ActionBinding>(std::move(*bound));
1507
1508 return {};
1509 } catch (const std::bad_alloc &) {
1510 return std::unexpected(error(ManagedPhase::BIND, node, TreeError::NO_MEMORY));
1511 } catch (...) {
1512 return std::unexpected(error(ManagedPhase::BIND, node, TreeError::CALLBACK_FAILED));
1513 }
1514 }
1515
1523 template <class T>
1524 std::expected<void, ManagedError> onPrepare(Node<T> node, std::type_identity_t<ManagedPrepareHandler<T>> callback) {
1525 ui::detail::SetupFailureScope mask({}, nullptr, nullptr);
1526 ManagedPrepareHandler<T> incoming;
1527
1528 incoming.swap(callback);
1529 auto allowed = boundary(ManagedPhase::BIND, node);
1530
1531 if (!allowed) {
1532 return allowed;
1533 }
1534
1535 auto entry = find(node);
1536
1537 if (!entry || !incoming) {
1538 return std::unexpected(error(ManagedPhase::BIND, node, TreeError::INVALID_ARGUMENT));
1539 }
1540
1541 try {
1542 entry->customSync =
1543 [this, node,
1544 callback = ui::detail::currentSceneCallback(facadeContext(), std::move(incoming))](Node<Widget> focused) {
1545 std::expected<void, TreeError> result;
1546 auto edited = app_.tree().edit(node, [&](T &widget) {
1547 result = callback(widget, focused);
1548 });
1549
1550 return edited ? result : edited;
1551 };
1552
1553 return {};
1554 } catch (const std::bad_alloc &) {
1555 return std::unexpected(error(ManagedPhase::BIND, node, TreeError::NO_MEMORY));
1556 }
1557 }
1558
1563 std::expected<void, ManagedError> style(Node<Widget> node, StyleTarget target);
1564
1569 std::expected<void, ManagedError> id(Node<Widget> node, std::string_view value);
1570
1577 std::expected<void, ManagedError> classes(Node<Widget> node, std::vector<std::string> values);
1578
1583 std::expected<void, ManagedError> theme(StyleSheet sheet);
1584
1589 std::expected<void, ManagedError> enableStyleLayers(StyleLayerOptions options = {});
1590
1611 std::expected<StyleLayerHandle, ManagedError> styleDocument(StyleTier tier, std::string_view name,
1612 const PssDocument &document,
1613 std::optional<StyleLayerOptions> options = std::nullopt);
1614
1624 std::expected<std::vector<StyleLayerSource>, ManagedError> styleSources() const;
1625
1632 std::expected<void, ManagedError> validateStyleLayer(StyleLayerHandle handle) const;
1633
1639 std::expected<StyleLayerHandle, ManagedError> addLayer(StyleTier tier, std::string_view name,
1640 const StyleSheet &sheet);
1645 std::expected<Invalidation, ManagedError> replaceLayer(StyleLayerHandle handle, const StyleSheet &sheet);
1649 std::expected<Invalidation, ManagedError> removeLayer(StyleLayerHandle handle);
1653 std::expected<Invalidation, ManagedError> updateLayers(std::span<const StyleLayerUpdate> updates);
1657 std::expected<StyleLayerHandle, ManagedError> baseLayer(StyleTier tier) const;
1661 std::expected<Invalidation, ManagedError> styleDefaults(const StyleSheet &sheet);
1662
1667 std::expected<void, ManagedError>
1668 onInput(std::function<std::expected<bool, ManagedError>(const InputEvent &)> callback);
1669
1679 std::expected<void, TreeError> reportError(ManagedError failure,
1680 std::span<const ManagedDiagnosticContext> contexts = {},
1681 std::source_location origin = std::source_location::current()) noexcept;
1682
1689 std::expected<void, ManagedError> onError(ManagedErrorHandler callback);
1690
1695 std::expected<ManagedDiagnosticBatch, TreeError> diagnostics() const;
1696
1700 std::expected<void, TreeError> clearErrors() noexcept;
1701
1707
1715 template <class T>
1716 std::expected<ManagedModel<T>, ManagedError> model(std::shared_ptr<const ModelSnapshot<T>> initial,
1717 ModelOptions options = {}, ManagedViewHandler<T> prepared = {});
1718
1727 template <class Source>
1728 requires detail::ManagedCollectionSource<Source>
1729 std::expected<ManagedModel<typename detail::CollectionSource<std::remove_cvref_t<Source>>::Row>, ManagedError>
1730 model(Source &&source, CollectionModelOptions options = {});
1731
1737 std::expected<ManagedNavigation, ManagedError> navigation(ModelResource resource, SourceStamp session,
1738 NavigationOptions options = {});
1743 std::expected<LogNavigation, ManagedError> logNavigation(LogCheckpointOptions options = {});
1744
1750 template <class T>
1751 std::expected<ManagedNavigation, ManagedError> navigation(ManagedModel<T> model, NavigationOptions options = {});
1752
1760 template <class T>
1761 std::expected<ManagedNavigation, ManagedError> navigation(ManagedModel<T> model, ModelResource resource,
1762 SourceStamp session, NavigationOptions options = {});
1763
1770 template <class T>
1771 std::expected<void, ManagedError> bindNavigation(Node<VirtualList<T>> node, ManagedNavigation navigation,
1772 NavigationBindingOptions options = {});
1773
1780 template <class T>
1781 std::expected<void, ManagedError> bindNavigation(Node<VirtualTable<T>> node, ManagedNavigation navigation,
1782 NavigationBindingOptions options = {});
1783
1795 template <class T>
1796 std::expected<Node<VirtualTable<T>>, ManagedError>
1797 virtualTable(Node<Widget> parent, ManagedModel<T> model,
1798 std::type_identity_t<std::span<const TableColumn<T>>> columns, VirtualTableOptions options = {},
1799 SizePolicy policy = DEFAULT_VIEWPORT_POLICY, std::type_identity_t<ManagedViewHandler<T>> prepared = {});
1800
1812 template <class T>
1813 std::expected<Node<VirtualList<T>>, ManagedError>
1814 virtualList(Node<Widget> parent, ManagedModel<T> model, std::type_identity_t<ManagedListFormatter<T>> delegate,
1815 VirtualListOptions options = {}, SizePolicy policy = DEFAULT_VIEWPORT_POLICY,
1816 std::type_identity_t<ManagedViewHandler<T>> prepared = {});
1817
1829 template <class T>
1830 std::expected<void, ManagedError>
1831 setModel(Node<VirtualList<T>> node, ManagedModel<T> model,
1832 std::type_identity_t<std::optional<ManagedViewHandler<T>>> prepared = std::nullopt,
1833 ModelRebindOptions options = {});
1834
1843 template <class T>
1844 std::expected<void, ManagedError>
1845 setModel(Node<VirtualTable<T>> node, ManagedModel<T> model,
1846 std::type_identity_t<std::optional<ManagedViewHandler<T>>> prepared = std::nullopt,
1847 ModelRebindOptions options = {});
1848
1855 template <class T>
1856 std::expected<std::optional<PositionResolution>, ManagedError> restoreStatus(Node<VirtualList<T>> node) const;
1860 template <class T>
1861 std::expected<std::optional<PositionResolution>, ManagedError> restoreStatus(Node<VirtualTable<T>> node) const;
1862
1875 template <class T>
1876 std::expected<Node<Chart<T>>, ManagedError>
1877 chart(Node<Widget> parent, ManagedModel<T> model, std::type_identity_t<ManagedChartAccessor<T>> accessor,
1878 ChartOptions options = {}, ManagedChartOrigin first = {},
1879 std::type_identity_t<ManagedViewHandler<T>> prepared = {}, SizePolicy policy = DEFAULT_VIEWPORT_POLICY);
1880
1882
1889 std::expected<Node<Spinner>, ManagedError> spinner(Node<Widget> parent, SpinnerOptions options = {},
1890 ControlStyle style = {},
1891 SizePolicy policy = DEFAULT_CONTENT_POLICY,
1892 SpinnerLabelResolver resolver = {});
1893
1894 bool usesPreparedLayout() const noexcept override;
1896 bool usesGeometrySnapshot() const noexcept override;
1900 bool requiresPointerMotion() const noexcept override;
1901
1907 std::expected<NodeGeometry, ManagedError> geometry(Node<Widget> node) const;
1908
1915 template <class T>
1917
1926 template <class Callback>
1927 requires detail::ManagedAction<Callback, NodeGeometry>
1928 std::expected<void, ManagedError> onLayout(Node<Widget> node, Callback callback,
1929 std::source_location origin = std::source_location::current()) {
1930 auto allowed = boundary(ManagedPhase::BIND, node);
1931 if (!allowed) {
1932 return allowed;
1933 }
1934 try {
1935 return registerLayout(node, actionAdapter<NodeGeometry>(std::move(callback), origin), origin);
1936 } catch (const std::bad_alloc &) {
1937 return std::unexpected(error(ManagedPhase::BIND, node, TreeError::NO_MEMORY));
1938 } catch (...) {
1939 return std::unexpected(error(ManagedPhase::BIND, node, TreeError::CALLBACK_FAILED));
1940 }
1941 }
1942
1946 std::expected<void, TreeError> completedLayout(Application &app) override;
1950 std::expected<void, TreeError> afterDispatch(Application &app) override;
1952 bool hasPendingLayout() const noexcept override;
1953
1959 std::expected<void, TreeError> prepareViews(Application &app, const LayoutSnapshot &snapshot) override;
1960
1962 bool requiresBackgroundExecutor() const noexcept override {
1963 return asyncEnabled_;
1964 }
1965
1969 std::expected<ApplicationStats, ManagedError> run(std::stop_token stop = {});
1970
1975 std::expected<ApplicationStats, ManagedError> run(ApplicationTerminal &terminal, std::stop_token stop = {});
1976
1981 std::expected<void, ManagedError> start(ApplicationReadyTerminal &terminal, std::stop_token stop = {});
1982
1986 std::expected<ApplicationStep, ManagedError> step();
1987
1994 std::expected<void, ManagedError> close();
1995
2000 std::expected<void, TreeError> prepare(Application &app, CellSize size) override;
2001
2006 std::expected<bool, TreeError> input(Application &app, const InputEvent &event) override;
2007
2009 void stop(Application &app) override;
2010
2011private:
2012 template <std::equality_comparable T, class Value>
2013 std::expected<ManagedState<T>, ManagedError> stateFrom(Value &&initial, Invalidation kind, PropertyOptions options) {
2014 auto allowed = boundary(ManagedPhase::STATE, root_);
2015
2016 if (!allowed) {
2017 return std::unexpected(allowed.error());
2018 }
2019
2020 if (kind != Invalidation::PAINT && kind != Invalidation::LAYOUT) {
2021 return std::unexpected(error(ManagedPhase::STATE, root_, TreeError::INVALID_ARGUMENT));
2022 }
2023
2024 if (!liveText_.empty() || !originProperties_.empty()) {
2025 pruneLiveText();
2026 }
2027 if (properties_.size() >= options_.maxStates) {
2028 return std::unexpected(error(ManagedPhase::STATE, root_, TreeError::NODE_LIMIT));
2029 }
2030
2031 auto created = Property<T>::create(app_.tree(), rowOrigin_ ? rowOrigin_->node : root_, std::forward<Value>(initial),
2032 kind, options);
2033
2034 if (!created) {
2035 return std::unexpected(error(ManagedPhase::STATE, root_, created.error()));
2036 }
2037
2038 try {
2039 std::shared_ptr<Property<T>> model(std::move(*created));
2040 ManagedState<T> handle;
2041
2042 handle.model_ = model;
2043 handle.facade_ = facade_;
2044 handle.lifetime_ = lifetime_;
2045 handle.owner_ = owner_;
2046 handle.scene_ = root_.id();
2047 handle.origin_ = rowOrigin_;
2048 ownRowProperty(model);
2049 properties_.push_back(std::move(model));
2050
2051 return handle;
2052 } catch (const std::bad_alloc &) {
2053 return std::unexpected(error(ManagedPhase::STATE, root_, TreeError::NO_MEMORY));
2054 }
2055 }
2056
2057 struct OriginProperty {
2058 std::shared_ptr<detail::ManagedOrigin> origin;
2059 std::weak_ptr<void> property;
2060 Node<Widget> receiver;
2061 };
2062
2063 void ownRowProperty(const std::shared_ptr<void> &property) {
2064 if (rowOrigin_) {
2065 originProperties_.push_back({rowOrigin_, property, rowOrigin_->node});
2066 }
2067 }
2068
2069 struct LiveTextRecord {
2070 std::shared_ptr<detail::ManagedOrigin> origin;
2071 int kind{};
2072 PropertyOptions options;
2073 bool publicUse{};
2074 std::shared_ptr<Property<GraphemeText>> property;
2075 std::function<std::expected<std::optional<GraphemeText>, ManagedError>(const GraphemeText *)> capture;
2076 std::function<std::expected<std::optional<GraphemeText>, ManagedError>()> validateModel;
2077 const char *operation{};
2078 std::source_location registered;
2079 };
2080
2081 std::expected<ManagedSource<GraphemeText>, ManagedError> attachLiveText(const ui::TextSource &source,
2082 PropertyOptions options,
2083 std::source_location registered,
2084 bool publicUse);
2085 std::expected<bool, TreeError> captureLiveText();
2086 void pruneLiveText() noexcept;
2087
2088 struct ObserverRecord {
2089 ManagedScene *scene{};
2090 Node<Widget> node;
2091 std::shared_ptr<detail::ManagedOrigin> inputOrigin;
2092 std::weak_ptr<detail::ManagedOrigin> recoveryOrigin;
2093 Subscription subscription;
2094 std::function<std::expected<std::uint64_t, TreeError>()> revision;
2095 std::function<std::expected<std::uint64_t, TreeError>(const std::shared_ptr<ObserverRecord> &)> deliver;
2096 std::shared_ptr<std::optional<TextError>> textFailure;
2097 std::optional<std::uint64_t> successful;
2098 std::optional<ManagedError> shortFailure;
2099 const void *shortAttempt{};
2100 bool promotesFailure{};
2101 bool runtime{true};
2102 const char *operation{};
2103 std::source_location origin{};
2104 bool initialPending{true};
2105 bool failed{};
2106 bool running{};
2107 bool retired{};
2108
2109 static void collectShortFailure(void *owner, ui::detail::SetupFailureEvent event, ManagedError *failure,
2110 const void *attempt) noexcept {
2111 auto &record = *static_cast<ObserverRecord *>(owner);
2112 if (event == ui::detail::SetupFailureEvent::LATCH && !record.shortFailure && failure) {
2113 record.shortFailure = *failure;
2114 record.shortAttempt = attempt;
2115 auto &scene = *record.scene;
2116 if (record.runtime && !scene.failure_ && scene.shortReported(*failure)) {
2117 // LATCH precedes recordError without intervening user code. Reserve that exact diagnostic receipt;
2118 // clearErrors already revokes it if user code explicitly clears history after the short operation.
2119 scene.failure_ = *failure;
2120 scene.failureDiagnostic_ =
2121 scene.errorCount_ < scene.errors_.size() ? std::optional<std::size_t>(scene.errorCount_) : std::nullopt;
2122 record.promotesFailure = true;
2123 }
2124 }
2125 if (event == ui::detail::SetupFailureEvent::NOTIFY && attempt == record.shortAttempt && record.promotesFailure) {
2126 record.scene->failureNotified_ = true;
2127 }
2128 if (event == ui::detail::SetupFailureEvent::END_ATTEMPT && attempt == record.shortAttempt) {
2129 record.shortAttempt = nullptr;
2130 }
2131 }
2132 };
2133
2134 std::expected<void, ManagedError> observerAdmission(Node<Widget> node);
2135 template <class T, class Callback>
2136 void prepareObserverRecord(const std::shared_ptr<ObserverRecord> &record, const std::shared_ptr<Property<T>> &source,
2137 Callback &&callback);
2138 template <class W, class T>
2139 std::expected<Subscription, TreeError> connectObserverRecord(Node<W> receiver,
2140 const std::shared_ptr<Property<T>> &source,
2141 const std::shared_ptr<ObserverRecord> &record);
2142 std::expected<void, TreeError> invokeObserver(const std::shared_ptr<ObserverRecord> &record, ManagedPhase phase);
2143 std::expected<void, TreeError> recoverObservers(std::size_t maxPasses = 0, bool *invoked = nullptr,
2144 bool *pending = nullptr, bool deferFailedLive = false);
2145 std::expected<bool, TreeError> observerLive(const std::shared_ptr<ObserverRecord> &record);
2146 void pruneObservers() noexcept;
2147
2148 bool observerMountPending() const noexcept {
2149 return coldMountPending_ || (mountDepth_ && (!observers_.empty() || !dataStates_.empty())) ||
2150 dataStateMountPending();
2151 }
2152
2153 template <class Value, class Callback>
2154 std::expected<void, ManagedError> onShortcutActions(Value &&shortcut, Callback &action,
2155 detail::ShortcutActions actions, ShortcutOptions options,
2156 std::source_location origin) {
2157 auto allowed = keyBoundary();
2158
2159 if (!allowed) {
2160 return allowed;
2161 }
2162
2163 const auto valid = validateShortcut(shortcut, options);
2164
2165 if (!valid) {
2166 auto failure = error(ManagedPhase::BIND, root_, TreeError::INVALID_ARGUMENT);
2167
2168 failure.shortcut = valid.error();
2169
2170 return std::unexpected(std::move(failure));
2171 }
2172
2173 if (keyHandlers_ >= options_.maxKeyHandlers) {
2174 return std::unexpected(error(ManagedPhase::BIND, root_, TreeError::NODE_LIMIT));
2175 }
2176
2177 try {
2178 auto reusable = prepareReusableAction(action);
2179 if (!reusable) {
2180 return reusable;
2181 }
2182
2183 // Avoid both caller-side transfers and noexcept debug-vector moves before the checked boundary.
2184 Shortcut owned(std::forward<Value>(shortcut));
2185 auto adapter = actionAdapter<KeyEvent>(std::move(action), origin);
2186
2187 if (!adapter) {
2188 return std::unexpected(error(ManagedPhase::BIND, root_, TreeError::INVALID_ARGUMENT));
2189 }
2190
2191 return registerShortcut(std::move(owned), std::move(adapter), actions, origin);
2192 } catch (const std::bad_alloc &) {
2193 return std::unexpected(error(ManagedPhase::BIND, root_, TreeError::NO_MEMORY));
2194 } catch (...) {
2195 return std::unexpected(error(ManagedPhase::BIND, root_, TreeError::CALLBACK_FAILED));
2196 }
2197 }
2198
2199 struct KeyRecord;
2200 struct KeySnapshot;
2201
2202 struct KeyTransaction {
2203 bool &active;
2204 std::shared_ptr<KeySnapshot> previous;
2205 std::shared_ptr<std::function<std::expected<bool, ManagedError>(const InputEvent &)>> input;
2206 std::uint64_t revision, focus, tree;
2207 Node<Widget> owner;
2208
2209 explicit KeyTransaction(ManagedScene &scene)
2210 : active(scene.keyStaging_), previous(scene.keys_), input(scene.input_), revision(scene.keyRevision_),
2211 focus(scene.app_.router().focusGeneration()), tree(scene.app_.tree().inputGeneration()) {
2212 active = true;
2213 }
2214
2215 ~KeyTransaction() {
2216 active = false;
2217 }
2218
2219 void release() noexcept {
2220 active = false;
2221 }
2222 };
2223 enum class KeyChange {
2224 ENABLED,
2225 VISIBLE,
2226 TEXT,
2227 REBIND,
2228 UNBIND,
2229 REMOVE
2230 };
2231 struct KeyPending;
2232
2233 std::expected<void, ManagedError> registerLegacyKey(KeyEvent chord,
2234 std::function<EditorCommandResult(const KeyEvent &)> action);
2235 std::expected<void, ManagedError> registerShortcut(Shortcut &&shortcut,
2236 std::function<EditorCommandResult(const KeyEvent &)> action,
2237 detail::ShortcutActions actions, std::source_location origin);
2238 std::expected<void, ManagedError> publishKey(std::shared_ptr<KeyRecord> record);
2239 std::expected<bool, ManagedError> dispatchKeys(const std::shared_ptr<KeySnapshot> &snapshot, const InputEvent &event);
2240 std::expected<bool, ManagedError> invokeKey(const std::shared_ptr<KeyRecord> &record, const KeyEvent &event);
2241 std::expected<bool, ManagedError> waitForKey(const std::shared_ptr<KeySnapshot> &snapshot,
2242 const std::shared_ptr<KeyRecord> &winner, std::size_t depth);
2243 static void resetKeys(KeyPending &pending) noexcept;
2244 std::expected<KeyBinding, ManagedError>
2245 registerAnnotatedKey(const KeySelection &selection, KeyInfo info,
2246 std::function<EditorCommandResult(const KeyEvent &)> action, std::source_location origin,
2247 KeyTransaction &transaction);
2248 std::expected<void, ManagedError> keyBoundary() const;
2249 std::expected<void, ManagedError> keyPreflight(KeyInfo &info);
2250 std::expected<void, ManagedError> changeKey(KeyBindingId id, KeyChange change, bool value = false,
2251 const KeySelection *selection = nullptr, const KeyInfo *text = nullptr);
2252 std::expected<void, ManagedError> observeKeyScopes();
2253 std::expected<std::shared_ptr<const KeyBindingsSnapshot>, ManagedError> readKeyProjection(bool recover);
2254 std::expected<void, TreeError> prepareKeyHelp(const std::shared_ptr<detail::KeyHelpRecord> &record,
2255 const LayoutSnapshot &snapshot);
2256 std::expected<void, ManagedError>
2257 checkKeyProjectionBudget(const detail::KeyHelpRecord *replacement,
2258 const std::shared_ptr<const KeyBindingsSnapshot> &projection, std::size_t projectionBytes,
2259 std::size_t textBytes);
2260 std::expected<void, ManagedError> changeHelp(Node<Widget> node, bool opening);
2261 std::uint64_t helpActivation(Node<Widget> node) const noexcept;
2262 std::weak_ptr<detail::ActionCancellation> helpScope(Node<Widget> node) const noexcept;
2263 std::expected<GraphemeText, ManagedError> keyText(const TextValue &value, const KeyTextResolver &resolver,
2264 std::size_t limit, bool label);
2265 KeyEligibility keyEligibility(const KeyRecord &record, Node<Widget> focus) const;
2266 std::expected<void, ManagedError> publishKeyCandidate(std::shared_ptr<KeySnapshot> snapshot, bool preserve,
2267 KeyTransaction &transaction, KeyBinding *result = nullptr,
2268 const std::shared_ptr<detail::KeyBindingSlot> &slot = {});
2269 friend class KeyBinding;
2270
2271 friend struct style::ct::detail::Access;
2272 friend struct ui::detail::Access;
2273 friend struct ui::detail::RowAccess;
2274 friend struct ui::detail::RefAccess;
2275 friend struct ui::detail::SceneAccess;
2276 friend struct ui::detail::ClickAccess;
2277 friend struct ui::detail::EditorEventAccess;
2278 friend struct ui::detail::ChangeAccess;
2279 friend struct ui::detail::NamedAccess;
2280 friend struct ui::detail::LayoutAccess;
2281 friend struct ui::detail::MessageAccess;
2282 friend struct ui::detail::NotificationAccess;
2283 friend class ui::NotificationCenter;
2284 friend struct ui::detail::KeyHelpAccess;
2285 friend struct ui::detail::ThemeSelectionAccess;
2286 friend struct ui::detail::ThemeSelectorAccess;
2287 friend struct ui::detail::ActionAccess;
2288 friend struct ui::detail::AsyncAccess;
2289 friend struct detail::ManagedScrollTestAccess;
2290 friend class ManagedNavigation;
2291
2292 struct Entry;
2293 std::shared_ptr<detail::MessageRecord> findMessage(Node<Widget> node) const;
2294 std::expected<void, TreeError> chooseMessage(const std::shared_ptr<detail::MessageRecord> &record,
2295 MessageChoice choice);
2296 bool messageOwner(Node<Widget> owner) const;
2297 bool messageWithin(Node<Widget> root, Node<Widget> node) const;
2298 std::expected<Node<Widget>, TreeError> messageParent(Node<Widget> node) const;
2299 std::expected<void, TreeError> prepareMessages();
2300 void retireMessages() noexcept;
2301 void completeMessage(const std::shared_ptr<detail::MessageRecord> &record,
2302 const std::expected<void, ManagedError> &result, bool opening, bool committed);
2303 void deliverMessage(const std::shared_ptr<detail::MessageRequest> &request);
2304 std::shared_ptr<detail::DialogRecord> findDialog(Node<Widget> node) const;
2305 std::expected<std::shared_ptr<detail::NotificationRecord>, ManagedError>
2306 makeNotifications(Node<Widget> wrapper, Node<Widget> body, const NotificationOptions &options,
2307 std::vector<Node<Widget>> &created);
2308 std::expected<void, ManagedError> finalizeNotifications(const std::shared_ptr<detail::NotificationRecord> &record);
2309 std::expected<ToastPostReceipt, ManagedError> postToast(const std::shared_ptr<detail::NotificationRecord> &record,
2310 const ui::ToastMessage &message);
2311 std::expected<void, ManagedError> toastCommand(const std::shared_ptr<detail::NotificationRecord> &record,
2312 detail::ToastCommand command, std::optional<ToastId> id, bool flag);
2313 std::expected<std::shared_ptr<const NotificationSnapshot>, ManagedError>
2314 notificationSnapshot(const std::shared_ptr<detail::NotificationRecord> &record) const;
2315 std::expected<void, ManagedError> stageNotifications(const std::shared_ptr<detail::NotificationRecord> &record,
2316 detail::ToastCandidate &candidate, ManagedPhase phase,
2317 bool firstPresentation = false);
2318 std::expected<void, ManagedError> commitNotifications(const std::shared_ptr<detail::NotificationRecord> &record,
2319 detail::ToastCandidate &candidate, ManagedPhase phase);
2320 std::expected<void, ManagedError> activateToast(const std::shared_ptr<detail::NotificationRecord> &record,
2321 ToastId id);
2322 std::expected<void, TreeError> prepareNotifications(bool firstPresentation = false);
2323 bool notificationEligible(const std::shared_ptr<detail::NotificationRecord> &record, bool geometry) const;
2324 void notificationTimer(const std::weak_ptr<detail::NotificationRecord> &record,
2325 const std::shared_ptr<detail::ToastTimerMarker> &marker);
2326 void retireNotifications() noexcept;
2327 std::array<CellStyle, 5> notificationStyles(const std::shared_ptr<detail::NotificationRecord> &record,
2328 const detail::ToastPayload &payload, NodeId node,
2329 bool alert) const noexcept;
2330 Invalidation invalidateNotificationStyles() noexcept;
2331 std::expected<void, TreeError> changeDialog(Node<Widget> node, bool open, DialogDismissReason reason);
2332 std::expected<void, ManagedError> dialogCommand(Node<Widget> node, bool opening, DialogDismissReason reason);
2333 std::expected<void, TreeError> prepareDialogs();
2334 bool modalDialogInput();
2335 void retireDialogs() noexcept;
2336 std::expected<Node<Widget>, ManagedError> makeDialogPanel(Node<Dialog> node, BorderOptions options);
2337 std::expected<Node<Column>, ManagedError> makeDialogContent(Node<Widget> parent, LinearOptions options);
2338 std::expected<void, ManagedError> installDialogClose(const std::shared_ptr<detail::DialogRecord> &record);
2339 std::expected<void, ManagedError>
2340 setDialogDismiss(Node<Dialog> node, std::function<std::expected<void, TreeError>(DialogDismissReason)> callback);
2341
2342 struct LayoutValue {
2343 NodeGeometry geometry;
2344 std::uint64_t revision{};
2345 };
2346
2347 struct LayoutRecord {
2348 Node<Widget> node;
2349 std::function<EditorCommandResult(const NodeGeometry &)> action;
2350 std::source_location origin;
2351 SchedulerConnection<LayoutValue> connection;
2352 std::shared_ptr<const LayoutValue> pending;
2353 std::optional<NodeGeometry> delivered;
2354 std::uint64_t visibilityRevision{};
2355 bool queued{};
2356 std::size_t rejected{};
2357 bool retired{};
2358 };
2359
2360 std::expected<void, ManagedError> registerLayout(Node<Widget> node,
2361 std::function<EditorCommandResult(const NodeGeometry &)> action,
2362 std::source_location origin);
2363 void retireLayouts(Entry &entry) noexcept;
2364 void deliverLayout(const std::shared_ptr<LayoutRecord> &record, std::shared_ptr<const LayoutValue> value);
2365 std::expected<void, TreeError> publishLayout(const std::shared_ptr<LayoutRecord> &record);
2366
2367 struct ClickRecord {
2368 std::function<EditorCommandResult(ui::ClickParams &)> action;
2369 std::source_location origin;
2370 };
2371
2372 struct ClickChain {
2373 // MSVC Debug's noexcept default constructor allocates a proxy; the count constructor is checked.
2374 std::vector<std::shared_ptr<ClickRecord>> records = std::vector<std::shared_ptr<ClickRecord>>(0);
2375 bool retired{};
2376 };
2377
2378 struct EditorEventRecord {
2379 std::variant<std::function<EditorCommandResult(const TextEditedEvent &)>,
2380 std::function<EditorCommandResult(const EditingFinishedEvent &)>>
2381 action;
2382 std::source_location origin;
2383 };
2384
2385 struct EditorEventChain {
2386 std::vector<std::shared_ptr<EditorEventRecord>> records = std::vector<std::shared_ptr<EditorEventRecord>>(0);
2387 bool retired{};
2388 };
2389
2390 struct ChangeRecord {
2391 std::variant<std::function<EditorCommandResult(const PropertyUpdate<bool> &)>,
2392 std::function<EditorCommandResult(const PropertyUpdate<CheckState> &)>,
2393 std::function<EditorCommandResult(const PropertyUpdate<RadioGroupValue> &)>>
2394 action;
2395 std::source_location origin;
2396 };
2397
2398 struct ChangeChain {
2399 std::vector<std::shared_ptr<ChangeRecord>> records = std::vector<std::shared_ptr<ChangeRecord>>(0);
2400 bool boolean{};
2401 bool radio{};
2402 bool retired{};
2403 };
2404
2405 std::expected<bool, ManagedError> changeModel(Node<CheckBox> node);
2406 std::expected<std::shared_ptr<detail::ManagedSliderRecord>, ManagedError> sliderRecord(Node<Slider>, ManagedPhase);
2407 std::expected<std::shared_ptr<detail::ManagedSpinBoxRecord>, ManagedError> spinBoxRecord(Node<SpinBox>, ManagedPhase);
2408 std::expected<double, ManagedError> spinBoxValue(Node<SpinBox>);
2409 std::expected<SpinBoxResult, ManagedError> setSpinBoxValue(Node<SpinBox>, double);
2410 std::expected<Node<LineEdit>, ManagedError> spinBoxEditor(Node<SpinBox>);
2411 std::expected<void, ManagedError>
2412 registerNumericChange(Node<SpinBox>, std::function<EditorCommandResult(const PropertyUpdate<NumericValue> &)>,
2413 std::source_location);
2414 std::expected<double, ManagedError> sliderValue(Node<Slider> node);
2415 std::expected<PropertyUpdate<NumericValue>, ManagedError> setSliderValue(Node<Slider> node, double value);
2416 std::expected<void, ManagedError>
2417 registerNumericChange(Node<Slider>, std::function<EditorCommandResult(const PropertyUpdate<NumericValue> &)>,
2418 std::source_location);
2419 std::expected<void, ManagedError>
2420 registerNumericFinished(Node<Slider>, std::function<EditorCommandResult(const SliderOperationEvent &)>,
2421 std::source_location);
2422 void retireNumeric(Entry &entry) noexcept;
2423 template <class Event>
2424 void dispatchNumeric(Node<Slider>, const std::shared_ptr<detail::ManagedSliderRecord> &,
2425 const std::weak_ptr<const void> &, const Event &, std::size_t count);
2426 std::expected<void, ManagedError> registerChange(Node<Widget> node, ChangeRecord record);
2427 void retireChanges(Entry &entry) noexcept;
2428 template <class T>
2429 std::function<void(std::expected<PropertyUpdate<T>, TreeError>)>
2430 checkboxCallback(Node<Widget> node, std::shared_ptr<ChangeChain> chain,
2431 std::function<std::expected<void, TreeError>(std::expected<PropertyUpdate<T>, TreeError>)> changed);
2432 template <class T>
2433 void dispatchChange(Node<Widget> node, const std::shared_ptr<ChangeChain> &chain,
2434 const std::weak_ptr<const void> &lifetime, const PropertyUpdate<T> &receipt, std::size_t count);
2435
2436 std::expected<void, ManagedError> registerEditing(Node<LineEdit> node, EditorEventRecord record);
2437 void retireEditing(Entry &entry) noexcept;
2438 template <class Event>
2439 void dispatchEditing(Node<LineEdit> node, const std::shared_ptr<EditorEventChain> &chain,
2440 const std::weak_ptr<const void> &lifetime, const Event &event);
2441
2442 bool spinnerEligible(Node<Spinner> node) const;
2443 std::expected<void, TreeError> prepareSpinners();
2444 void stopSpinners() noexcept;
2445 std::expected<void, TreeError> armSpinner(const std::shared_ptr<detail::SpinnerState> &record);
2446 void tickSpinner(const std::shared_ptr<detail::SpinnerState> &record, std::uint64_t generation);
2447 std::vector<std::weak_ptr<detail::SpinnerState>> spinners_ = std::vector<std::weak_ptr<detail::SpinnerState>>(0);
2448
2449 struct CaptionBinding {
2450 std::variant<Node<Control>, Node<Border>> node;
2451 ManagedState<std::string> model;
2452 std::optional<std::uint64_t> revision;
2453 std::shared_ptr<ui::detail::ValueCaptionBinding> source;
2454 };
2455
2456 std::expected<Node<DataStateView>, ManagedError> beginDataState(Node<Widget> parent, DataPresentation initial,
2457 DataStateConfig config, bool automatic = false);
2458 template <class Source>
2459 std::expected<Node<DataStateView>, ManagedError> beginBoundDataState(Node<Widget> parent, Source source,
2460 DataStateConfig config);
2461 template <class Content>
2462 std::expected<void, ManagedError> finishDataState(Node<Widget> root, Node<Content> body, bool automatic);
2463 std::expected<void, TreeError> applyDataState(const std::shared_ptr<detail::DataStateRecord> &record,
2464 DataPresentation value);
2465 std::expected<void, TreeError> prepareDataStates(const LayoutSnapshot &layout);
2466 std::expected<void, TreeError> animateDataState(const std::shared_ptr<detail::DataStateRecord> &record);
2467 std::expected<bool, TreeError> reserveDataTimer(const std::shared_ptr<detail::DataStateRecord> &record,
2468 DataPhase phase, Subscription &reserved);
2469 void tickDataState(const std::shared_ptr<detail::DataStateRecord> &record, std::uint64_t generation);
2470 void pruneDataStates() noexcept;
2471 bool dataStateMountPending() const noexcept;
2472 std::expected<Node<Widget>, TreeError> repairDataFocus();
2473 std::vector<std::shared_ptr<detail::DataStateRecord>> dataStates_ =
2474 std::vector<std::shared_ptr<detail::DataStateRecord>>(0);
2475 std::shared_ptr<detail::DataStateOwner> dataStateOwner_;
2476
2477 struct PasswordFeedback {
2478 bool active{};
2479 std::optional<ManagedError> reported;
2480 };
2481
2482 struct DeliveryRegistration {
2483 Subscription subscription;
2484 std::weak_ptr<const void> liveness;
2485 };
2486
2487 struct Entry {
2488 Node<Widget> companion;
2489 Node<Widget> node;
2490 std::shared_ptr<StyleTarget> target;
2491 std::variant<std::monostate, ActionBinding, CheckBoxBinding, CheckStateBinding, RadioGroupBinding, LineEditBinding,
2492 PasswordBinding, SliderBinding, SpinBoxBinding, std::shared_ptr<LineEditBinding>>
2493 binding;
2494
2495 LineEditBinding *editorBinding() {
2496 if (auto *direct = std::get_if<LineEditBinding>(&binding)) {
2497 return direct;
2498 }
2499 auto *shared = std::get_if<std::shared_ptr<LineEditBinding>>(&binding);
2500 return shared ? shared->get() : nullptr;
2501 }
2502
2503 std::shared_ptr<PasswordFeedback> passwordFeedback;
2504 std::unique_ptr<CaptionBinding> caption;
2505 std::unique_ptr<ManagedState<std::string>> textModel;
2506 ActionBinding focusScope;
2507 std::function<std::expected<void, TreeError>(Node<Widget>)> sync;
2508 std::function<std::expected<void, TreeError>(Node<Widget>)> customSync;
2509 std::function<std::expected<void, TreeError>(const LayoutSnapshot &)> viewPrepare;
2510 std::shared_ptr<detail::KeyHelpRecord> keyHelp;
2511 std::weak_ptr<detail::ManagedModelSource> viewSource;
2512 bool stylePending{};
2513 bool removed{};
2514 std::shared_ptr<ClickChain> clicks;
2515 std::shared_ptr<EditorEventChain> editing;
2516 std::shared_ptr<ChangeChain> changes;
2517 std::vector<DeliveryRegistration> deliveries = std::vector<DeliveryRegistration>(0);
2518 std::shared_ptr<detail::ScrollIntentRecord> scrollIntent;
2519 std::shared_ptr<detail::ManagedScrollState> scrollOwner;
2520 std::shared_ptr<ScrollController> scrollController;
2521 Node<Widget> scrollArea;
2522 bool regionalLayoutOwner{};
2523 };
2524
2525 template <class T, class... Args>
2526 requires std::derived_from<T, Widget>
2527 std::expected<Node<T>, ManagedError> emplaceConfigured(Node<Widget> parent, std::optional<bool> scrollWriter,
2528 Args &&...args);
2529 std::expected<void, TreeError> attachScroll(const std::shared_ptr<Entry> &entry, Node<ScrollArea> node, bool writer);
2530 std::expected<void, TreeError> attachScroll(const std::shared_ptr<Entry> &entry, Node<ScrollBar> node, bool writer);
2531 std::expected<void, TreeError> attachScroll(const std::shared_ptr<Entry> &entry, Node<Widget> node, bool writer);
2532 std::expected<void, TreeError> attachScrollValues(const std::shared_ptr<Entry> &entry);
2533 void publishScroll(const std::shared_ptr<Entry> &entry) noexcept;
2534 void pruneScroll() noexcept;
2535 std::expected<void, TreeError> sampleScrollFocus();
2536 std::expected<void, TreeError> queueScrollReveal(Node<Widget> node, Node<Widget> root, bool explicitRequest);
2537 bool scrollIntentIntersects(const Entry &entry, std::span<const Node<Widget>> chain) const noexcept;
2538 std::expected<bool, TreeError> prepareRegionalInput(const LayoutSnapshot &snapshot);
2539 std::expected<void, TreeError> syncRegionalPresentation(Node<Widget> focused);
2540 std::expected<bool, TreeError> prepareLogViews(const LayoutSnapshot &snapshot);
2541 std::expected<void, TreeError> prepareScrollFrame(const LayoutSnapshot &snapshot);
2542 void completeScrollFrame() noexcept;
2543
2544 std::expected<void, ManagedError> syncCaption(Node<Widget> node, CaptionBinding &binding, ManagedPhase phase);
2545
2546 template <class T>
2547 std::expected<std::shared_ptr<detail::ManagedModelSourceOf<T>>, ManagedError> modelSource(ManagedModel<T> model,
2548 Node<Widget> parent);
2549
2550 template <class T, class Collection, class MakeRows>
2551 std::expected<ManagedModel<T>, ManagedError> collectionModel(ManagedState<Collection> input,
2552 CollectionModelOptions options, MakeRows makeRows);
2553
2554 template <class T>
2555 std::expected<void, ManagedError> applyOwnedSnapshot(ManagedModel<T> model,
2556 std::shared_ptr<const ModelSnapshot<T>> snapshot) {
2557 auto source = modelSource(model, root_);
2558 if (!source) {
2559 return std::unexpected(source.error());
2560 }
2561 auto applied = Model<T>::applySnapshot(*(*source)->model->state_, std::move(snapshot));
2562 return applied ? std::expected<void, ManagedError>{}
2563 : std::unexpected(error(ManagedPhase::STATE, root_, applied.error()));
2564 }
2565
2567 template <class T, class W> struct ViewPreparation;
2568 template <class T, class W> struct PreparedViewModelChange;
2570
2571 template <class T>
2572 std::expected<ManagedNavigation, ManagedError> makeModelNavigation(ManagedModel<T> model, ModelResource resource,
2573 SourceStamp session, NavigationOptions options,
2574 bool explicitDomain);
2575
2576 template <class T, class W>
2577 std::expected<Node<W>, ManagedError> attachView(Node<W> node, std::shared_ptr<detail::ManagedModelSourceOf<T>> source,
2578 ManagedViewHandler<T> handler, ManagedChartOrigin first = {});
2579
2580 template <class T, class W>
2581 std::expected<void, ManagedError> replaceViewModel(Node<W> node, ManagedModel<T> model,
2582 std::optional<ManagedViewHandler<T>> prepared,
2583 ModelRebindOptions options = {});
2584
2585 template <class T, class W>
2586 std::expected<detail::ModelViewCheckpoint, TreeError>
2587 captureViewCheckpoint(Node<W> node, const std::shared_ptr<detail::ManagedModelSourceOf<T>> &source,
2588 BookmarkOptions options);
2589
2590 template <class T>
2591 std::expected<detail::ModelViewCheckpoint, TreeError> resolveViewCheckpoint(
2592 detail::ModelViewCheckpoint value, const std::shared_ptr<detail::ManagedModelSourceOf<T>> &source,
2593 const std::shared_ptr<detail::ModelViewHistory> &history, BookmarkOptions options, PositionResolution &resolution,
2594 PositionChangeMap changes = {}, const detail::ModelRestoreChannels *channels = nullptr);
2595
2596 template <class T>
2597 std::expected<void, TreeError> retryCanonicalRestore(const std::shared_ptr<detail::ManagedNavigationRecord> &record,
2598 const std::shared_ptr<detail::ManagedModelSourceOf<T>> &source);
2599
2600 template <class T>
2601 std::expected<void, TreeError>
2602 captureSelectedPositions(detail::ModelViewCheckpoint &value,
2603 const std::shared_ptr<detail::ManagedModelSourceOf<T>> &source,
2604 const std::shared_ptr<detail::ModelViewHistory> &history, BookmarkOptions options);
2605
2606 template <class T, class W>
2607 std::expected<std::unique_ptr<detail::PreparedModelViewChange>, ManagedError>
2608 prepareViewModelChange(Node<W> node, const std::shared_ptr<detail::ManagedModelSourceOf<T>> &source,
2609 std::optional<ManagedViewHandler<T>> prepared, ModelRebindOptions options,
2610 std::shared_ptr<detail::ModelViewHistory> history,
2611 const detail::ModelViewCheckpoint *sharedPosition = nullptr,
2612 const NavigationBindingOptions *sharing = nullptr);
2613
2614 template <class T>
2615 std::expected<void, ManagedError>
2616 replaceNavigationModel(const std::shared_ptr<detail::ManagedNavigationRecord> &record, ManagedModel<T> model,
2617 ModelRebindOptions options, Node<Widget> overrideNode = {},
2618 std::optional<ManagedViewHandler<T>> prepared = std::nullopt);
2619
2620 explicit ManagedScene(Application &app, ManagedOptions options);
2621
2622 std::weak_ptr<ui::detail::SceneAnchor> facadeContext() const noexcept {
2623 if (owner_ != std::this_thread::get_id() || closed_) {
2624 return {};
2625 }
2626
2627 return facade_;
2628 }
2629
2630 std::expected<void, ManagedError>
2631 setInput(std::function<std::expected<bool, ManagedError>(const InputEvent &)> callback, std::size_t keyHandlers,
2632 std::shared_ptr<KeySnapshot> keys = {});
2633
2634 std::expected<void, ManagedError>
2635 onButtonClick(Node<Button> node, std::function<EditorCommandResult(const ClickEvent &)> action, bool allowModified);
2636
2637 std::expected<void, ManagedError> composeButtonClick(Node<Button> node,
2638 std::function<EditorCommandResult(ui::ClickParams &)> action,
2639 std::source_location origin);
2640 void retireClicks(Entry &entry) noexcept;
2641 void dispatchClicks(Node<Button> node, const std::shared_ptr<ClickChain> &chain,
2642 const std::weak_ptr<const void> &lifetime, const ClickEvent &event);
2643
2644 struct ActionAdmission {
2645 ManagedScene &scene;
2646 std::weak_ptr<const void> lifetime;
2647 bool previous;
2648
2649 explicit ActionAdmission(ManagedScene &owner) noexcept
2650 : scene(owner), lifetime(owner.lifetime_), previous(owner.actionAdmitted_) {
2651 scene.actionAdmitted_ = true;
2652 }
2653
2654 ~ActionAdmission() {
2655 if (!lifetime.expired()) {
2656 scene.actionAdmitted_ = previous;
2657 }
2658 }
2659 };
2660
2661 std::expected<void, TreeError> actionBoundary() const noexcept {
2662 if (owner_ != std::this_thread::get_id()) {
2663 return std::unexpected(TreeError::WRONG_THREAD);
2664 }
2665 if (closed_) {
2666 return std::unexpected(TreeError::CLOSED);
2667 }
2668 auto root = app_.tree().root();
2669
2670 return root ? std::expected<void, TreeError>{} : std::unexpected(root.error());
2671 }
2672
2673 template <class Callback> std::expected<void, ManagedError> prepareReusableAction(const Callback &action) {
2674 if constexpr (std::same_as<Callback, ui::ActionRef>) {
2675 return ui::detail::attachAction(*this, action);
2676 }
2677
2678 return {};
2679 }
2680
2681 template <class Callback>
2682 std::function<EditorCommandResult(ui::ClickParams &)>
2683 clickAdapter(Callback action, std::source_location origin = std::source_location::current()) {
2684 ui::detail::SetupFailureScope mask({}, nullptr, nullptr);
2685 if constexpr (std::is_pointer_v<Callback> || requires { action.operator bool(); }) {
2686 if (!static_cast<bool>(action)) {
2687 return {};
2688 }
2689 }
2690
2691 if constexpr (requires(Callback &callback, ui::ClickParams &params) {
2692 { callback(params) } -> std::same_as<std::expected<void, ManagedError>>;
2693 } || (!std::invocable<Callback &, ui::ClickParams &> && requires(Callback &callback) {
2694 { callback() } -> std::same_as<std::expected<void, ManagedError>>;
2695 })) {
2696 return clickAdapter([this, lifetime = std::weak_ptr<const void>(lifetime_), action = std::move(action),
2697 origin]([[maybe_unused]] ui::ClickParams &params) mutable -> EditorCommandResult {
2698 auto result = [&] {
2699 if constexpr (std::invocable<Callback &, ui::ClickParams &>) {
2700 return action(params);
2701 } else {
2702 return action();
2703 }
2704 }();
2705 if (lifetime.expired()) {
2706 return EditorCommandResult(std::unexpected(TreeError::CLOSED), {}, false);
2707 }
2708 if (!result && !result.error().registrationOrigin) {
2709 result.error().registrationOrigin = origin;
2710 }
2711 return admitActionResult(std::move(result));
2712 });
2713 } else {
2714 return ui::detail::currentSceneCallback(
2715 facadeContext(),
2716 [this, lifetime = std::weak_ptr<const void>(lifetime_),
2717 action = std::move(action)]([[maybe_unused]] ui::ClickParams &params) mutable -> EditorCommandResult {
2718 if (lifetime.expired()) {
2719 return EditorCommandResult(std::unexpected(TreeError::CLOSED), {}, false);
2720 }
2721 auto admitted = actionBoundary();
2722 if (!admitted) {
2723 return EditorCommandResult(std::move(admitted), {}, false);
2724 }
2725 ActionAdmission admission(*this);
2726 const auto invoke = [&]() -> decltype(auto) {
2727 if constexpr (std::invocable<Callback &, ui::ClickParams &>) {
2728 return action(params);
2729 } else {
2730 return action();
2731 }
2732 };
2733
2734 if constexpr (std::same_as<decltype(invoke()), EditorCommandResult>) {
2735 return invoke();
2736
2737 } else {
2738 return EditorCommandResult(detail::invokeIgnoringValue(invoke), {}, false);
2739 }
2740 });
2741 }
2742 }
2743
2744 static bool commandReported(const EditorCommandResult &command, const std::weak_ptr<const void> &lifetime) {
2745 return command.reported_ && !lifetime.expired() && !command.collector_.expired() &&
2746 !lifetime.owner_before(command.collector_) && !command.collector_.owner_before(lifetime);
2747 }
2748
2749 template <class T, class Callback>
2750 std::function<EditorCommandResult(const PropertyUpdate<T> &)> changeAdapter(Callback action,
2751 std::source_location origin) {
2752 if constexpr (std::is_pointer_v<Callback> || requires { action.operator bool(); }) {
2753 if (!static_cast<bool>(action)) {
2754 return {};
2755 }
2756 }
2757
2758 if constexpr (detail::ChangeValueAction<Callback, T>) {
2759 return actionAdapter<PropertyUpdate<T>>(
2760 [action = std::move(action)](const PropertyUpdate<T> &receipt) mutable -> decltype(auto) {
2761 return action(receipt.snapshot->value);
2762 },
2763 origin);
2764 } else {
2765 return actionAdapter<PropertyUpdate<T>>(std::move(action), origin);
2766 }
2767 }
2768
2769 template <class Event, class Callback>
2770 std::function<EditorCommandResult(const Event &)>
2771 actionAdapter(Callback &&action, std::source_location origin = std::source_location::current()) {
2772 ui::detail::SetupFailureScope mask({}, nullptr, nullptr);
2773 const auto lifetime = std::weak_ptr<const void>(lifetime_);
2774 const auto context = facadeContext();
2775 using OwnedAction = std::decay_t<Callback>;
2776 OwnedAction owned(std::forward<Callback>(action));
2777
2778 if (lifetime.expired()) {
2779 return {};
2780 }
2781
2782 if constexpr (std::is_pointer_v<OwnedAction> || requires { owned.operator bool(); }) {
2783 const bool present = static_cast<bool>(owned);
2784
2785 if (lifetime.expired() || !present) {
2786 return {};
2787 }
2788 }
2789
2790 if constexpr (requires(OwnedAction &callback, const Event &event) {
2791 { callback(event) } -> std::same_as<std::expected<void, ManagedError>>;
2792 } || (!std::invocable<OwnedAction &, const Event &> && requires(OwnedAction &callback) {
2793 { callback() } -> std::same_as<std::expected<void, ManagedError>>;
2794 })) {
2795 auto converted = [this, lifetime, action = std::move(owned),
2796 origin]([[maybe_unused]] const Event &event) mutable -> EditorCommandResult {
2797 auto result = [&] {
2798 if constexpr (std::invocable<OwnedAction &, const Event &>) {
2799 return action(event);
2800 } else {
2801 return action();
2802 }
2803 }();
2804 if (lifetime.expired()) {
2805 return EditorCommandResult(std::unexpected(TreeError::CLOSED), {}, false);
2806 }
2807 if (!result && !result.error().registrationOrigin) {
2808 result.error().registrationOrigin = origin;
2809 }
2810 return admitActionResult(std::move(result));
2811 };
2812
2813 if (lifetime.expired()) {
2814 return {};
2815 }
2816
2817 return actionAdapter<Event>(std::move(converted), origin);
2818 } else {
2819 return ui::detail::currentSceneCallback(
2820 context,
2821 [this, lifetime,
2822 action = std::move(owned)]([[maybe_unused]] const Event &event) mutable -> EditorCommandResult {
2823 if (lifetime.expired()) {
2824 return EditorCommandResult(std::unexpected(TreeError::CLOSED), {}, false);
2825 }
2826 auto admitted = actionBoundary();
2827 if (!admitted) {
2828 return EditorCommandResult(std::move(admitted), {}, false);
2829 }
2830 ActionAdmission admission(*this);
2831 const auto invoke = [&]() -> decltype(auto) {
2832 if constexpr (std::invocable<OwnedAction &, const Event &>) {
2833 return action(event);
2834 } else {
2835 return action();
2836 }
2837 };
2838
2839 if constexpr (std::same_as<decltype(invoke()), EditorCommandResult>) {
2840 return invoke();
2841
2842 } else {
2843 return EditorCommandResult(detail::invokeIgnoringValue(invoke), {}, false);
2844 }
2845 });
2846 }
2847 }
2848
2849 EditorCommandResult admitActionResult(std::expected<void, ManagedError> result);
2850 static ManagedError error(ManagedPhase phase, Node<Widget> node, TreeError cause);
2851 std::expected<void, ManagedError> boundary(ManagedPhase phase, Node<Widget> node) const;
2852 std::shared_ptr<Entry> find(Node<Widget> node) const;
2853 std::expected<std::shared_ptr<Entry>, ManagedError> bindingEntry(Node<Widget> node);
2854 std::unexpected<ManagedError> rollback(Node<Widget> node, TreeError cause);
2855 std::expected<void, ManagedError> flushStyles();
2856 std::expected<void, ManagedError> pendingStyles(std::optional<std::vector<StyleRegistration>> &destination);
2857 void publishStyleMetadata() noexcept;
2858 std::expected<Invalidation, ManagedError>
2859 mutateStyles(StyleEngine::Mutation mutation, StyleLayerOptions options, StyleTier tier, std::string_view name,
2860 const StyleSheet *sheet, std::span<const StyleLayerUpdate> updates, StyleLayerHandle *added = nullptr,
2861 const detail::StyleThemeLease *lease = nullptr, const PssDocument *document = nullptr,
2862 std::optional<StyleLayerOptions> admissionOptions = std::nullopt,
2863 const StyleEngine::PreviewCapture *previewCapture = nullptr);
2864 std::expected<void, ManagedError> installThemeSelection(const ui::ThemeSelectionRef &reference,
2865 const std::vector<ui::ThemeChoice> &choices,
2866 const ui::ThemeSelectionOptions &options);
2867 std::expected<void, ManagedError> changeThemeSelection(const std::shared_ptr<detail::ThemeSelectionRecord> &record,
2868 detail::ThemeSelectionCommand command, std::string_view id,
2869 std::source_location origin,
2870 std::optional<std::string_view> expectedId = std::nullopt);
2871 std::expected<void, ManagedError> attachThemeSelector(const std::optional<ManagedError> *setupFailure = nullptr);
2872 std::expected<void, ManagedError> prepareThemeSelector();
2873 void retireThemeSelector() noexcept;
2874 std::expected<void, ManagedError> changeThemeSelector(const std::shared_ptr<detail::ThemeSelectorRecord> &record,
2875 detail::ThemeSelectorCommand command, std::size_t index,
2876 std::source_location origin);
2877 std::expected<std::shared_ptr<const ui::ThemeSelectionSnapshot>, ManagedError>
2878 readThemeSelection(const std::shared_ptr<detail::ThemeSelectionRecord> &record) const;
2879 std::expected<void, ManagedError> checkThemeLease(detail::StyleThemeLease lease) const;
2880 detail::StyleThemeLease captureThemeLease() const noexcept;
2881 std::expected<detail::StyleThemeLease, ManagedError> attachTheme(const StyleSheet &sheet,
2882 detail::StyleThemeLease lease);
2883 std::expected<void, ManagedError> applyLegacyTheme(const StyleSheet &sheet, detail::StyleThemeLease lease);
2884 std::expected<void, ManagedError> applyTheme(const StyleSheet &sheet, detail::StyleThemeLease lease);
2885 std::optional<std::size_t> recordError(ManagedError failure, std::span<const ManagedDiagnosticContext> contexts,
2886 std::source_location origin, bool *observerInvoked = nullptr,
2887 bool runFailure = false,
2888 const ui::detail::SetupFailureTicket *shortTicket = nullptr,
2889 bool contextUnavailable = false, bool dialogPrimary = false) noexcept;
2890 bool notifyError(ManagedDiagnostic &diagnostic, bool runFailure,
2891 const ui::detail::SetupFailureTicket *shortTicket = nullptr) noexcept;
2892 void reportShortError(ManagedError &failure, const char *operation, std::string_view name,
2893 std::string_view expectedType, std::source_location origin,
2894 bool admittedRuntime = false) noexcept;
2895
2896 bool shortReported(const ManagedError &failure) const noexcept {
2897 const auto &collector = failure.reportReceipt.collector_;
2898
2899 return !collector.expired() && !lifetime_.owner_before(collector) && !collector.owner_before(lifetime_);
2900 }
2901
2902 static bool focusReported(const ManagedError &failure) noexcept {
2903 const auto &collector = failure.reportReceipt.collector_;
2904 const std::weak_ptr<const void> empty;
2905
2906 // Focus propagation preserves a delivered receipt even after its source scene is destroyed.
2907 return collector.owner_before(empty) || empty.owner_before(collector);
2908 }
2909
2910 void remember(ManagedError failure, std::source_location origin = std::source_location::current(),
2911 std::span<const ManagedDiagnosticContext> contexts = {});
2912 std::expected<ApplicationStats, ManagedError> finish(std::expected<ApplicationStats, ApplicationError> result);
2913 void retainCloseFailure();
2914 std::expected<ApplicationStep, ManagedError> finishStep(std::expected<ApplicationStep, ApplicationError> result);
2915
2916 Application &app_;
2917 std::thread::id owner_;
2918 ManagedOptions options_;
2919 std::shared_ptr<const void> lifetime_;
2920 std::expected<void, ManagedError> admitActivity(std::shared_ptr<ui::detail::SceneActivity> activity);
2921 std::expected<void, TreeError> visitActivities(bool prepared, const LayoutSnapshot *layout = nullptr,
2922 bool completed = false);
2923 bool choiceWithin(Node<Widget> root, Node<Widget> node) const;
2924 std::weak_ptr<ui::detail::SceneActivity> choiceIntent_;
2925 std::uint64_t activityRevision_{};
2926
2927 std::vector<std::weak_ptr<ui::detail::SceneActivity>> asyncActivities_;
2928 bool servicingActivities_{};
2929 bool asyncEnabled_{};
2930 std::weak_ptr<ui::detail::SceneAnchor> facade_;
2931 Node<Widget> root_;
2932 StyleEngine styles_;
2933 std::shared_ptr<detail::ThemeSelectionRecord> themeSelection_;
2934 std::shared_ptr<detail::ThemeSelectorRecord> themeSelector_;
2935 std::shared_ptr<ui::detail::ActionRegistry> actionSets_;
2936 std::expected<void, TreeError> prepareActionMenus();
2937 bool installingThemeSelection_{};
2938 std::vector<std::shared_ptr<Entry>> entries_;
2939 std::shared_ptr<detail::ManagedScrollState> scroll_;
2940 std::weak_ptr<const void> rowLayoutLease_;
2941 std::shared_ptr<detail::ManagedOrigin> rowOrigin_;
2942 std::vector<std::shared_ptr<void>> properties_;
2943 std::vector<std::shared_ptr<ObserverRecord>> observers_ = std::vector<std::shared_ptr<ObserverRecord>>(0);
2944 std::vector<OriginProperty> originProperties_ = std::vector<OriginProperty>(0);
2945 std::size_t coldMountPending_{};
2946 std::vector<std::shared_ptr<LiveTextRecord>> liveText_ = std::vector<std::shared_ptr<LiveTextRecord>>(0);
2947 std::vector<std::shared_ptr<detail::ManagedModelSource>> models_;
2948 std::unique_ptr<detail::ManagedNavigationRegistry> navigation_;
2949 std::expected<void, TreeError> synchronizeNavigation();
2950 std::expected<void, TreeError> navigationBefore(Node<Widget> node);
2951 std::expected<void, TreeError> navigationAfter(Node<Widget> node);
2952 void retireNavigation() noexcept;
2953 void pruneNavigation();
2954 template <class T, class W>
2955 std::expected<void, ManagedError> bindNavigationView(Node<W> node, ManagedNavigation navigation,
2956 NavigationBindingOptions options);
2957 std::shared_ptr<std::function<std::expected<bool, ManagedError>(const InputEvent &)>> input_;
2958 std::shared_ptr<KeySnapshot> keys_;
2959 std::shared_ptr<const KeyBindingsSnapshot> keyProjection_;
2960 std::uint64_t keyRevision_{1};
2961 std::uint64_t keySerial_{};
2962 std::uint64_t keyScopeGeneration_{1};
2963 bool keyStaging_{};
2964 std::array<std::uint64_t, 4> failedKeyProjection_{};
2965 std::size_t keyProjectionBytes_{};
2966 std::size_t keyHandlers_{};
2967 std::size_t clickHandlers_{};
2968 std::size_t editingHandlers_{};
2969 std::size_t changeHandlers_{};
2970 std::vector<std::shared_ptr<LayoutRecord>> layouts_ = std::vector<std::shared_ptr<LayoutRecord>>(0);
2971 std::shared_ptr<detail::DialogHostRecord> dialogs_;
2972 std::vector<std::shared_ptr<detail::MessageRecord>> messages_ =
2973 std::vector<std::shared_ptr<detail::MessageRecord>>(0);
2974 std::vector<std::shared_ptr<detail::MessageRequest>> messageRequests_ =
2975 std::vector<std::shared_ptr<detail::MessageRequest>>(0);
2976 bool collectingMessages_{};
2977 std::shared_ptr<detail::NotificationRecord> notifications_;
2978 bool dialogOperation_{};
2979 bool collectingDialogs_{};
2980 std::uint64_t layoutRevision_{};
2981 std::shared_ptr<ManagedErrorHandler> errorObserver_;
2982 std::vector<ManagedDiagnostic> errors_;
2983 ManagedDiagnostic overflowDiagnostic_;
2984 std::size_t errorCount_{};
2985 std::size_t droppedErrors_{};
2986 std::size_t contextFailures_{};
2987 std::size_t observerFailures_{};
2988 std::size_t suppressedNotifications_{};
2989 std::optional<std::size_t> failureDiagnostic_;
2990 std::optional<ManagedError> failure_;
2991 std::optional<ManagedError> closeFailure_;
2992 bool closeFailureRetained_{};
2993 std::optional<TreeError> cleanup_;
2994 struct FocusReport;
2995 bool stylesDirty_{};
2996 mutable bool styling_{};
2997 bool preparing_{};
2998 bool recoveringObservers_{};
2999 bool pruningObservers_{};
3000 std::size_t observerCallbacks_{};
3001 std::size_t mountDepth_{};
3002 bool reporting_{};
3003 bool actionAdmitted_{};
3004 bool dialogPrimaryRecorded_{};
3005 bool failureNotified_{};
3006 bool runFailureNotified_{};
3007 bool notifyingRunFailure_{};
3008 void *closeContext_{};
3009 std::expected<void, ManagedError> (*beforeClose_)(void *){};
3010 std::optional<std::expected<ApplicationStep, ManagedError>> sessionResult_;
3011 bool sessionActive_{}, sessionOperating_{}, stoppingSession_{};
3012 bool closing_{};
3013 bool closed_{};
3014 std::shared_ptr<bool> textMutating_ = std::make_shared<bool>(false);
3015};
3016} // namespace portals
3017
3018#include <portals/detail/managed_derive.hpp>
3019#include <portals/detail/managed_navigation.hpp>
3020
3021// Plain history types must be complete before the dependent view templates.
3022#include <portals/detail/model_view_history.hpp>
3023
3024// These integration headers depend on the navigation and history records above.
3025#include <portals/detail/managed_navigation_views.hpp>
3026#include <portals/detail/managed_scroll.hpp>
3027#include <portals/detail/managed_views.hpp>
3028
3029#include <portals/detail/managed_collections.hpp>
3030
3031#include <portals/detail/managed_data_presentation.hpp>
Exclusive ready-only transport borrowed by an application session. Every operation must return withou...
Definition application.hpp:162
Borrowed scene extension; bindings/models/providers belong to the caller. Construct the Application f...
Definition application.hpp:281
Custom/replay terminal borrowed for exactly one run; no competing I/O is allowed. The owner retains i...
Definition application.hpp:112
One UI owner for scheduler, tree, routing and a single terminal run. All calls/destruction except req...
Definition application.hpp:358
Owning checked editor command, preserving exactly its collector reporting receipt....
Definition editor_command.hpp:23
UI-owned Grid implementing the existing pure Layout contract. Every visible child needs a placement....
Definition grid.hpp:149
Copyable immutable owning shortcut selection, or a deferred typed construction error....
Definition shortcut.hpp:171
Owning immutable identities and local sizes from one completed layout pass. Copies share immutable va...
Definition layout_snapshot.hpp:43
Weak UI handle to a model owned by one ManagedScene. Handles may be copied and destroyed on any threa...
Definition managed_model.hpp:120
Weak UI-affine navigation handle owned by an existing scene/model scope. Removing a view does not rem...
Definition managed_navigation.hpp:119
Additive lifecycle owner over one existing Application subtree. UI affine and nonmovable....
Definition managed.hpp:530
bool hasPendingLayout() const noexcept override
std::expected< void, ManagedError > onClick(Node< Button > node, Callback action)
Definition managed.hpp:841
std::expected< void, ManagedError > bindNavigation(Node< VirtualList< T > > node, ManagedNavigation navigation, NavigationBindingOptions options={})
Definition managed_navigation_views.hpp:257
std::expected< LogStatus, ManagedError > logStatus(Node< LogView > node)
std::expected< VisibleModelSnapshot< T >, VisibleModelError > visibleModelSnapshot(Node< VirtualTable< T > > node) const
Read ready physical rows after successful final layout publication.
Definition managed_views.hpp:9
std::expected< PropertyUpdate< bool >, ManagedError > setChecked(Node< CheckBox > node, bool value)
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< void, ManagedError > dialog(Node< Dialog > node, Node< Widget > panel, Node< Widget > body)
Register an initially hidden layer under the declared host.
std::expected< void, ManagedError > onError(ManagedErrorHandler callback)
Retain or clear the UI error observer; empty clears it.
std::expected< ApplicationStep, ManagedError > step()
~ManagedScene()
Retire bindings and the owned subtree on UI; wrong-thread/frame destruction terminates.
std::expected< void, TreeError > reportError(ManagedError failure, std::span< const ManagedDiagnosticContext > contexts={}, std::source_location origin=std::source_location::current()) noexcept
Record an explicit error without changing runtime stop/recovery policy.
std::expected< bool, ManagedError > dialogOpened(Node< Widget > node)
std::expected< void, ManagedError > onDismiss(Node< Dialog > node, Callback callback)
Definition managed.hpp:1408
std::expected< void, ManagedError > focus(Node< Widget > node)
Enter a scope or focus an ordinary registered control through the same blur path.
static std::expected< std::unique_ptr< ManagedScene >, ManagedError > create(Application &app, ManagedOptions options={})
std::expected< Node< VirtualTable< T > >, ManagedError > virtualTable(Node< Widget > parent, ManagedModel< T > model, std::type_identity_t< std::span< const TableColumn< T > > > columns, VirtualTableOptions options={}, SizePolicy policy=DEFAULT_VIEWPORT_POLICY, std::type_identity_t< ManagedViewHandler< T > > prepared={})
Mount a table with owned range, input binding, style and automatic preparation.
Definition managed_views.hpp:1389
std::expected< void, ManagedError > onKey(KeyEvent chord, Callback action)
Definition managed.hpp:867
std::expected< void, ManagedError > bindText(Node< Control > node, ManagedSource< std::string > source)
Definition managed.hpp:1354
std::expected< void, ManagedError > close()
Idempotently retire callbacks and subtree; properties survive until scene destruction....
Node< Widget > root() const noexcept
Definition managed.hpp:545
std::expected< std::optional< PositionResolution >, ManagedError > restoreStatus(Node< VirtualList< T > > node) const
Definition managed_views.hpp:1343
std::expected< void, ManagedError > onKey(Value &&shortcut, Callback action, ShortcutBehavior behavior={}, ShortcutOptions options={}, std::source_location origin=std::source_location::current())
Definition managed.hpp:970
std::expected< ManagedSource< detail::DerivedOutput< Transform, In > >, ManagedError > derive(ManagedSource< In > input, Transform &&transform, Invalidation kind=Invalidation::PAINT, PropertyOptions options={}, std::source_location origin=std::source_location::current())
Definition managed.hpp:819
std::expected< Invalidation, ManagedError > updateLayers(std::span< const StyleLayerUpdate > updates)
std::expected< void, ManagedError > setScrollOffset(Node< Widget > node, ScrollAxis axis, ScrollOffset offset)
std::expected< void, ManagedError > start(ApplicationReadyTerminal &terminal, std::stop_token stop={})
std::expected< void, ManagedError > bind(Node< LineEdit > node, ManagedState< std::string > model, std::function< std::expected< void, TreeError >(LineEditResult)> result={}, std::shared_ptr< Clipboard > clipboard={}, std::function< bool(std::string_view)> validate={})
std::expected< void, ManagedError > observe(ManagedState< T > model, Callback &&callback)
Definition managed.hpp:756
std::expected< void, ManagedError > leaveFocusScope(Node< Widget > node)
Leave the top focus-return scope; callback errors retain the published return.
std::expected< void, ManagedError > validateStyleLayer(StyleLayerHandle handle) const
Validate an observing layer identity without resolving styles or invoking callbacks.
std::expected< void, ManagedError > overlayHost(Node< OverlayHost > host, Node< Widget > body)
Bind the scene's sole retained host to its exact ordinary body.
std::expected< Node< T >, ManagedError > emplace(Node< Widget > parent, Args &&...args)
Checked mount with automatic standard presentation and style registration. Failure retires only the a...
Definition managed.hpp:585
std::expected< void, ManagedError > bind(Node< CheckBox > node, ManagedState< bool > model, std::function< std::expected< void, TreeError >(CheckBoxResult)> changed={})
bool usesGeometrySnapshot() const noexcept override
std::expected< bool, TreeError > input(Application &app, const InputEvent &event) override
std::expected< void, ManagedError > onEditingFinished(Node< T > node, Callback callback, std::source_location origin=std::source_location::current())
Definition managed.hpp:1328
std::expected< void, ManagedError > bind(Node< RadioGroup > node, ManagedState< RadioGroupValue > model, std::function< std::expected< void, TreeError >(RadioGroupResult)> changed={})
std::expected< PropertyUpdate< RadioGroupValue >, ManagedError > selectRadio(Node< RadioGroup > node, std::optional< RowId > id)
bool usesPreparedLayout() const noexcept override
Opt into bounded layout-driven view preparation; default is false.
std::expected< PasswordValue, ManagedError > passwordValue(Node< Password > node) const
std::expected< ApplicationStats, ManagedError > run(ApplicationTerminal &terminal, std::stop_token stop={})
std::expected< void, ManagedError > bind(Node< Password > node, ManagedState< PasswordValue > model, std::function< std::expected< void, TreeError >(PasswordResult)> result={}, std::shared_ptr< Clipboard > clipboard={}, std::function< bool(SecretView)> validate={})
std::expected< void, ManagedError > enableStyleLayers(StyleLayerOptions options={})
Opt into owning style tiers; failure preserves pending registrations and legacy controllers.
std::expected< LogAppendReceipt, ManagedError > appendLogBatch(Node< LogView > node, std::string_view bytes)
std::expected< Invalidation, ManagedError > styleDefaults(const StyleSheet &sheet)
std::expected< void, ManagedError > enterFocusScope(Node< Widget > node)
Enter a declared scope while saving exact previous focus in the existing router. This focus-only oper...
std::expected< void, ManagedError > onEditingFinished(Node< T > node, const Callback &callback, std::source_location origin=std::source_location::current())
Definition managed.hpp:1246
std::expected< ManagedDiagnosticBatch, TreeError > diagnostics() const
Copy the bounded error history on UI, including after close.
std::expected< void, ManagedError > classes(Node< Widget > node, std::vector< std::string > values)
std::expected< void, ManagedError > openDialog(Node< Widget > node)
Open a ready registered layer; an already open layer is unchanged.
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< void, ManagedError > focusDefault(Node< Widget > node)
Set a live managed node as its nearest scope's default.
std::expected< void, ManagedError > observe(Node< W > receiver, ManagedSource< T > source, Callback &&callback)
Definition managed.hpp:772
std::expected< void, ManagedError > setScrollMetrics(Node< ScrollBar > node, ScrollAxisMetrics metrics)
std::expected< void, ManagedError > setLogModel(Node< LogView > node, ui::LogSource source)
std::expected< void, ManagedError > setModel(Node< VirtualList< T > > node, ManagedModel< T > model, std::type_identity_t< std::optional< ManagedViewHandler< T > > > prepared=std::nullopt, ModelRebindOptions options={})
Atomically replace a managed list's model without replacing its node or presentation.
Definition managed_views.hpp:1327
std::expected< ApplicationStats, ManagedError > run(std::stop_token stop={})
std::expected< void, TreeError > afterDispatch(Application &app) override
std::expected< void, ManagedError > bind(Node< SpinBox > node, NumericState model, LineEditOptions options={}, std::uint64_t pageSteps=10)
std::expected< void, ManagedError > onInput(std::function< std::expected< bool, ManagedError >(const InputEvent &)> callback)
std::expected< NumericState, ManagedError > numericState(double initial=0, NumericRange range={})
std::expected< void, ManagedError > followLogTail(Node< LogView > node)
bool requiresBackgroundExecutor() const noexcept override
Definition managed.hpp:1962
std::expected< void, ManagedError > dialogAnchor(Node< Widget > node, Node< Widget > anchor, DialogPlacement placement)
Set the body-only anchor before the first activation.
std::expected< void, ManagedError > theme(StyleSheet sheet)
std::expected< void, ManagedError > onPrepare(Node< T > node, std::type_identity_t< ManagedPrepareHandler< T > > callback)
Register custom presentation work at the existing dirty-frame boundary.
Definition managed.hpp:1524
std::expected< Node< ScrollBar >, ManagedError > scrollBar(Node< Widget > parent, std::shared_ptr< ScrollController > controller={}, ScrollAxis axis=ScrollAxis::VERTICAL, ScrollBarOptions options={}, ControlStyle style={}, bool geometryWriter=true)
std::expected< ManagedState< RadioGroupValue >, ManagedError > radioState(std::initializer_list< std::string_view > captions)
std::expected< KeyBindingsSnapshot, ManagedError > keyBindings()
void stop(Application &app) override
WidthPolicy widthPolicy() const noexcept
Definition managed.hpp:550
std::expected< void, ManagedError > style(Node< Widget > node, StyleTarget target)
std::expected< void, ManagedError > ensureVisible(Node< Widget > node, Node< Widget > root={})
std::expected< void, ManagedError > clearLog(Node< LogView > node)
std::expected< ManagedSource< GraphemeText >, ManagedError > liveText(const ui::TextSource &source, PropertyOptions options={}, std::source_location origin=std::source_location::current())
Attach a readonly node-scoped source to a published caption, draft or accepted editor value.
std::expected< StyleLayerHandle, ManagedError > addLayer(StyleTier tier, std::string_view name, const StyleSheet &sheet)
std::expected< Node< VirtualList< T > >, ManagedError > virtualList(Node< Widget > parent, ManagedModel< T > model, std::type_identity_t< ManagedListFormatter< T > > delegate, VirtualListOptions options={}, SizePolicy policy=DEFAULT_VIEWPORT_POLICY, std::type_identity_t< ManagedViewHandler< T > > prepared={})
Mount a list with owned range, input binding, style and automatic preparation.
Definition managed_views.hpp:1415
std::expected< Invalidation, ManagedError > replaceLayer(StyleLayerHandle handle, const StyleSheet &sheet)
std::expected< StyleLayerHandle, ManagedError > baseLayer(StyleTier tier) const
std::expected< Node< Chart< T > >, ManagedError > chart(Node< Widget > parent, ManagedModel< T > model, std::type_identity_t< ManagedChartAccessor< T > > accessor, ChartOptions options={}, ManagedChartOrigin first={}, std::type_identity_t< ManagedViewHandler< T > > prepared={}, SizePolicy policy=DEFAULT_VIEWPORT_POLICY)
Mount a chart with owned range, style and automatic preparation.
Definition managed_views.hpp:1441
std::expected< NodeGeometry, ManagedError > geometry(Node< Widget > node) const
Read an owning final arranged value without performing layout or reporting errors.
std::expected< void, ManagedError > onChange(Node< T > node, Callback callback, std::source_location origin=std::source_location::current())
Definition managed.hpp:1119
std::expected< void, ManagedError > observe(ManagedSource< T > source, Callback &&callback)
Definition managed.hpp:786
std::expected< void, ManagedError > onTextEdited(Node< LineEdit > node, Callback callback, std::source_location origin=std::source_location::current())
Definition managed.hpp:1307
std::expected< Invalidation, ManagedError > removeLayer(StyleLayerHandle handle)
std::expected< RadioGroupValue, ManagedError > radioValue(Node< RadioGroup > node)
std::expected< void, ManagedError > bind(Node< Slider > node, NumericState model, std::function< std::expected< void, TreeError >(SliderResult)> changed={})
std::expected< void, TreeError > prepare(Application &app, CellSize size) override
std::expected< bool, ManagedError > checkedValue(Node< CheckBox > node)
std::expected< void, ManagedError > focusScope(Node< Widget > node)
Declare a nested focus scope; this scene owns its disconnect token.
std::expected< void, ManagedError > onClick(Node< Button > node, std::function< std::expected< void, TreeError >()> action)
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
bool requiresPointerMotion() const noexcept override
std::expected< void, TreeError > clearErrors() noexcept
Clear history and counters while preserving capacity and runtime first failure.
std::expected< Node< LogView >, ManagedError > logView(Node< Widget > parent, std::string_view initial={}, LogViewConfig config={}, ControlStyle style={}, SizePolicy policy=DEFAULT_LOG_VIEW_POLICY, std::optional< FrameOptions > frame={})
std::expected< ManagedState< RadioGroupValue >, ManagedError > radioState(std::span< const TextValue > captions, KeyTextResolver resolver={}, CollectionLimits limits={})
std::expected< void, ManagedError > bindText(Node< Control > node, ManagedState< std::string > model)
Observe accepted text as a one-way caption, independently of the control's action.
std::expected< void, ManagedError > onEvent(Node< T > node, std::type_identity_t< ManagedEventHandler< T > > callback)
Own one custom event callback, without subclassing or an additional router.
Definition managed.hpp:1468
std::expected< Node< Spinner >, ManagedError > spinner(Node< Widget > parent, SpinnerOptions options={}, ControlStyle style={}, SizePolicy policy=DEFAULT_CONTENT_POLICY, SpinnerLabelResolver resolver={})
std::expected< void, ManagedError > id(Node< Widget > node, std::string_view value)
std::expected< void, ManagedError > bind(Node< CheckBox > node, ManagedState< CheckState > model, std::function< std::expected< void, TreeError >(CheckStateResult)> changed={}, CheckBoxOptions options={})
std::expected< ManagedNavigation, ManagedError > navigation(ModelResource resource, SourceStamp session, NavigationOptions options={})
std::expected< ManagedState< RadioGroupValue >, ManagedError > radioState(std::span< const RadioOption > options, KeyTextResolver resolver={}, CollectionLimits limits={})
std::expected< void, ManagedError > setKeyCapabilities(KeyCapabilities capabilities)
std::expected< void, ManagedError > observe(Node< W > receiver, ManagedState< T > model, Callback &&callback)
Own a one-way presentation observer until its receiver or scene retires. Initial delivery reads the l...
Definition managed.hpp:687
std::expected< LogNavigation, ManagedError > logNavigation(LogCheckpointOptions options={})
std::expected< std::vector< StyleLayerSource >, ManagedError > styleSources() const
Copy every actual layer row in installation order on the UI thread.
std::expected< void, ManagedError > onLayout(Node< Widget > node, Callback callback, std::source_location origin=std::source_location::current())
Definition managed.hpp:1928
std::expected< void, ManagedError > onChange(Node< T > node, Callback callback, std::source_location origin=std::source_location::current())
Definition managed.hpp:1070
std::expected< ManagedDiagnosticBatch, TreeError > drainErrors()
Copy then clear history and counters; allocation failure leaves them unchanged.
std::expected< StyleLayerHandle, ManagedError > styleDocument(StyleTier tier, std::string_view name, const PssDocument &document, std::optional< StyleLayerOptions > options=std::nullopt)
Atomically install owning declarations and provenance in an APPLICATION or USER layer.
std::expected< void, ManagedError > onKey(const KeySelection &selection, Callback action, std::source_location origin=std::source_location::current())
Definition managed.hpp:990
std::expected< void, TreeError > completedLayout(Application &app) override
std::expected< void, ManagedError > dismissDialog(Node< Widget > node)
Dismiss a layer; a closed layer is unchanged and callbacks never replay.
std::expected< void, ManagedError > onChange(Node< T > node, const Callback &callback, std::source_location origin=std::source_location::current())
Definition managed.hpp:1188
std::expected< void, TreeError > prepareViews(Application &app, const LayoutSnapshot &snapshot) override
Prepare registered views from the pins captured by prepare(), in registration order.
std::expected< KeyBinding, ManagedError > onKey(const KeySelection &selection, KeyInfo info, Callback action, std::source_location origin=std::source_location::current())
Definition managed.hpp:906
std::expected< void, ManagedError > setPasswordValue(Node< Password > node, PasswordValue value)
std::expected< void, ManagedError > remove(Node< Widget > node)
Retire one managed subtree and immediately reclaim its managed entry budget.
Read-only weak scene-owned derived value; no writable alias or subscription escapes.
Definition managed.hpp:484
std::expected< std::shared_ptr< const PropertyChange< T > >, TreeError > snapshot() const
Definition managed.hpp:492
ManagedSource()=default
Construct an empty source whose operations return CLOSED.
Weak UI handle to a scene-owned Property, never an owning alias. Copies and destruction of the handle...
Definition managed.hpp:367
std::expected< PropertyUpdate< T >, TreeError > set(const T &value) const
Definition managed.hpp:375
std::expected< std::shared_ptr< const PropertyChange< T > >, TreeError > snapshot() const
Definition managed.hpp:399
ManagedState()=default
Construct an empty handle; operations return CLOSED.
std::expected< PropertyUpdate< T >, TreeError > set(T &&value) const
Definition managed.hpp:387
Immutable list/table provider storage, independent of view/source lifetime. Implement read as bounded...
Definition model.hpp:94
Copyable typed observer; never owns or exposes an unchecked widget pointer.
Definition widget.hpp:92
Weak checked numeric source over the existing scene-owned Property runtime. Copies own no scene/widge...
Definition managed.hpp:451
NumericState()=default
Create an empty handle whose operations return CLOSED.
std::expected< std::shared_ptr< const PropertyChange< NumericValue > >, ManagedError > snapshot() const
std::expected< PropertyUpdate< NumericValue >, ManagedError > set(double candidate) const
std::expected< PropertyUpdate< NumericValue >, ManagedError > configure(double initial, NumericRange range) const
Copyable identity of immutable logical bytes in protected native storage.
Definition password_value.hpp:44
static std::expected< std::unique_ptr< Property >, TreeError > create(WidgetTree &tree, Node< Widget > target, const T &initial, Invalidation kind, PropertyOptions options={})
Create a source bound to one checked invalidation target; no initial notification....
Definition property.hpp:76
Weak UI-affine observer; destruction does not remove its layer.
Definition style.hpp:272
One UI-owned table with bounded owning cell text and one independent model consumer....
Definition virtual_table.hpp:154
Copyable immutable ready values for one physically visible table interval.
Definition visible_model.hpp:31
UI-owned extension object. Hooks borrow their arguments for one call. Models are separate explicit ow...
Definition widget.hpp:32
Weak UI-affine action identity; owner retirement never leaves an executable callback.
Definition ui_action.hpp:117
Owning deferred external log binding; construction performs no file I/O. Copies share the provider an...
Definition ui_log_view.hpp:48
Copyable read-only source observing one caption, visible draft or accepted editor model....
Definition ui_ref.hpp:302
Owning catalog input; legacy factories run synchronously once per explicit preview attempt on UI....
Definition theme_selection.hpp:95
Weak UI-affine observation of the one scene-owned catalog/model. Copying/destroying observations neve...
Definition theme_selection.hpp:224
Allocation-free UI execution publication; an empty scope suspends the caller's scene.
Definition current_scene.hpp:37
Suspend an unrelated setup collector during an independently owned callback.
Definition current_scene.hpp:16
Allocation-free current-thread setup context; nested independent scopes restore their parent.
Definition setup_failure.hpp:57
Stack-local entered-report identity, valid only during one synchronous collector call.
Definition setup_failure.hpp:22
Admitted value callbacks take precedence over exact owning commit receipts.
Definition managed.hpp:259
Recognize a checkbox value invocation with a supported result.
Definition managed.hpp:250
Accepted compact callback results; command receipts retain exact reporting provenance.
Definition managed.hpp:207
A compact action optionally receives owning event parameters.
Definition managed.hpp:239
Reject known borrowed outputs; arbitrary user values still satisfy Property's owning contract.
Definition managed.hpp:312
Exact checked TreeError result, including owning success values.
Definition managed.hpp:201
auto live(ManagedScene &scene, const S &description)
Definition style_static.hpp:1703
consteval auto type(StyleState state=StyleState::ANY, bool readOnly=false)
Definition style_static.hpp:876
auto bind(ManagedState< std::string > value)
Definition ui_static.hpp:591
Public Portals API.
Definition action.hpp:8
std::variant< ManagedError, VisibleModelReadError > VisibleModelError
Exact scene access failure or owning table preparation/provider failure.
Definition managed.hpp:43
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
DataPhase
Presentation facts; offline is explicit domain information, never inferred from an error string.
Definition data_presentation.hpp:11
constexpr SizePolicy DEFAULT_LOG_VIEW_POLICY
Native log default: fill both viewport axes from zero flex bases; explicit SizePolicy stays literal.
Definition log_view.hpp:33
std::function< std::expected< EventReply, TreeError >(T &, const RoutedEvent &)> ManagedEventHandler
Owning, copyable custom input adapter; arguments are borrowed for one invocation.
Definition managed.hpp:326
std::expected< PropertyUpdate< CheckState >, TreeError > CheckStateResult
Exact typed Property set receipt; successful commits can reject notifications.
Definition controls.hpp:477
std::expected< PropertyUpdate< RadioGroupValue >, TreeError > RadioGroupResult
Exact selection commit and observer-publication receipt, or a precommit TreeError.
Definition radio_group.hpp:141
std::function< std::expected< std::string, TextResourceError >(std::string_view)> SpinnerLabelResolver
Owning synchronous label lookup, invoked only while staging a configuration.
Definition spinner.hpp:14
std::function< std::expected< std::string, TextResourceError >(std::string_view)> KeyTextResolver
Same exact resolver type as ui::TextResolver; used only during checked normalization.
Definition key_binding.hpp:57
std::expected< PropertyUpdate< NumericValue >, TreeError > SliderResult
Exact numeric Property operation receipt; unexpected means no commit.
Definition slider.hpp:138
std::variant< KeyEvent, TextInputEvent, MouseInputEvent, PasteInputEvent, InputProbeCandidate, InputIssue > InputEvent
Independent owning result, usable beyond decoder reset/destruction.
Definition input.hpp:378
PositionResolution
Successful protocol outcomes; absence of support differs from missing history.
Definition model_position.hpp:123
constexpr SizePolicy DEFAULT_CONTENT_POLICY
Intrinsic content on both axes; explicit policies remain authoritative.
Definition layout.hpp:44
@ HANDLED
Stop bubbling; this registration consumed the event.
Definition action.hpp:51
constexpr SizePolicy DEFAULT_VIEWPORT_POLICY
A bounded data viewport fills both axes without requesting the whole model extent.
Definition layout.hpp:53
std::function< std::expected< std::uint64_t, TreeError >()> ManagedChartOrigin
Owning chart-origin callback, evaluated in registration order before chart preparation.
Definition managed_model.hpp:245
KeyEligibility
Eligibility observed for one immutable snapshot, not a universal conflict winner.
Definition key_binding.hpp:81
std::function< std::optional< Ohlc >(const T &)> ManagedChartAccessor
Owning projection of a borrowed domain row into an optional candle. The callback runs during preparat...
Definition managed_model.hpp:240
std::expected< void, ShortcutError > validateShortcut(const Shortcut &shortcut, ShortcutOptions options={}) noexcept
std::variant< ActionEvent, KeyEvent, TextInputEvent, PasteInputEvent, MouseInputEvent > RoutedEvent
Synchronous input value; callback borrows it only until return.
Definition action.hpp:47
DialogDismissReason
Generic dismissal cause, independent of application results.
Definition dialog.hpp:28
ManagedPhase
Boundary at which a managed operation failed.
Definition managed_diagnostics.hpp:48
@ STATE
Create and retain a scene-owned property.
Definition managed_diagnostics.hpp:50
@ BIND
Register a managed callback, binding or presentation adapter.
Definition managed_diagnostics.hpp:51
@ INPUT
Dispatch input or deliver a managed control/property callback.
Definition managed_diagnostics.hpp:54
ScrollAxis
Logical scrolling axis; X increases right and Y increases down.
Definition scroll_geometry.hpp:15
@ VERTICAL
Rows.
Definition scroll_geometry.hpp:17
MessageChoice
A requested application action; SAVE does not confirm that data was written.
Definition message_box.hpp:14
@ INVALID_CHORD
Invalid semantic key/scalar combination.
Definition shortcut.hpp:26
@ NO_MEMORY
Owning alternative allocation failed.
Definition shortcut.hpp:27
std::function< GraphemeText(const ModelRow< T > &)> ManagedListFormatter
Owning formatter of a borrowed visible list row into owning text. The callback runs during preparatio...
Definition managed_model.hpp:233
std::uint64_t SchedulerTime
Monotonic milliseconds; the clock must not move backwards.
Definition scheduler.hpp:18
std::function< void(const ManagedDiagnostic &)> ManagedErrorHandler
Scene-owned UI observer; the diagnostic is borrowed only until the call returns.
Definition managed_diagnostics.hpp:154
StyleTier
Independent cascade priority, before selector specificity.
Definition style.hpp:251
DialogPlacement
Preferred panel position within the owning host.
Definition dialog.hpp:21
Invalidation
Accumulated work; layout always includes painting.
Definition widget_types.hpp:41
@ LAYOUT
Layout and painting are required; old arranged geometry becomes invalid.
Definition widget_types.hpp:44
@ PAINT
Painting is required; arranged geometry remains usable.
Definition widget_types.hpp:43
std::function< std::expected< void, TreeError >(T &, Node< Widget >)> ManagedPrepareHandler
Owning, copyable custom presentation adapter at the dirty-frame boundary.
Definition managed.hpp:331
std::expected< PropertyUpdate< bool >, TreeError > CheckBoxResult
Exact Property set outcome; errors mean no commit, successful receipts can reject notifications.
Definition controls.hpp:474
std::function< std::expected< void, TreeError >(const ModelFrame< T > &, const std::optional< ModelRequest< T > > &)> ManagedViewHandler
Owning callback after each successful virtual-view preparation, including layout retries....
Definition managed_model.hpp:25
TreeError
Checked tree failures; rejected operations never start the requested callback.
Definition widget_types.hpp:26
@ CLOSED
The owning tree or source is closed.
Definition widget_types.hpp:31
@ CALLBACK_FAILED
A user extension or callback threw.
Definition widget_types.hpp:37
@ NODE_LIMIT
The configured live node, observer or consumer limit was reached.
Definition widget_types.hpp:35
@ WRONG_THREAD
Operation requires the tree's UI thread.
Definition widget_types.hpp:28
@ INVALID_ARGUMENT
An option, enum value or operation argument is invalid.
Definition widget_types.hpp:27
@ 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 typed checkbox input configuration.
Definition controls.hpp:279
Bound the row/index storage of an immutable in-memory collection; domain T payload is source-owned.
Definition collection.hpp:9
Owning paint values; no theme engine or behavior is encoded here.
Definition controls.hpp:24
Application-supplied native phase support, independent of physical-key identity.
Definition key_binding.hpp:48
Owning key value without an inferred physical keyboard scan code.
Definition input.hpp:213
Owning metadata normalized once before canonical publication.
Definition key_binding.hpp:60
Owning bounds and appearances for a one-line editor.
Definition line_edit.hpp:175
Exact editing or confirmation result delivered on the UI thread.
Definition line_edit.hpp:104
Configurable metadata bounds; no source-count limit or LRU eviction.
Definition log_navigation.hpp:89
Owning bounded-log settings; frame bars use ON_FRAME without a horizontal gutter.
Definition log_view.hpp:23
Owning snapshot or drained history; counters saturate at size_t's maximum.
Definition managed_diagnostics.hpp:143
Finite error-history and causal-context budgets. All limits must be positive.
Definition managed_diagnostics.hpp:114
Original error plus independent runner/restoration and cleanup failures.
Definition managed_diagnostics.hpp:62
std::optional< ShortcutError > shortcut
Exact shortcut syntax/value cause and owned offset, when present.
Definition managed_diagnostics.hpp:79
Finite managed bookkeeping budgets, independent of the existing tree/queue limits.
Definition managed.hpp:334
std::size_t maxModels
Maximum scene-owned models; retired row scopes release their slots.
Definition managed.hpp:338
std::size_t maxEditingHandlersPerNode
Positive combined callback maximum for one editor.
Definition managed.hpp:356
ManagedDiagnosticOptions diagnostics
Positive limits for error history and owning causal traces.
Definition managed.hpp:339
std::size_t maxClickHandlers
Positive maximum retained pipe click callbacks across the scene.
Definition managed.hpp:341
std::size_t maxClickHandlersPerNode
Positive maximum pipe click callbacks for one button.
Definition managed.hpp:342
std::size_t maxObserverRecoveryPasses
Positive dirty-prepare convergence bound.
Definition managed.hpp:349
std::size_t maxObservers
Positive scene-owned state observer limit.
Definition managed.hpp:347
std::size_t maxStates
Maximum scene-owned properties; retired row scopes and private text adapters release their slots.
Definition managed.hpp:336
std::size_t maxChangeHandlersPerNode
Positive maximum change callbacks for one checkbox.
Definition managed.hpp:358
std::size_t maxLayoutPublicationRetries
Positive queue-full attempt cap before one typed rejection and cancellation.
Definition managed.hpp:345
SchedulerTime keySequenceTimeout
Positive inactivity timeout between sequence strokes, in milliseconds.
Definition managed.hpp:343
KeyCapabilities keyCapabilities
Explicit native phase knowledge; UNKNOWN remains routable.
Definition managed.hpp:354
std::size_t maxEditingHandlers
Positive maximum retained callbacks across both editor event kinds.
Definition managed.hpp:355
std::size_t maxNodes
Maximum retained entries, including removals pending next preparation.
Definition managed.hpp:335
std::size_t maxKeyHandlers
Positive maximum owning onKey registrations; onInput resets the count.
Definition managed.hpp:340
std::size_t maxKeyProjectionBytes
Positive aggregate logical projection payload budget.
Definition managed.hpp:353
std::size_t maxMessageRequests
Positive cap including reservations and retired undelivered requests.
Definition managed.hpp:350
std::size_t maxObserversPerNode
Positive state observer limit per receiving node.
Definition managed.hpp:348
std::size_t maxKeyLabelBytes
Positive input and resolved label byte cap.
Definition managed.hpp:351
std::size_t maxChangeHandlers
Positive maximum retained checkbox change callbacks.
Definition managed.hpp:357
std::size_t maxKeyDescriptionBytes
Positive input and resolved description byte cap.
Definition managed.hpp:352
std::size_t maxLayoutHandlers
Positive maximum scene-owned geometry observers; scheduler limits apply too.
Definition managed.hpp:344
Finite per-model storage and work budgets; all fields must be positive.
Definition model.hpp:165
Logical resource namespace, distinct from its current delivery session. Reuse an existing SourceStamp...
Definition model_position.hpp:21
Positive bounded metadata limits; no source extent or viewport is retained.
Definition managed_navigation.hpp:95
Owning arranged geometry; invalid geometry must never be used for hit-testing.
Definition widget_types.hpp:48
Owning inclusive bounds and user increment; validated together with a numeric value.
Definition numeric.hpp:22
Secret-free editing outcome; a commit owns only protected immutable snapshots.
Definition password.hpp:60
Finite observer endpoint storage, independent of Scheduler queue capacity.
Definition property.hpp:28
A successful set result; notification rejection does not undo the committed value....
Definition property.hpp:38
Owning parsed declarations and provenance; input bytes need not survive the call. Metadata is not aut...
Definition pss_data.hpp:259
Owning one-axis logical metrics, independent of materialized content.
Definition scroll_geometry.hpp:41
Owning standalone bar settings, validated before mounting or replacement. No callbacks,...
Definition scroll_options.hpp:17
Owning exact integral position and sub-cell remainder; no affinity or invalidation.
Definition scroll_geometry.hpp:35
Command admission independent of low-level KeyEvent binding behavior.
Definition shortcut.hpp:51
Allocation-free diagnostic independent of source and scene lifetime.
Definition shortcut.hpp:34
Configurable finite parser limits; every value must be positive.
Definition shortcut.hpp:44
Owning shortcut alternatives; one registration invokes at most once per completed event.
Definition shortcut.hpp:91
Owning operation observation; model revisions and live onChange calls can be numerous.
Definition slider.hpp:51
Immutable source namespace; replacement sessions must share their old budget root.
Definition window_source.hpp:27
Owning single-row indicator configuration; no thread or timer is created by this value.
Definition spinner.hpp:87
Aggregate logical owning payload budgets; base slots count as layers.
Definition style.hpp:259
Owned immutable-at-use rules; constructing typed values may allocate and throw.
Definition style.hpp:233
Owned subject metadata, supplied explicitly for built-in or custom widget types.
Definition style.hpp:40
Owning deterministic width policy; no font or terminal matching promise.
Definition text.hpp:42
T Type
Owning successful payload type.
Definition managed.hpp:289
Unwrap the supported checked transform result without constructing an output.
Definition managed.hpp:279
T Type
Owning output type.
Definition managed.hpp:281
static ShortcutActions actions(const KeySelection &selection) noexcept
Definition shortcut.hpp:232
static ShortcutOptions options(const KeySelection &selection) noexcept
Definition shortcut.hpp:239
static const auto & shortcut(const KeySelection &selection) noexcept
Definition shortcut.hpp:225
Private bridge reusing managed lifetime, affinity and mutation boundaries.
Definition style_static.hpp:701
Finite normalization budgets and optional first-preview layer admission.
Definition theme_selection.hpp:77
Owning point-in-time read model; IDs do not claim the identity of an external theme....
Definition theme_selection.hpp:64
Internal bridge for checked access to managed scene and recipe state.
Definition ui_recipe_access.hpp:28