Portals0.7.0 · dev (544a5c68c72e · 2026-11-28 UTC)
Loading...
Searching...
No Matches
property.hpp
1// Copyright (c) 2026 ttldtor.
2// SPDX-License-Identifier: BSL-1.0
3#pragma once
4
5#include <portals/widget.hpp>
6
7#include <algorithm>
8#include <limits>
9#include <optional>
10#include <thread>
11#include <utility>
12
13namespace portals {
14namespace detail {
15struct ManagedNavigationRecord;
16}
17
22template <class T> struct PropertyChange {
24 std::uint64_t revision{};
25};
26
29 std::size_t max_observers{64};
30};
31
38template <class T> struct PropertyUpdate {
39 std::shared_ptr<const PropertyChange<T>> snapshot;
40 bool changed{};
41 std::size_t accepted{};
42 std::size_t rejected{};
43 std::size_t cancelled{};
44 std::optional<SchedulerError> notification_error{};
45};
46
62template <std::equality_comparable T> class Property {
63public:
75 static std::expected<std::unique_ptr<Property>, TreeError>
76 create(WidgetTree &tree, Node<Widget> target, const T &initial, Invalidation kind, PropertyOptions options = {}) {
77 return createImpl(tree, target, initial, kind, options);
78 }
79
91 static std::expected<std::unique_ptr<Property>, TreeError> create(WidgetTree &tree, Node<Widget> target, T &&initial,
92 Invalidation kind, PropertyOptions options = {}) {
93 return createImpl(tree, target, std::move(initial), kind, options);
94 }
95
102 if (state_->owner != std::this_thread::get_id()) {
103 std::terminate();
104 }
105
106 state_->alive = false;
107 }
108
109 Property(const Property &) = delete;
110 Property &operator=(const Property &) = delete;
111
117 std::expected<std::shared_ptr<const PropertyChange<T>>, TreeError> snapshot() const {
118 if (state_->owner != std::this_thread::get_id()) {
119 return std::unexpected(TreeError::WRONG_THREAD);
120 }
121
122 return state_->current;
123 }
124
136 std::expected<PropertyUpdate<T>, TreeError> set(const T &value) {
137 return setImpl(value);
138 }
139
148 std::expected<PropertyUpdate<T>, TreeError> set(T &&value) {
149 return setImpl(std::move(value));
150 }
151
169 template <class W, class Callback>
170 std::expected<Subscription, TreeError> observe(Node<W> receiver, Callback &&callback) {
171 auto state = state_;
172
173 if (state->owner != std::this_thread::get_id()) {
174 return std::unexpected(TreeError::WRONG_THREAD);
175 }
176
177 auto allowed = state->tree.withScope(receiver, [](const UiScope &) {
178 });
179
180 if (!allowed) {
181 return std::unexpected(allowed.error());
182 }
183
184 state->prune();
185
186 if (state->observers.size() >= state->limit) {
187 return std::unexpected(TreeError::NODE_LIMIT);
188 }
189
190 try {
191 auto lifetime = std::make_shared<Lifetime>();
192 auto connection = state->tree.template connect<PropertyChange<T>>(
193 receiver, [source = std::weak_ptr<State>(state), lifetime, function = std::forward<Callback>(callback)](
194 W &widget, std::shared_ptr<const PropertyChange<T>> event) mutable {
195 auto locked = source.lock();
196
197 if (locked && locked->alive) {
198 std::invoke(function, widget, std::move(event));
199 }
200 });
201
202 if (!connection) {
203 return std::unexpected(connection.error());
204 }
205
206 // Moved-from callback destructors can reenter while connect materializes its captures.
207 if (!state->alive) {
208 return std::unexpected(TreeError::CLOSED);
209 }
210
211 state->prune();
212
213 if (state->observers.size() >= state->limit) {
214 return std::unexpected(TreeError::NODE_LIMIT);
215 }
216
217 state->observers.push_back(Observer{std::move(connection->publisher), lifetime});
218
219 return std::move(connection->subscription);
220 } catch (const std::bad_alloc &) {
221 return std::unexpected(TreeError::NO_MEMORY);
222 } catch (...) {
223 return std::unexpected(TreeError::CALLBACK_FAILED);
224 }
225 }
226
227private:
237 template <class Value>
238 static std::expected<std::unique_ptr<Property>, TreeError>
239 createImpl(WidgetTree &tree, Node<Widget> target, Value &&initial, Invalidation kind, PropertyOptions options) {
240 auto allowed = tree.withScope(target, [](const UiScope &) {
241 });
242
243 if (!allowed) {
244 return std::unexpected(allowed.error());
245 }
246
247 if (!options.max_observers ||
248 (kind != Invalidation::NONE && kind != Invalidation::PAINT && kind != Invalidation::LAYOUT)) {
249 return std::unexpected(TreeError::INVALID_ARGUMENT);
250 }
251
252 try {
253 auto state = std::make_shared<State>(tree, target, kind);
254
255 if (options.max_observers > state->observers.max_size()) {
256 return std::unexpected(TreeError::INVALID_ARGUMENT);
257 }
258
259 state->observers.reserve(options.max_observers);
260 state->limit = options.max_observers;
261 state->current = std::make_shared<const PropertyChange<T>>(std::forward<Value>(initial), 0);
262
263 return std::unique_ptr<Property>(new Property(std::move(state)));
264 } catch (const std::bad_alloc &) {
265 return std::unexpected(TreeError::NO_MEMORY);
266 } catch (...) {
267 return std::unexpected(TreeError::CALLBACK_FAILED);
268 }
269 }
270
271 friend struct detail::ManagedNavigationRecord;
272
273 struct State;
274
275 // SDK navigation groups reuse these private phases. No public batch operation or
276 // additional per-property state is introduced.
277 struct PreparedChange {
278 std::shared_ptr<State> state;
279 std::shared_ptr<const PropertyChange<T>> previous;
280 std::shared_ptr<const PropertyChange<T>> next;
281 bool changed{};
282 };
283
284 template <class Value> std::expected<PreparedChange, TreeError> prepareChange(Value &&value) {
285 auto state = state_;
286
287 if (state->owner != std::this_thread::get_id()) {
288 return std::unexpected(TreeError::WRONG_THREAD);
289 }
290
291 auto allowed = state->tree.withScope(state->target, [](const UiScope &) {
292 });
293
294 if (!allowed) {
295 return std::unexpected(allowed.error());
296 }
297
298 auto previous = state->current;
299
300 try {
301 if (previous->value == value) {
302 if (auto *recorder = state->tree.diagnostics(); recorder && recorder->enabled()) {
303 const auto id = state->target.id();
304
306 {id.session, id.slot, id.generation});
307 }
308
309 return PreparedChange{state, previous, previous, false};
310 }
311
312 if (previous->revision == std::numeric_limits<std::uint64_t>::max()) {
313 return std::unexpected(TreeError::IDENTITY_EXHAUSTED);
314 }
315
316 auto next = std::make_shared<const PropertyChange<T>>(std::forward<Value>(value), previous->revision + 1);
317
318 return PreparedChange{state, previous, std::move(next), true};
319 } catch (const std::bad_alloc &) {
320 return std::unexpected(TreeError::NO_MEMORY);
321 } catch (...) {
322 return std::unexpected(TreeError::CALLBACK_FAILED);
323 }
324 }
325
326 static std::expected<void, TreeError> validateChange(const PreparedChange &change) {
327 const auto &state = change.state;
328
329 if (state->owner != std::this_thread::get_id()) {
330 return std::unexpected(TreeError::WRONG_THREAD);
331 }
332 if (!state->alive) {
333 return std::unexpected(TreeError::CLOSED);
334 }
335 if (state->current != change.previous) {
336 return std::unexpected(TreeError::WOULD_BLOCK);
337 }
338
339 return state->tree.withScope(state->target, [](const UiScope &) {
340 });
341 }
342
343 static std::expected<void, TreeError> invalidateChange(const PreparedChange &change) {
344 return change.changed ? change.state->tree.invalidate(change.state->target, change.state->kind)
345 : std::expected<void, TreeError>{};
346 }
347
348 static void installChange(const PreparedChange &change) noexcept {
349 if (change.changed) {
350 // previous pins the retired value through the complete group installation/publication.
351 change.state->current = change.next;
352 }
353 }
354
355 static PropertyUpdate<T> publishChange(const PreparedChange &change) {
356 if (!change.changed) {
357 return PropertyUpdate<T>{change.previous};
358 }
359
360 const auto &state = change.state;
361 const auto &next = change.next;
362
363 if (auto *recorder = state->tree.diagnostics(); recorder && recorder->enabled()) {
364 const auto id = state->target.id();
365
366 recorder->note(DiagnosticEvent::PROPERTY, DiagnosticReason::VALUE_CHANGED, {id.session, id.slot, id.generation});
367 }
368
369 state->prune();
370
371 PropertyUpdate<T> result{next, true};
372
373 for (auto &observer : state->observers) {
374 auto published = observer.publisher.publish(next);
375
376 if (published) {
377 ++result.accepted;
378 } else {
379 if (!result.notification_error) {
380 result.notification_error = published.error();
381 }
382
383 if (published.error() == SchedulerError::CLOSED) {
384 ++result.cancelled;
385 } else {
386 ++result.rejected;
387 }
388 }
389 }
390
391 state->prune();
392
393 return result;
394 }
395
397 template <class Value> std::expected<PropertyUpdate<T>, TreeError> setImpl(Value &&value) {
398 auto change = prepareChange(std::forward<Value>(value));
399
400 if (!change) {
401 return std::unexpected(change.error());
402 }
403
404 auto invalidated = invalidateChange(*change);
405
406 if (!invalidated) {
407 return std::unexpected(invalidated.error());
408 }
409
410 installChange(*change);
411
412 return publishChange(*change);
413 }
414
415 struct Lifetime {};
416
417 struct Observer {
418 Publisher<PropertyChange<T>> publisher;
419 std::weak_ptr<Lifetime> lifetime;
420 };
421
422 struct State {
423 State(WidgetTree &value, Node<Widget> node, Invalidation invalidation)
424 : tree(value), target(node), kind(invalidation) {
425 }
426
427 void prune() {
428 std::erase_if(observers, [](const Observer &observer) {
429 return observer.lifetime.expired();
430 });
431 }
432
433 WidgetTree &tree;
434 Node<Widget> target;
435 Invalidation kind;
436 const std::thread::id owner{std::this_thread::get_id()};
437 bool alive{true};
438 std::size_t limit{};
439 std::shared_ptr<const PropertyChange<T>> current;
440 std::vector<Observer> observers = std::vector<Observer>(0);
441 };
442
443 explicit Property(std::shared_ptr<State> state) : state_(std::move(state)) {
444 }
445
446 std::shared_ptr<State> state_;
447};
448} // namespace portals
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
~Property()
Logically close the source; executing callbacks retain their captures until return....
Definition property.hpp:101
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
std::expected< Subscription, TreeError > observe(Node< W > receiver, Callback &&callback)
Register an ordinary Subscription tied to a receiving node in the same tree. The callback owns its ca...
Definition property.hpp:170
std::expected< PropertyUpdate< T >, TreeError > set(const T &value)
Commit a changed value and invalidate its target before attempting notifications. unexpected means no...
Definition property.hpp:136
static std::expected< std::unique_ptr< Property >, TreeError > create(WidgetTree &tree, Node< Widget > target, T &&initial, Invalidation kind, PropertyOptions options={})
Create a source by moving its initial value directly into the snapshot. Validation and lifetime match...
Definition property.hpp:91
std::expected< PropertyUpdate< T >, TreeError > set(T &&value)
Commit a candidate by moving it directly into the immutable snapshot. Commit and notification semanti...
Definition property.hpp:148
std::expected< std::shared_ptr< const PropertyChange< T > >, TreeError > snapshot() const
Obtain an independent immutable owner, even after the target node was removed. Access on another thre...
Definition property.hpp:117
UI-owned scope disconnecting all its subscriptions and timers, in any token order....
Definition scheduler.hpp:154
Exclusive parent/child ownership on Scheduler's UI thread. Scheduler must outlive this object....
Definition widget.hpp:179
std::expected< void, TreeError > withScope(Node< Widget > node, Callback &&callback)
Borrow the node-owned scope for registration with the existing Scheduler. Registrations borrowing wid...
Definition widget.hpp:340
auto change(T value)
Definition style_static.hpp:1496
Public Portals API.
Definition action.hpp:8
@ CLOSED
Scheduler, scope, registration or endpoint is closed.
Definition scheduler.hpp:24
@ VALUE_UNCHANGED
An observed Property comparison was equal.
Definition diagnostics.hpp:50
@ VALUE_CHANGED
An observed Property commit or tree work change occurred.
Definition diagnostics.hpp:51
@ PROPERTY
Observed equality or committed property change.
Definition diagnostics.hpp:28
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
@ NONE
No new work requested.
Definition widget_types.hpp:42
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
@ WOULD_BLOCK
The current frame/reentry boundary or finite queue/work budget rejects this operation.
Definition widget_types.hpp:32
@ IDENTITY_EXHAUSTED
A session, generation or revision cannot advance without reuse.
Definition widget_types.hpp:34
@ 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
Immutable owning value/revision pair; revision zero is the initial value. T must own its data transit...
Definition property.hpp:22
T value
Value captured at this revision, independent of the source lifetime.
Definition property.hpp:23
std::uint64_t revision
Monotonic revision within this property, never wrapped.
Definition property.hpp:24
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
A successful set result; notification rejection does not undo the committed value....
Definition property.hpp:38
std::size_t cancelled
Endpoints found closed during publication.
Definition property.hpp:43
std::size_t rejected
Live endpoints whose publication was rejected.
Definition property.hpp:42
std::shared_ptr< const PropertyChange< T > > snapshot
Owning snapshot of this operation's revision.
Definition property.hpp:39
bool changed
False means all publication counts are zero.
Definition property.hpp:40
std::size_t accepted
Events accepted by the existing Scheduler.
Definition property.hpp:41
std::optional< SchedulerError > notification_error
First publication failure, including closed.
Definition property.hpp:44