Portals0.7.0 · dev (544a5c68c72e · 2026-11-28 UTC)
Loading...
Searching...
No Matches
managed_derive.hpp
1// Copyright (c) 2026 ttldtor.
2// SPDX-License-Identifier: BSL-1.0
3#pragma once
4
5// Included after ManagedScene's definition; all records use its existing Property/Scheduler runtime.
6namespace portals {
7template <class T, class Callback>
8void ManagedScene::prepareObserverRecord(const std::shared_ptr<ObserverRecord> &record,
9 const std::shared_ptr<Property<T>> &source, Callback &&callback) {
10 record->revision = [source = std::weak_ptr(source)]() -> std::expected<std::uint64_t, TreeError> {
11 auto locked = source.lock();
12 if (!locked) {
13 return std::unexpected(TreeError::CLOSED);
14 }
15 auto snapshot = locked->snapshot();
16 return snapshot ? std::expected<std::uint64_t, TreeError>((*snapshot)->revision)
17 : std::unexpected(snapshot.error());
18 };
19 record->deliver = ui::detail::currentSceneCallback(
20 facadeContext(),
21 [source = std::weak_ptr(source), scene = facadeContext(), action = std::forward<Callback>(callback)](
22 const std::shared_ptr<ObserverRecord> &entered) mutable -> std::expected<std::uint64_t, TreeError> {
23 auto live = entered->scene->observerLive(entered);
24
25 if (!live || !*live) {
26 return live ? std::expected<std::uint64_t, TreeError>(entered->successful.value_or(0))
27 : std::unexpected(live.error());
28 }
29
30 auto locked = source.lock();
31 if (!locked) {
32 return std::unexpected(TreeError::CLOSED);
33 }
34 auto snapshot = locked->snapshot();
35 if (!snapshot) {
36 return std::unexpected(snapshot.error());
37 }
38 // The input and callable owners survive self/ancestor removal until this entered invocation returns.
39 ui::detail::SetupFailureScope collector(entered, ObserverRecord::collectShortFailure, "managed.observe");
40 ui::detail::CurrentSceneScope current(scene);
41 auto status = [&]() {
42 if constexpr (std::invocable<Callback &, const T &, const std::shared_ptr<ObserverRecord> &>) {
43 return detail::invokeIgnoringValue(action, std::as_const((*snapshot)->value), entered);
44 } else {
45 return detail::invokeIgnoringValue(action, std::as_const((*snapshot)->value));
46 }
47 }();
48 return status ? std::expected<std::uint64_t, TreeError>((*snapshot)->revision) : std::unexpected(status.error());
49 });
50}
51
52template <class W, class T>
53std::expected<Subscription, TreeError>
54ManagedScene::connectObserverRecord(Node<W> receiver, const std::shared_ptr<Property<T>> &source,
55 const std::shared_ptr<ObserverRecord> &record) {
56 return source->observe(receiver, [this, weak = std::weak_ptr(record), lifetime = std::weak_ptr(lifetime_)](
57 W &, std::shared_ptr<const PropertyChange<T>>) {
58 auto entered = weak.lock();
59 if (!lifetime.expired() && entered && !entered->initialPending) {
60 (void)invokeObserver(entered, ManagedPhase::INPUT);
61 }
62 });
63}
64
65template <std::equality_comparable In, class Transform>
67std::expected<ManagedSource<detail::DerivedOutput<Transform, In>>, ManagedError>
69 std::source_location origin) {
70 ui::detail::SetupFailureScope mask({}, nullptr, nullptr);
71 using Out = detail::DerivedOutput<Transform, In>;
72 const auto failure = [&](TreeError cause, const char *operation = "derive.initial") {
73 auto result = error(ManagedPhase::STATE, root_, cause);
74 result.operation = operation;
75 result.operationOrigin = origin;
76 result.registrationOrigin = origin;
77 return std::unexpected(result);
78 };
79 const auto admission = [&]() -> std::expected<void, ManagedError> {
80 auto allowed = observerAdmission(root_);
81 if (!allowed) {
82 return failure(std::get<TreeError>(allowed.error().cause), "derive.register");
83 }
84 if (properties_.size() >= options_.maxStates || properties_.size() == properties_.max_size() ||
85 observers_.size() == observers_.max_size()) {
86 return failure(TreeError::NODE_LIMIT, "derive.register");
87 }
88 return {};
89 };
90 auto allowed = admission();
91 if (!allowed) {
92 return std::unexpected(allowed.error());
93 }
94 if ((kind != Invalidation::PAINT && kind != Invalidation::LAYOUT) || !options.max_observers) {
95 return failure(TreeError::INVALID_ARGUMENT, "derive.register");
96 }
97 auto source = input.lock();
98 if (!source || input.scene_ != root_.id()) {
99 return failure(source ? TreeError::INVALID_ARGUMENT : source.error(), "derive.register");
100 }
101
102 try {
103 if constexpr (std::is_pointer_v<std::decay_t<Transform>> || requires { transform.operator bool(); }) {
104 if (!static_cast<bool>(transform)) {
105 return failure(TreeError::INVALID_ARGUMENT, "derive.register");
106 }
107 }
108 auto record = std::make_shared<ObserverRecord>();
109 record->inputOrigin = input.origin_;
110 record->recoveryOrigin = input.origin_ ? input.origin_ : input.recoveryOrigin_;
111 record->scene = this;
112 record->node = rowOrigin_ ? rowOrigin_->node : root_;
113 record->runtime = false;
114 record->operation = "derive.compute";
115 record->origin = origin;
116
117 // Keep one callable instance for initial and subsequent computations. Consume a stationary result:
118 // moving checked MSVC strings through an intermediate expected can allocate inside noexcept moves.
119 auto wrapped = ui::detail::currentSceneCallback(
120 facadeContext(),
121 [scene = facadeContext(),
122 action = std::forward<Transform>(transform)](const In &value, const std::shared_ptr<ObserverRecord> &entered,
123 auto &&consume) mutable -> std::expected<void, TreeError> {
124 ui::detail::SetupFailureScope collector(entered, ObserverRecord::collectShortFailure, "managed.derive");
125 ui::detail::CurrentSceneScope current(scene);
126 auto result = std::invoke(action, value);
127 if (entered->shortFailure) {
128 const auto *cause = std::get_if<TreeError>(&entered->shortFailure->cause);
129 return std::unexpected(cause ? *cause : TreeError::CALLBACK_FAILED);
130 }
131 if constexpr (detail::IS_DERIVED_EXPECTED<decltype(result)>) {
132 return result ? consume(*result) : std::unexpected(result.error());
133 } else {
134 return consume(result);
135 }
136 });
137 auto callable = std::make_shared<decltype(wrapped)>(std::move(wrapped));
138 allowed = admission();
139 source = input.lock();
140 if (!allowed) {
141 return std::unexpected(allowed.error());
142 }
143 if (!source) {
144 return failure(source.error(), "derive.register");
145 }
146 auto initial = (*source)->snapshot();
147 if (!initial) {
148 return failure(initial.error());
149 }
150
151 std::shared_ptr<Property<Out>> output;
152 std::expected<void, TreeError> computed;
153 {
154 struct Computing {
155 std::size_t &count;
156
157 explicit Computing(std::size_t &active) : count(active) {
158 ++count;
159 }
160
161 ~Computing() {
162 --count;
163 }
164 } guard{observerCallbacks_};
165
166 try {
167 computed =
168 (*callable)(std::as_const((*initial)->value), record, [&](Out &value) -> std::expected<void, TreeError> {
169 auto created = [&] {
170 if constexpr (std::same_as<Out, std::string>) {
171 return Property<Out>::create(app_.tree(), root_, std::as_const(value), kind, options);
172 } else {
173 return Property<Out>::create(app_.tree(), root_, std::move(value), kind, options);
174 }
175 }();
176 if (!created) {
177 return std::unexpected(created.error());
178 }
179 output = std::shared_ptr<Property<Out>>(std::move(*created));
180 return {};
181 });
182 } catch (const std::bad_alloc &) {
183 computed = std::unexpected(TreeError::NO_MEMORY);
184 } catch (...) {
185 computed = std::unexpected(TreeError::CALLBACK_FAILED);
186 }
187 }
188 if (record->shortFailure) {
189 return std::unexpected(*record->shortFailure);
190 }
191 if (!computed) {
192 return failure(computed.error());
193 }
194
195 prepareObserverRecord(
196 record, *source,
197 [this, callable, output = std::weak_ptr(output)](
198 const In &value, const std::shared_ptr<ObserverRecord> &entered) -> std::expected<void, TreeError> {
199 auto locked = output.lock();
200 if (!locked) {
201 return std::unexpected(TreeError::CLOSED);
202 }
203 return (*callable)(value, entered, [&](Out &candidate) -> std::expected<void, TreeError> {
204 auto live = observerLive(entered);
205
206 if (!live || !*live) {
207 return live ? std::expected<void, TreeError>{} : std::unexpected(live.error());
208 }
209
210 auto changed = [&] {
211 if constexpr (std::same_as<Out, std::string>) {
212 return locked->set(std::as_const(candidate));
213 } else {
214 return locked->set(std::move(candidate));
215 }
216 }();
217 // Notification rejection is postcommit; downstream records recover their current snapshots.
218 return changed ? std::expected<void, TreeError>{} : std::unexpected(changed.error());
219 });
220 });
221
222 allowed = admission();
223 source = input.lock();
224 if (!allowed) {
225 return std::unexpected(allowed.error());
226 }
227 if (!source) {
228 return failure(source.error(), "derive.register");
229 }
230 auto current = (*source)->snapshot();
231 if (!current) {
232 return failure(current.error());
233 }
234 if ((*current)->revision != (*initial)->revision) {
235 return failure(TreeError::WOULD_BLOCK);
236 }
237 properties_.reserve(properties_.size() + 1);
238 observers_.reserve(observers_.size() + 1);
239 auto token = connectObserverRecord(root_, *source, record);
240 if (!token) {
241 return failure(token.error(), "derive.register");
242 }
243 auto dirty = app_.tree().invalidate(root_, Invalidation::PAINT);
244 if (!dirty) {
245 return failure(dirty.error(), "derive.register");
246 }
247
248 ManagedState<Out> handle;
249 handle.model_ = output;
250 handle.facade_ = facade_;
251 handle.lifetime_ = lifetime_;
252 handle.owner_ = owner_;
253 handle.scene_ = root_.id();
254 handle.origin_ = rowOrigin_;
255 handle.recoveryOrigin_ = record->recoveryOrigin;
256 record->subscription = std::move(*token);
257 record->successful = (*initial)->revision;
258 record->initialPending = false;
259 record->runtime = true;
260 ownRowProperty(output);
261 properties_.push_back(std::move(output));
262 observers_.push_back(std::move(record));
263 return ManagedSource<Out>(std::move(handle));
264 } catch (const std::bad_alloc &) {
265 return failure(TreeError::NO_MEMORY);
266 } catch (...) {
267 return failure(TreeError::CALLBACK_FAILED);
268 }
269}
270} // namespace portals
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< bool, TreeError > input(Application &app, const InputEvent &event) override
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
Copyable typed observer; never owns or exposes an unchecked widget pointer.
Definition widget.hpp:92
UI-owned typed value with node-scoped observers and explicit partial delivery. WidgetTree and its Sch...
Definition property.hpp:62
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
Allocation-free UI execution publication; an empty scope suspends the caller's scene.
Definition current_scene.hpp:37
Allocation-free current-thread setup context; nested independent scopes restore their parent.
Definition setup_failure.hpp:57
Reject known borrowed outputs; arbitrary user values still satisfy Property's owning contract.
Definition managed.hpp:312
auto live(ManagedScene &scene, const S &description)
Definition style_static.hpp:1703
Public Portals API.
Definition action.hpp:8
@ STATE
Create and retain a scene-owned property.
Definition managed_diagnostics.hpp:50
@ INPUT
Dispatch input or deliver a managed control/property callback.
Definition managed_diagnostics.hpp:54
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
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
@ WOULD_BLOCK
The current frame/reentry boundary or finite queue/work budget rejects this operation.
Definition widget_types.hpp:32
@ 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
Original error plus independent runner/restoration and cleanup failures.
Definition managed_diagnostics.hpp:62
Finite observer endpoint storage, independent of Scheduler queue capacity.
Definition property.hpp:28
std::size_t max_observers
Maximum live or executing observers; must be positive.
Definition property.hpp:29