Portals0.7.0 · dev (544a5c68c72e · 2026-11-28 UTC)
Loading...
Searching...
No Matches
ui_model.hpp
1// Copyright (c) 2026 ttldtor.
2// SPDX-License-Identifier: BSL-1.0
3#pragma once
4
5#include <portals/collection.hpp>
6#include <portals/detail/ui_model_sequence.hpp>
7#include <portals/text_format.hpp>
8#include <portals/ui_description.hpp>
9
10#include <array>
11
12namespace portals::ui {
13template <class T> class Model;
14template <class T> class Navigation;
15template <class T> class ModelValue;
16template <class T, class Member> class ModelField;
17
18namespace detail {
20struct ModelAccess;
21struct ValueModelAccess;
22struct EditAccess;
23
24inline void captureRowDeclarationOrigin(RefTarget &observation) {
25 const auto *scope = RowDeclarationOriginScope::current;
26 if (scope && scope->origin) {
27 // Prepublication observation fields carry only a weak construction owner.
28 observation.node = scope->origin->node;
29 observation.lifetime = scope->origin;
30 }
31}
32
33struct ModelDeclarationBase {
34 enum class Kind {
35 COLLECTION,
36 VALUE,
37 VALUE_ALIAS,
38 VALUE_SOURCE,
39 VALUE_DEFERRED_SOURCE
40 };
41
42 explicit ModelDeclarationBase(Kind value) : observation(std::make_shared<RefTarget>()), kind(value) {
43 captureRowDeclarationOrigin(*observation);
44 }
45
46 std::shared_ptr<RefTarget> observation;
47 NodeId scene;
48 const MountContext *attempt{};
49 bool published{};
50 bool resolving{};
51 const Kind kind;
52};
53
54struct ModelDeclarationOriginScope {
55 ModelDeclarationOriginScope(ManagedScene &owner, const RefTarget &observation)
56 : scene(owner), lifetime(Access::lifetime(owner)) {
57 if (observation.node != Node<Widget>{}) {
58 auto retained = observation.lifetime.lock();
59 if (!retained) {
60 failure = TreeError::CLOSED;
61 return;
62 }
63 auto origin = std::const_pointer_cast<portals::detail::ManagedOrigin>(
64 std::static_pointer_cast<const portals::detail::ManagedOrigin>(retained));
65 auto valid = Access::validateModelOrigin(scene, origin);
66 if (!valid) {
67 failure = valid.error();
68 return;
69 }
70 declarations.origin = std::move(origin);
71 }
72 previous = Access::exchangeModelOrigin(scene, declarations.origin);
73 shifted = true;
74 }
75
76 ~ModelDeclarationOriginScope() {
77 if (shifted && !lifetime.expired()) {
78 (void)Access::exchangeModelOrigin(scene, std::move(previous));
79 }
80 }
81
82 ManagedScene &scene;
83 std::weak_ptr<const void> lifetime;
84 RowDeclarationOriginScope declarations;
85 std::shared_ptr<portals::detail::ManagedOrigin> previous;
86 std::optional<TreeError> failure;
87 bool shifted{};
88};
89
90template <class T> struct ModelDeclaration : ModelDeclarationBase {
91 using Factory = std::function<std::expected<std::shared_ptr<const ModelSnapshot<T>>, TreeError>()>;
92
93 ModelDeclaration() : ModelDeclarationBase(Kind::COLLECTION) {
94 }
95
96 Factory create;
97 ModelOptions options;
98 ManagedViewHandler<T> prepared;
99 ManagedModel<T> handle;
100 std::shared_ptr<OwnedSequence<T>> sequence;
101};
102
103template <class T> struct NavigationDeclaration {
104 explicit NavigationDeclaration(Model<T> value)
105 : initial(std::move(value)), observation(std::make_shared<RefTarget>()) {
106 captureRowDeclarationOrigin(*observation);
107 }
108
109 Model<T> initial;
110 NavigationBindingOptions binding;
111 NavigationOptions options;
112 std::shared_ptr<RefTarget> observation;
113 ManagedNavigation handle;
114 NodeId scene;
115 const MountContext *attempt{};
116 bool published{};
117 bool resolving{};
118};
119
121} // namespace detail
122
129template <class T> class Model {
130public:
131 using Row = T;
133 Model() = default;
134
138 std::expected<ManagedModel<T>, ManagedError> managed() const {
139 if (!data_ || data_->kind != detail::ModelDeclarationBase::Kind::COLLECTION) {
140 return std::unexpected(ManagedError{ManagedPhase::STATE, {}, failure_, {}, {}});
141 }
142 if (data_->observation->owner != std::this_thread::get_id()) {
143 return std::unexpected(ManagedError{ManagedPhase::STATE, {}, TreeError::WRONG_THREAD, {}, {}});
144 }
145 if (!data_->published) {
146 return std::unexpected(ManagedError{ManagedPhase::STATE, {}, TreeError::CLOSED, {}, {}});
147 }
148 auto owner = detail::eventScene(data_->observation);
149 if (!owner) {
150 return std::unexpected(owner.error());
151 }
152 if (detail::Access::modelSceneClosed(**owner)) {
153 return std::unexpected(ManagedError{ManagedPhase::STATE, {}, TreeError::CLOSED, {}, {}});
154 }
155 return std::static_pointer_cast<detail::ModelDeclaration<T>>(data_)->handle;
156 }
157
163 ModelValue<T> value(std::source_location origin = std::source_location::current()) const
164 requires std::equality_comparable<T>;
165
175 template <class Member, class Record>
176 requires std::same_as<Record, T> && std::equality_comparable<T> && std::copy_constructible<T> &&
177 std::copy_constructible<std::remove_cv_t<Member>> && (!std::is_array_v<Member>) &&
178 (!std::is_pointer_v<Member>) && (!portals::detail::IS_BORROWED_DERIVED_VALUE<std::remove_cv_t<Member>>) &&
179 (!std::ranges::view<std::remove_cv_t<Member>>)
180 ModelField<T, Member> field(Member Record::*member,
181 std::source_location origin = std::source_location::current()) const;
182
189 std::expected<void, ManagedError> insert(std::uint64_t index, const T &value) const;
197 std::expected<void, ManagedError> update(RowId id, const T &value) const;
204 bool row(RowId id, const T &value, std::source_location origin = std::source_location::current()) const;
210 std::expected<void, ManagedError> erase(std::uint64_t first, std::uint64_t count = 1) const;
217 std::expected<void, ManagedError> move(std::uint64_t first, std::uint64_t count, std::uint64_t destination) const;
222 std::expected<void, ManagedError> clear() const;
223
224private:
225 friend struct detail::ModelAccess;
226 friend struct detail::EditAccess;
227 friend struct detail::ValueModelAccess;
228 template <class> friend class ModelValue;
229 template <class, class> friend class ModelField;
230 std::shared_ptr<detail::ModelDeclarationBase> data_;
232
233 struct Replacement {
234 RowId id;
235 const T &value;
236 std::optional<std::uint64_t> expectedVersion;
237 std::uint64_t *acceptedVersion{};
238 };
239
240 template <class Build>
241 std::expected<void, ManagedError> mutate(PositionChange change, bool inserts, Build build,
242 const Replacement *replacement = nullptr) const;
243};
244
248template <class T> class Navigation {
249public:
250 using Row = T;
252 Navigation() = default;
253
257 std::expected<ManagedNavigation, ManagedError> managed() const {
258 if (!data_) {
259 return std::unexpected(ManagedError{ManagedPhase::STATE, {}, failure_, {}, {}});
260 }
261 auto owner = detail::eventScene(data_->observation);
262 if (!owner) {
263 return std::unexpected(owner.error());
264 }
265 if (detail::Access::modelSceneClosed(**owner)) {
266 return std::unexpected(ManagedError{ManagedPhase::STATE, {}, TreeError::CLOSED, {}, {}});
267 }
268 return data_->handle;
269 }
270
276 std::expected<std::optional<RowId>, ManagedError> currentRow() const {
277 auto context = managed();
278
279 if (!context) {
280 return std::unexpected(context.error());
281 }
282
283 auto fail = [&](TreeError error) {
284 return std::unexpected(ManagedError{ManagedPhase::STATE, data_->observation->node.id(), error, {}, {}});
285 };
286 auto channel = context->current();
287
288 if (!channel) {
289 return fail(channel.error());
290 }
291
292 auto value = channel->snapshot();
293
294 if (!value) {
295 return fail(value.error());
296 }
297
298 return (*value)->value.row;
299 }
300
305 Model<NavigationPosition> current() const;
306
312 std::expected<void, ManagedError> setModel(Model<T> target, ModelRebindOptions options = {}) const;
313
320 bool model(Model<T> target, ModelRebindOptions options = {},
321 std::source_location origin = std::source_location::current()) const {
322 const auto observation = data_ ? data_->observation : nullptr;
323 auto result = setModel(std::move(target), options);
324 if (!result) {
325 detail::reportEventError(observation, result.error(), origin);
326 }
327 return static_cast<bool>(result);
328 }
329
330private:
331 friend struct detail::ModelAccess;
332 friend struct detail::EditAccess;
333 std::shared_ptr<detail::NavigationDeclaration<T>> data_;
334 TreeError failure_{TreeError::INVALID_ARGUMENT};
335};
336
337namespace detail {
339struct ModelAccess {
340 template <class T> static NavigationBindingOptions bindings(const Navigation<T> &value) {
341 return value.data_ ? value.data_->binding : NavigationBindingOptions{};
342 }
343
344 struct RegisteredSource {
345 NodeId scene;
346 ModelResource resource;
347 };
348
349 // The pure projection may run before descriptor publication in the same mount transaction.
350 // Inspect only an already registered handle; never resolve/register a cold catalog entry here.
351 template <class T>
352 static std::expected<std::optional<RegisteredSource>, TreeError> registeredSource(const Model<T> &model) {
353 const auto base = model.data_;
354 if (!base) {
355 return std::unexpected(model.failure_);
356 }
357 if (base->kind != ModelDeclarationBase::Kind::COLLECTION) {
358 return std::unexpected(TreeError::INVALID_ARGUMENT);
359 }
360 if (base->observation->owner != std::this_thread::get_id()) {
361 return std::unexpected(TreeError::WRONG_THREAD);
362 }
363 if (base->scene == NodeId{}) {
364 return std::optional<RegisteredSource>{};
365 }
366
367 const auto data = std::static_pointer_cast<ModelDeclaration<T>>(base);
368 auto resource = Access::registeredModelResource(data->handle);
369 if (!resource) {
370 return std::unexpected(resource.error());
371 }
372
373 return std::optional(RegisteredSource{base->scene, *resource});
374 }
375
376 template <class T> static std::shared_ptr<void> identity(const Model<T> &model) {
377 return model.data_;
378 }
379
380 template <class T>
381 static std::expected<std::optional<ManagedModel<T>>, ManagedError> existing(ManagedScene &scene,
382 const Model<T> &value) {
383 auto base = value.data_;
384 auto data = base && base->kind == ModelDeclarationBase::Kind::COLLECTION
385 ? std::static_pointer_cast<ModelDeclaration<T>>(base)
386 : nullptr;
387 const auto fail = [&](TreeError error) {
388 return std::unexpected(ManagedError{ManagedPhase::STATE, scene.root().id(), error, {}, {}});
389 };
390 if (Access::modelSceneClosed(scene)) {
391 return fail(TreeError::CLOSED);
392 }
393 if (!data) {
394 return fail(value.failure_);
395 }
396 if (data->observation->owner != std::this_thread::get_id()) {
397 return fail(TreeError::WRONG_THREAD);
398 }
399 if (data->scene != NodeId{} && data->scene != scene.root().id()) {
400 return fail(TreeError::WRONG_SESSION);
401 }
402 if (data->resolving || (!data->published && data->attempt)) {
403 return fail(TreeError::WOULD_BLOCK);
404 }
405 if (!data->published) {
406 return std::optional<ManagedModel<T>>{};
407 }
408 auto handle = value.managed();
409 return handle ? std::expected<std::optional<ManagedModel<T>>, ManagedError>(std::optional(*handle))
410 : std::unexpected(handle.error());
411 }
412
413 template <class W> static void keep(ManagedScene &scene, Node<W> node, MountContext &context) {
414 try {
415 context.rollback.emplace_back([&scene, node, lifetime = Access::lifetime(scene)] {
416 if (!lifetime.expired()) {
417 (void)scene.remove(node);
418 }
419 });
420 } catch (...) {
421 (void)scene.remove(node);
422 throw;
423 }
424 }
425
426 template <class T> static Model<T> make(std::shared_ptr<ModelDeclaration<T>> value) {
427 Model<T> result;
428 result.data_ = std::move(value);
429 return result;
430 }
431
432 template <class T> static Model<T> failed(TreeError error) {
433 Model<T> result;
434 result.failure_ = error;
435 return result;
436 }
437
438 template <class T> static Navigation<T> make(std::shared_ptr<NavigationDeclaration<T>> value) {
439 Navigation<T> result;
440 result.data_ = std::move(value);
441 return result;
442 }
443
444 template <class T> static Navigation<T> failedNavigation(TreeError error) {
445 Navigation<T> result;
446 result.failure_ = error;
447 return result;
448 }
449
450 static void publish(MountContext &context) {
451 context.committed = true;
452 for (auto &action : context.publish) {
453 action();
454 }
455 }
456
457 template <class T>
458 static std::expected<ManagedModel<T>, ManagedError> resolve(ManagedScene &scene, const Model<T> &value,
459 MountContext &context) {
460 auto base = value.data_;
461 auto data = base && base->kind == ModelDeclarationBase::Kind::COLLECTION
462 ? std::static_pointer_cast<ModelDeclaration<T>>(base)
463 : nullptr;
464 const auto root = scene.root();
465 const auto lifetime = Access::lifetime(scene);
466 const auto fail = [&](TreeError error) {
467 return std::unexpected(ManagedError{ManagedPhase::STATE, root.id(), error, {}, {}});
468 };
469 if (Access::modelSceneClosed(scene)) {
470 return fail(TreeError::CLOSED);
471 }
472 if (!data) {
473 return fail(value.failure_);
474 }
475 if (data->observation->owner != std::this_thread::get_id()) {
476 return fail(TreeError::WRONG_THREAD);
477 }
478 if (data->resolving) {
479 return fail(TreeError::WOULD_BLOCK);
480 }
481 if (data->scene != NodeId{}) {
482 if (data->scene != scene.root().id()) {
483 return fail(TreeError::WRONG_SESSION);
484 }
485 if (data->published) {
486 return value.managed();
487 }
488 return data->attempt == &context ? std::expected<ManagedModel<T>, ManagedError>(data->handle)
489 : std::expected<ManagedModel<T>, ManagedError>(fail(TreeError::WOULD_BLOCK));
490 }
491
492 ModelDeclarationOriginScope ownership(scene, *data->observation);
493 if (ownership.failure) {
494 return fail(*ownership.failure);
495 }
496
497 struct Resolving {
498 bool &active;
499
500 ~Resolving() {
501 active = false;
502 }
503 } guard{data->resolving};
504
505 data->resolving = true;
506 try {
507 auto initial = data->create();
508 if (!initial) {
509 return fail(initial.error());
510 }
511 if (lifetime.expired()) {
512 return fail(TreeError::CLOSED);
513 }
514 // User callable copies are callouts too. Finish that copy and validate
515 // lifetime before entering a method through the borrowed scene pointer.
516 auto prepared = data->prepared;
517 if (lifetime.expired()) {
518 return fail(TreeError::CLOSED);
519 }
520 auto created = scene.model<T>(std::move(*initial), data->options, std::move(prepared));
521 if (!created) {
522 return std::unexpected(created.error());
523 }
524 if (lifetime.expired()) {
525 return fail(TreeError::CLOSED);
526 }
527 Access::editDeclaration(*created, data);
528 if (data->sequence) {
529 Access::ownedModel(*created);
530 }
531 bool rollbackInstalled{};
532 try {
533 context.rollback.emplace_back([&scene, data, lifetime, handle = *created] {
534 if (!lifetime.expired()) {
535 auto copy = handle;
536 Access::retireChoiceModel(scene, copy);
537 }
538 data->handle = {};
539 data->scene = {};
540 data->attempt = nullptr;
541 });
542 rollbackInstalled = true;
543 context.publish.emplace_back([&scene, data, root, lifetime] {
544 data->observation->scene = &scene;
545 data->observation->lifetime = lifetime;
546 data->observation->node = root;
547 data->attempt = nullptr;
548 data->published = true;
549 });
550 } catch (...) {
551 if (!rollbackInstalled) {
552 auto copy = *created;
553 Access::retireChoiceModel(scene, copy);
554 }
555 throw;
556 }
557 data->handle = *created;
558 data->scene = scene.root().id();
559 data->attempt = &context;
560 return *created;
561 } catch (const std::bad_alloc &) {
562 return fail(lifetime.expired() ? TreeError::CLOSED : TreeError::NO_MEMORY);
563 } catch (...) {
564 return fail(lifetime.expired() ? TreeError::CLOSED : TreeError::CALLBACK_FAILED);
565 }
566 }
567
568 template <class T>
569 static std::expected<ManagedNavigation, ManagedError> resolve(ManagedScene &scene, const Navigation<T> &value,
570 MountContext &context) {
571 auto data = value.data_;
572 const auto root = scene.root();
573 const auto lifetime = Access::lifetime(scene);
574 const auto fail = [&](TreeError error) {
575 return std::unexpected(ManagedError{ManagedPhase::STATE, root.id(), error, {}, {}});
576 };
577 if (Access::modelSceneClosed(scene)) {
578 return fail(TreeError::CLOSED);
579 }
580 if (!data) {
581 return fail(value.failure_);
582 }
583 if (data->observation->owner != std::this_thread::get_id()) {
584 return fail(TreeError::WRONG_THREAD);
585 }
586 if (data->resolving) {
587 return fail(TreeError::WOULD_BLOCK);
588 }
589 if (data->scene != NodeId{}) {
590 if (data->scene != scene.root().id()) {
591 return fail(TreeError::WRONG_SESSION);
592 }
593 if (data->published) {
594 return value.managed();
595 }
596 return data->attempt == &context ? std::expected<ManagedNavigation, ManagedError>(data->handle)
597 : std::expected<ManagedNavigation, ManagedError>(fail(TreeError::WOULD_BLOCK));
598 }
599
600 ModelDeclarationOriginScope ownership(scene, *data->observation);
601 if (ownership.failure) {
602 return fail(*ownership.failure);
603 }
604
605 struct Resolving {
606 bool &active;
607
608 ~Resolving() {
609 active = false;
610 }
611 } guard{data->resolving};
612
613 data->resolving = true;
614 auto model = resolve(scene, data->initial, context);
615 if (!model) {
616 return std::unexpected(model.error());
617 }
618 auto created = scene.navigation(*model, data->options);
619 if (!created) {
620 return std::unexpected(created.error());
621 }
622 try {
623 context.rollback.emplace_back([&scene, data, lifetime, handle = *created] {
624 if (!lifetime.expired()) {
625 Access::retireColdNavigation(scene, handle);
626 }
627 data->handle = {};
628 data->scene = {};
629 data->attempt = nullptr;
630 });
631 } catch (const std::bad_alloc &) {
632 Access::retireColdNavigation(scene, *created);
633 return fail(TreeError::NO_MEMORY);
634 } catch (...) {
635 Access::retireColdNavigation(scene, *created);
636 return fail(TreeError::CALLBACK_FAILED);
637 }
638 try {
639 context.publish.emplace_back([&scene, data, root, lifetime] {
640 data->observation->scene = &scene;
641 data->observation->lifetime = lifetime;
642 data->observation->node = root;
643 data->attempt = nullptr;
644 data->published = true;
645 });
646 } catch (const std::bad_alloc &) {
647 return fail(TreeError::NO_MEMORY);
648 } catch (...) {
649 return fail(TreeError::CALLBACK_FAILED);
650 }
651 data->handle = *created;
652 data->scene = scene.root().id();
653 data->attempt = &context;
654 return *created;
655 }
656
657 template <class T>
658 static std::expected<ManagedModel<T>, ManagedError> source(ManagedScene &scene, const Model<T> &value,
659 MountContext &context) {
660 return resolve(scene, value, context);
661 }
662
663 template <class T>
664 static std::expected<ManagedModel<T>, ManagedError> source(ManagedScene &scene, const Navigation<T> &value,
665 MountContext &context) {
666 auto navigation = resolve(scene, value, context);
667 return navigation ? Access::navigationModel<T>(scene, *navigation) : std::unexpected(navigation.error());
668 }
669
670 template <class T, class W>
671 static std::expected<void, ManagedError> bind(ManagedScene &, Node<W>, const Model<T> &, MountContext &) {
672 return {};
673 }
674
675 template <class T, class W>
676 static std::expected<void, ManagedError> bind(ManagedScene &scene, Node<W> node, const Navigation<T> &value,
677 MountContext &context) {
678 auto navigation = resolve(scene, value, context);
679 return navigation ? scene.bindNavigation(node, *navigation, value.data_->binding)
680 : std::unexpected(navigation.error());
681 }
682};
683
685} // namespace detail
686
694template <class T>
695Model<T> model(std::shared_ptr<const ModelSnapshot<T>> provider, ModelOptions options = {},
696 ManagedViewHandler<T> prepared = {}) {
697 try {
698 auto data = std::make_shared<detail::ModelDeclaration<T>>();
699 data->options = options;
700 data->prepared = std::move(prepared);
701 data->create = [provider = std::move(provider)] {
702 return std::expected<std::shared_ptr<const ModelSnapshot<T>>, TreeError>(provider);
703 };
704 return detail::ModelAccess::make(std::move(data));
705 } catch (const std::bad_alloc &) {
706 return detail::ModelAccess::failed<T>(TreeError::NO_MEMORY);
707 } catch (...) {
708 return detail::ModelAccess::failed<T>(TreeError::CALLBACK_FAILED);
709 }
710}
711
722template <class T, std::size_t N>
723Model<T> model(std::array<T, N> values, CollectionLimits limits = {}, ModelOptions options = {},
724 PositionMapOptions history = {}) {
725 try {
726 auto data = std::make_shared<detail::ModelDeclaration<T>>();
727 data->options = options;
728 auto sequence = std::make_shared<detail::OwnedSequence<T>>();
729 sequence->capacity = limits.maxRows;
730 sequence->history = history;
731 data->sequence = sequence;
732 data->create = [values = std::move(values), limits,
733 sequence]() -> std::expected<std::shared_ptr<const ModelSnapshot<T>>, TreeError> {
734 if (!limits.maxRows || !sequence->history.maxChanges || N > limits.maxRows) {
735 return std::unexpected(!limits.maxRows || !sequence->history.maxChanges ? TreeError::INVALID_ARGUMENT
736 : TreeError::NODE_LIMIT);
737 }
738 if (sequence->current) {
739 return sequence->current;
740 }
741
742 std::vector<ModelRow<T>> rows(std::initializer_list<ModelRow<T>>{});
743 rows.reserve(N);
744 for (std::size_t index = 0; index < N; ++index) {
745 rows.push_back({{index + 1, 1}, values[index]});
746 }
747 auto proof = std::make_shared<detail::OwnedHistory>(1, N, sequence->history);
748 sequence->current = std::make_shared<detail::OwnedRows<T>>(rows, 1, std::move(proof));
749 sequence->nextId = N + 1;
750 return sequence->current;
751 };
752 return detail::ModelAccess::make(std::move(data));
753 } catch (const std::bad_alloc &) {
754 return detail::ModelAccess::failed<T>(TreeError::NO_MEMORY);
755 } catch (...) {
756 return detail::ModelAccess::failed<T>(TreeError::CALLBACK_FAILED);
757 }
758}
759
767template <class T>
768Navigation<T> navigation(Model<T> source, NavigationBindingOptions binding = {}, NavigationOptions options = {}) {
769 try {
770 auto data = std::make_shared<detail::NavigationDeclaration<T>>(std::move(source));
771 data->binding = binding;
772 data->options = options;
773 return detail::ModelAccess::make(std::move(data));
774 } catch (const std::bad_alloc &) {
775 return detail::ModelAccess::failedNavigation<T>(TreeError::NO_MEMORY);
776 } catch (...) {
777 return detail::ModelAccess::failedNavigation<T>(TreeError::CALLBACK_FAILED);
778 }
779}
780
781template <class T>
782std::expected<void, ManagedError> Navigation<T>::setModel(Model<T> target, ModelRebindOptions options) const {
783 const auto data = data_;
784 auto owner = data ? detail::eventScene(data->observation)
785 : std::expected<ManagedScene *, ManagedError>(
786 std::unexpected(ManagedError{ManagedPhase::INPUT, {}, failure_, {}, {}}));
787 if (!owner) {
788 return std::unexpected(owner.error());
789 }
790 auto existing = detail::ModelAccess::existing(**owner, target);
791 if (!existing) {
792 return std::unexpected(existing.error());
793 }
794 if (*existing) {
795 auto result = data->handle.setModel(**existing, options);
796 if (result) {
797 data->initial = target;
798 }
799 return result;
800 }
801 try {
802 detail::MountContext context;
803 auto model = detail::ModelAccess::resolve(**owner, target, context);
804 if (!model) {
805 return std::unexpected(model.error());
806 }
807 auto changed = data->handle.setModel(*model, options);
808 if (!changed) {
809 return changed;
810 }
811 detail::ModelAccess::publish(context);
812 data->initial = target;
813 return {};
814 } catch (const std::bad_alloc &) {
815 return std::unexpected(ManagedError{ManagedPhase::INPUT, {}, TreeError::NO_MEMORY, {}, {}});
816 } catch (...) {
817 return std::unexpected(ManagedError{ManagedPhase::INPUT, {}, TreeError::CALLBACK_FAILED, {}, {}});
818 }
819}
820
821template <class T>
822template <class Build>
823std::expected<void, ManagedError> Model<T>::mutate(PositionChange change, bool inserts, Build build,
824 const Replacement *replacement) const {
825 auto handle = managed();
826 if (!handle) {
827 return std::unexpected(handle.error());
828 }
829 auto owner = detail::eventScene(data_->observation);
830 if (!owner) {
831 return std::unexpected(owner.error());
832 }
833 const auto root = data_->observation->node;
834 const auto lifetime = data_->observation->lifetime;
835 auto fail = [&](TreeError error) {
836 return std::unexpected(ManagedError{ManagedPhase::STATE, root.id(), error, {}, {}});
837 };
838 if constexpr (!std::is_copy_constructible_v<T>) {
839 return fail(TreeError::INVALID_ARGUMENT);
840 } else {
841 auto sequence = std::static_pointer_cast<detail::ModelDeclaration<T>>(data_)->sequence;
842 if (!sequence || !sequence->current) {
843 return fail(TreeError::INVALID_ARGUMENT);
844 }
845 if (sequence->editing || data_->resolving) {
846 return fail(TreeError::WOULD_BLOCK);
847 }
848 const auto previous = sequence->current;
849 const auto count = previous->rowCount();
850 if (change.first > count || change.removed > count - change.first ||
851 (change.kind == PositionChangeKind::MOVE && change.destination > count - change.removed)) {
852 return fail(TreeError::INVALID_ARGUMENT);
853 }
854 if (!replacement && ((!change.removed && !change.inserted) ||
855 (change.kind == PositionChangeKind::MOVE && change.destination == change.first))) {
856 return {};
857 }
858 if (change.inserted > std::numeric_limits<std::uint64_t>::max() - (count - change.removed) ||
859 count - change.removed + change.inserted > sequence->capacity) {
860 return fail(TreeError::NODE_LIMIT);
861 }
862
863 struct Editing {
864 detail::OwnedSequence<T> &sequence;
865 bool active{true};
866
867 ~Editing() {
868 if (active) {
869 sequence.editing = false;
870 }
871 }
872 } guard{*sequence};
873
874 sequence->editing = true;
875 std::shared_ptr<detail::OwnedEditVersion> editVersion;
876 if (replacement && sequence->editVersions) {
877 for (const auto &weak : *sequence->editVersions) {
878 auto entry = weak.lock();
879 if (entry && entry->row == replacement->id) {
880 editVersion = std::move(entry);
881 break;
882 }
883 }
884 }
885 if (replacement && replacement->expectedVersion &&
886 (!editVersion || editVersion->version != *replacement->expectedVersion)) {
887 return fail(TreeError::WOULD_BLOCK);
888 }
889 if (editVersion && editVersion->version == std::numeric_limits<std::uint64_t>::max()) {
890 return fail(TreeError::IDENTITY_EXHAUSTED);
891 }
892 try {
893 if (replacement) {
894 const auto found = previous->locateRow(replacement->id);
895
896 if (found.state != RowLookupState::FOUND) {
897 return fail(TreeError::INVALID_ARGUMENT);
898 }
899
900 if constexpr (std::equality_comparable<T>) {
901 const bool equal = previous->rows()[static_cast<std::size_t>(found.index)].value == replacement->value;
902
903 if (lifetime.expired() || detail::Access::modelSceneClosed(**owner)) {
904 return fail(TreeError::CLOSED);
905 }
906
907 if (equal) {
908 if (replacement->acceptedVersion) {
909 *replacement->acceptedVersion = editVersion->version;
910 }
911 return {};
912 }
913 }
914 }
915
916 if (previous->revision() == std::numeric_limits<std::uint64_t>::max() ||
917 (inserts && sequence->nextId == std::numeric_limits<std::uint64_t>::max())) {
918 return fail(TreeError::IDENTITY_EXHAUSTED);
919 }
920
921 std::vector<ModelRow<T>> rows(std::initializer_list<ModelRow<T>>{});
922 const auto nextCount = change.kind == PositionChangeKind::MOVE ? count : count - change.removed + change.inserted;
923 rows.reserve(static_cast<std::size_t>(nextCount));
924 std::invoke(build, rows, previous->rows(), sequence->nextId);
925 auto history = std::make_shared<detail::OwnedHistory>(previous->history(), count,
926 replacement ? std::nullopt : std::optional(change));
927 auto next = std::make_shared<detail::OwnedRows<T>>(rows, previous->revision() + 1, std::move(history));
928 if (lifetime.expired()) {
929 return fail(TreeError::CLOSED);
930 }
931 if (sequence->current != previous) {
932 return fail(TreeError::WOULD_BLOCK);
933 }
934 auto applied = detail::Access::applyOwnedModel(**owner, *handle, std::shared_ptr<const ModelSnapshot<T>>(next));
935 if (!applied) {
936 return applied;
937 }
938 // All fallible work precedes the existing model transaction. Publish owner
939 // metadata before releasing old rows, whose user destructors may reenter.
940 if (editVersion) {
941 ++editVersion->version;
942 }
943 if (replacement && replacement->acceptedVersion) {
944 *replacement->acceptedVersion = editVersion->version;
945 }
946 sequence->current = std::move(next);
947 if (inserts) {
948 ++sequence->nextId;
949 }
950 sequence->editing = false;
951 guard.active = false;
952 return {};
953 } catch (const std::bad_alloc &) {
954 return fail(lifetime.expired() ? TreeError::CLOSED : TreeError::NO_MEMORY);
955 } catch (...) {
956 return fail(lifetime.expired() ? TreeError::CLOSED : TreeError::CALLBACK_FAILED);
957 }
958 }
959}
960
961template <class T> std::expected<void, ManagedError> Model<T>::insert(std::uint64_t index, const T &value) const {
962 return mutate(PositionChange::splice(index, 0, 1), true, [&](auto &rows, auto old, std::uint64_t identity) {
963 for (std::size_t offset = 0; offset <= old.size(); ++offset) {
964 if (offset == index) {
965 rows.emplace_back(RowId{identity, 1}, value);
966 }
967 if (offset < old.size()) {
968 rows.push_back(old[offset]);
969 }
970 }
971 });
972}
973
974template <class T> std::expected<void, ManagedError> Model<T>::update(RowId id, const T &value) const {
975 const Replacement replacement{id, value};
976
977 return mutate(
978 {}, false,
979 [&](auto &rows, auto old, std::uint64_t) {
980 for (const auto &row : old) {
981 rows.emplace_back(row.id, row.id == id ? value : row.value);
982 }
983 },
984 &replacement);
985}
986
987template <class T> bool Model<T>::row(RowId id, const T &value, std::source_location origin) const {
988 const auto observation = data_ ? data_->observation : nullptr;
989 auto result = update(id, value);
990
991 if (!result) {
992 detail::reportEventError(observation, result.error(), origin);
993 }
994
995 return result.has_value();
996}
997
998template <class T> std::expected<void, ManagedError> Model<T>::erase(std::uint64_t first, std::uint64_t count) const {
999 return mutate(PositionChange::splice(first, count, 0), false, [&](auto &rows, auto old, std::uint64_t) {
1000 for (std::size_t offset = 0; offset < old.size(); ++offset) {
1001 if (offset < first || offset - first >= count) {
1002 rows.push_back(old[offset]);
1003 }
1004 }
1005 });
1006}
1007
1008template <class T>
1009std::expected<void, ManagedError> Model<T>::move(std::uint64_t first, std::uint64_t count,
1010 std::uint64_t destination) const {
1011 return mutate(PositionChange::move(first, count, destination), false, [&](auto &rows, auto old, std::uint64_t) {
1012 for (std::size_t offset = 0; offset < old.size(); ++offset) {
1013 const bool moved = offset >= destination && offset - destination < count;
1014 std::uint64_t original{};
1015 if (moved) {
1016 original = first + offset - destination;
1017 } else {
1018 const auto remaining = offset < destination ? offset : offset - count;
1019 original = remaining < first ? remaining : remaining + count;
1020 }
1021 rows.push_back(old[static_cast<std::size_t>(original)]);
1022 }
1023 });
1024}
1025
1026template <class T> std::expected<void, ManagedError> Model<T>::clear() const {
1027 auto handle = managed();
1028 if (!handle) {
1029 return std::unexpected(handle.error());
1030 }
1031 const auto data = std::static_pointer_cast<detail::ModelDeclaration<T>>(data_);
1032 if (!data->sequence || !data->sequence->current) {
1033 return std::unexpected(ManagedError{ManagedPhase::STATE, {}, TreeError::INVALID_ARGUMENT, {}, {}});
1034 }
1035 return erase(0, data->sequence->current->rowCount());
1036}
1037
1038template <class T>
1039template <class Row>
1040 requires(std::same_as<T, VirtualList<Row>> || std::same_as<T, VirtualTable<Row>>)
1041std::expected<void, ManagedError> Ref<T>::setModel(Model<Row> source, ModelRebindOptions options,
1042 std::source_location origin) const {
1043 const auto observation = target();
1044 const auto node = this->node();
1045 auto owner = detail::eventScene(observation);
1046 if (!owner) {
1047 auto failure = owner.error();
1048 failure.registrationOrigin = origin;
1049 return std::unexpected(failure);
1050 }
1051 auto existing = detail::ModelAccess::existing(**owner, source);
1052 if (!existing) {
1053 auto failure = existing.error();
1054 failure.registrationOrigin = origin;
1055 return std::unexpected(failure);
1056 }
1057 if (*existing) {
1058 auto changed = (*owner)->setModel(node, **existing, std::nullopt, options);
1059 if (!changed) {
1060 changed.error().registrationOrigin = origin;
1061 }
1062 return changed;
1063 }
1064 try {
1065 detail::MountContext context;
1066 auto model = detail::ModelAccess::resolve(**owner, source, context);
1067 if (!model) {
1068 auto failure = model.error();
1069 failure.registrationOrigin = origin;
1070 return std::unexpected(failure);
1071 }
1072 auto changed = (*owner)->setModel(node, *model, std::nullopt, options);
1073 if (!changed) {
1074 changed.error().registrationOrigin = origin;
1075 return changed;
1076 }
1077 detail::ModelAccess::publish(context);
1078 return {};
1079 } catch (const std::bad_alloc &) {
1080 return std::unexpected(ManagedError{ManagedPhase::INPUT, {}, TreeError::NO_MEMORY, {}, {}});
1081 } catch (...) {
1082 return std::unexpected(ManagedError{ManagedPhase::INPUT, {}, TreeError::CALLBACK_FAILED, {}, {}});
1083 }
1084}
1085} // namespace portals::ui
1086
1087#include <portals/detail/ui_source_projection.hpp>
1088#include <portals/detail/ui_value_model.hpp>
Owning field descriptor over one scalar root; snapshots never retain a borrowed member reference.
Definition ui_value_model.hpp:520
Weak scalar property observation; assignment publishes a value without rebinding the descriptor.
Definition ui_value_model.hpp:412
Owning cold model declaration; copies share one single-scene registration. Construction does not read...
Definition ui_model.hpp:129
std::expected< void, ManagedError > clear() const
Definition ui_model.hpp:1026
ModelValue< portals::ui::TextDocumentValue > value(std::source_location origin=std::source_location::current()) const
Definition ui_value_model.hpp:507
bool row(RowId id, const portals::ui::TextDocumentValue &value, std::source_location origin=std::source_location::current()) const
Definition ui_model.hpp:987
std::expected< void, ManagedError > insert(std::uint64_t index, const portals::ui::TextDocumentValue &value) const
Definition ui_model.hpp:961
std::expected< void, ManagedError > move(std::uint64_t first, std::uint64_t count, std::uint64_t destination) const
Definition ui_model.hpp:1009
std::expected< void, ManagedError > erase(std::uint64_t first, std::uint64_t count=1) const
Definition ui_model.hpp:998
T Row
Immutable domain row, shared with the mounted model.
Definition ui_model.hpp:131
std::expected< ManagedModel< T >, ManagedError > managed() const
Obtain the published model without extending scene lifetime.
Definition ui_model.hpp:138
Model()=default
Create an empty descriptor whose checked use reports INVALID_ARGUMENT.
std::expected< void, ManagedError > update(RowId id, const portals::ui::TextDocumentValue &value) const
Definition ui_model.hpp:974
Cold explicit shared navigation; ordinary model-source views stay independent.
Definition ui_model.hpp:248
std::expected< std::optional< RowId >, ManagedError > currentRow() const
Read the current model-local item key from the existing managed navigation channel.
Definition ui_model.hpp:276
Navigation()=default
Create an empty context descriptor whose checked use reports INVALID_ARGUMENT.
T Row
Common domain row of the explicit navigation session.
Definition ui_model.hpp:250
bool model(Model< T > target, ModelRebindOptions options={}, std::source_location origin=std::source_location::current()) const
Change the shared model and report a checked failure through existing scene diagnostics.
Definition ui_model.hpp:320
std::expected< ManagedNavigation, ManagedError > managed() const
Obtain the published context without extending scene lifetime.
Definition ui_model.hpp:257
std::expected< void, ManagedError > setModel(Model< T > target, ModelRebindOptions options={}) const
Admit one model change for the complete shared group on its UI thread.
Definition ui_model.hpp:782
Node< T > node() const noexcept
Definition ui_ref.hpp:731
std::expected< void, ManagedError > setModel(const LogSource &source, std::source_location origin=std::source_location::current()) const
Definition ui_ref.hpp:1079
bool model(const LogSource &source, std::source_location origin=std::source_location::current()) const
Definition ui_ref.hpp:1089
auto change(T value)
Definition style_static.hpp:1496
auto bind(ManagedState< std::string > value)
Definition ui_static.hpp:591
Public Portals API.
Definition action.hpp:8
@ WOULD_BLOCK
Active resume, invocation, registration or queue capacity rejects the operation.
Definition async.hpp:30
@ 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
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
@ 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
Original error plus independent runner/restoration and cleanup failures.
Definition managed_diagnostics.hpp:62
Explicit rebinding policy; omitted history options inherit the session's settings.
Definition managed_navigation.hpp:44
Scalar ordering operation; payload and row identities remain in the model.
Definition model_position.hpp:181
static constexpr PositionChange splice(std::uint64_t first, std::uint64_t removed, std::uint64_t inserted) noexcept
Definition model_position.hpp:193
static constexpr PositionChange move(std::uint64_t first, std::uint64_t count, std::uint64_t destination) noexcept
Definition model_position.hpp:202
Provider-assigned row identity, independent of position; increment generation on reuse.
Definition row_id.hpp:9
Stack-owned transaction bookkeeping, discarded after one description mount.
Definition ui_recipe_context.hpp:554
Shared observation; publication and all mutable fields belong to the constructing UI thread.
Definition ui_ref.hpp:71