13 return std::unexpected(allowed.error());
16 auto revision = app_.tree().geometryRevision();
22 if (*revision != layoutRevision_) {
26 auto shown = detail::listShown(app_.tree(), node);
36 auto geometry = app_.tree().observeGeometry(node);
48 result = std::move(*snapshot);
50 result = std::unexpected(std::move(snapshot.error()));
52 }
catch (
const std::bad_alloc &) {
70 return std::unexpected(allowed.error());
73 if (models_.size() >= options_.maxModels) {
78 auto created =
Model<T>::create(app_.tree(), root_, std::move(initial), options);
84 auto source = std::make_shared<detail::ManagedModelSourceOf<T>>();
87 source->model = std::move(*created);
88 source->scene = root_.id();
90 source->origin = rowOrigin_;
91 source->receiver = rowOrigin_->node;
94 source->preparation = std::make_shared<ManagedViewHandler<T>>(std::move(prepared));
96 handle.source_ = source;
97 handle.owner_ = owner_;
98 models_.push_back(std::move(source));
101 }
catch (
const std::bad_alloc &) {
107std::expected<std::shared_ptr<detail::ManagedModelSourceOf<T>>,
ManagedError>
112 return std::unexpected(allowed.error());
115 auto source =
model.lock();
121 if ((*source)->retired || !(*source)->model) {
125 if ((*source)->scene != root_.id()) {
135template <
class T,
class W>
struct ManagedScene::ViewPreparation {
138 std::shared_ptr<detail::ManagedModelSourceOf<T>> source;
139 std::shared_ptr<detail::ManagedPreparedRegistration<T>> registration;
141 [[no_unique_address]] std::conditional_t<std::same_as<W, Chart<T>>, std::monostate,
142 std::shared_ptr<detail::ModelViewRestoreState>> restoration;
144 std::expected<void, TreeError> operator()(
const LayoutSnapshot &layout)
const {
145 const auto retireOrigin = [&]() -> std::expected<void, TreeError> {
146 if (source->origin) {
147 auto live = source->origin->check();
150 if (!source->origin->retired && !source->origin->closed) {
151 return std::unexpected(
live.error());
154 scene->pruneLiveText();
160 auto live = retireOrigin();
166 if (!source->frame) {
167 return std::unexpected(TreeError::INVALID_ARGUMENT);
170 if constexpr (std::same_as<W, VirtualList<T>> || std::same_as<W, VirtualTable<T>>) {
171 if (restoration && restoration->pending) {
172 if (
auto context = restoration->context.lock()) {
173 auto current = context->current.snapshot();
174 auto reading = context->reading.snapshot();
175 auto selection = context->selection.snapshot();
176 auto navigated = [](
const auto &snapshot, std::uint64_t revision) {
177 return snapshot->revision != revision && snapshot->value.row &&
178 (snapshot->value.resolution == PositionResolution::EXACT ||
179 snapshot->value.resolution == PositionResolution::NEAREST);
181 if (current && reading &&
182 ((restoration->shareCurrent && navigated(*current, restoration->currentRevision)) ||
183 (restoration->shareReading && navigated(*reading, restoration->readingRevision)))) {
185 restoration->pending.reset();
186 restoration->attempted =
false;
187 auto cleared = scene->app_.tree().edit(node, [](W &view) {
188 view.preparedSuppressed_ =
false;
193 }
else if (selection && (*selection)->revision != restoration->selectionRevision) {
194 restoration->pending->selection = (*selection)->value;
195 restoration->pending->selectedPositions.reset();
196 restoration->channels.selection =
false;
197 restoration->selectionRevision = (*selection)->revision;
198 if (!detail::pendingModelRestoration(*restoration->pending, restoration->channels) &&
199 restoration->attemptedRevision == source->frame->revision() &&
200 restoration->attemptedProofRevision == source->navigationRevision) {
201 restoration->resolution = restoration->pending->currentResolution == PositionResolution::NEAREST ||
202 restoration->pending->readingResolution == PositionResolution::NEAREST
203 ? PositionResolution::NEAREST
204 : PositionResolution::EXACT;
205 restoration->pending.reset();
206 auto cleared = scene->app_.tree().edit(node, [](W &view) {
207 view.preparedSuppressed_ =
false;
216 if (restoration && restoration->pending) {
217 auto retained = restoration;
219 const auto lifetime = std::weak_ptr<const void>(scene->lifetime_);
220 auto shown = detail::listShown(scene->app_.tree(), node);
222 return std::unexpected(shown.error());
227 const auto revision = source->frame->revision();
228 const auto proofRevision = source->navigationRevision;
230 if (restoration->attemptedRevision != revision ||
231 restoration->attemptedProofRevision != source->navigationRevision) {
232 restoration->attempted =
true;
233 auto outcome = restoration->resolution;
234 auto resolved = scene->resolveViewCheckpoint<T>(*restoration->pending, source, restoration->history,
235 restoration->history->options().bookmarks, outcome, {},
236 &restoration->channels);
238 if (lifetime.expired()) {
239 return std::unexpected(TreeError::CLOSED);
241 auto entry = scene->find(node);
242 auto current = entry ? entry->viewPrepare.template target<ViewPreparation<T, W>>() : nullptr;
243 if (!current || current->source != model || current->restoration != retained) {
244 return std::unexpected(TreeError::CLOSED);
246 if (source->retired || !source->frame || source->frame->revision() != revision ||
247 source->navigationRevision != proofRevision) {
252 return std::unexpected(resolved.error());
255 restoration->attemptedRevision = revision;
256 restoration->attemptedProofRevision = proofRevision;
257 restoration->resolution = outcome;
258 if (restoration->resolution == PositionResolution::EXACT ||
259 restoration->resolution == PositionResolution::NEAREST ||
260 restoration->resolution == PositionResolution::EMPTY) {
261 auto installed = scene->app_.tree().edit(node, [&](W &view) {
262 view.selected_ = resolved->current && (resolved->currentResolution == PositionResolution::EXACT ||
263 resolved->currentResolution == PositionResolution::NEAREST)
264 ? std::optional(resolved->current->position().row)
267 (void)view.scroll_.setOffset(resolved->first);
268 view.anchor_ = resolved->reading && resolved->reading->position().kind == PositionKind::ITEM
269 ? std::optional(resolved->reading->position().row)
271 view.anchorRevision_ = source->frame->dataRevision();
273 view.preparedSuppressed_ =
false;
279 restoration->pending.reset();
283 if (restoration->pending) {
291 if constexpr (std::same_as<W, VirtualList<T>>) {
292 if (source->retired) {
293 auto detached = scene->app_.tree().edit(node, [](W &view) {
294 view.detachedCollection_ =
true;
295 view.request_.cancel();
306 auto navigation = scene->navigationBefore(node);
312 auto work = [&]() -> std::expected<std::optional<ModelRequest<T>>, TreeError> {
313 if constexpr (std::same_as<W, VirtualList<T>>) {
315 }
else if constexpr (std::same_as<W, VirtualTable<T>>) {
318 auto origin = first ? first() : std::expected<std::uint64_t,
TreeError>(0);
321 return std::unexpected(origin.error());
324 return prepareChart(scene->app_.tree(), node, *source->frame, layout, *origin);
329 return std::unexpected(work.error());
332 navigation = scene->navigationAfter(node);
338 live = retireOrigin();
344 if (source->retired) {
349 auto action = registration && registration->action ? registration->action : source->preparation;
353 auto result = (*action)(*source->frame, *work);
354 auto retired = retireOrigin();
356 return result ? retired : result;
358 (void)retireOrigin();
367 return std::unexpected(TreeError::INVALID_ARGUMENT);
376template <
class T,
class W>
377std::expected<detail::ModelViewCheckpoint, TreeError>
378ManagedScene::captureViewCheckpoint(
Node<W> node,
const std::shared_ptr<detail::ManagedModelSourceOf<T>> &source,
380 auto resource = detail::modelNavigationResource(*source);
382 return std::unexpected(resource.error());
385 detail::ModelViewCheckpoint value;
386 std::optional<RowId> selected;
387 std::optional<RowId> anchor;
388 std::optional<std::uint64_t> selectedOffset;
389 std::uint64_t revision{};
391 auto read = app_.tree().read(node, [&](
const W &view) {
392 selected = view.selected_;
393 anchor = view.anchor_;
394 value.first = view.scroll_.rasterOffset();
395 if (view.prepared_) {
397 revision = view.prepared_->frame.dataRevision();
398 for (std::size_t index = 0; index < view.prepared_->rows.size(); ++index) {
399 if (view.prepared_->rows[index].id == selected) {
400 selectedOffset = view.prepared_->window.visible.first + index;
406 revision = view.anchorRevision_;
410 return std::unexpected(read.error());
413 auto pinned = source->pin();
415 return std::unexpected(pinned.error());
417 revision = source->frame->dataRevision();
419 const auto readingRevision = revision;
424 value.selection.resource_ = *resource;
427 value.selection.rows_ = std::make_shared<const std::vector<RowId>>(std::initializer_list<RowId>{*selected});
434 if (selected && !selectedOffset) {
435 auto located = source->frame->locateRow(*selected);
437 return std::unexpected(located.error());
442 selectedOffset = located->index;
443 revision = source->frame->dataRevision();
445 auto make = [&](
PositionKind kind, RowId row, std::uint64_t offset, std::uint64_t dataRevision) {
451 return std::unexpected(detail::navigationTreeError(mark.error()));
453 value.current = std::move(*mark);
455 value.selection.rows_ = std::make_shared<const std::vector<RowId>>(std::initializer_list<RowId>{*selected});
458 value.selection.resource_ = *resource;
462 return std::unexpected(detail::navigationTreeError(reading.error()));
464 value.reading = std::move(*reading);
471std::expected<void, TreeError> ManagedScene::captureSelectedPositions(
472 detail::ModelViewCheckpoint &value,
const std::shared_ptr<detail::ManagedModelSourceOf<T>> &source,
473 const std::shared_ptr<detail::ModelViewHistory> &history,
BookmarkOptions options) {
474 if (value.selection.rows().empty()) {
477 if (source->frame && !source->frame->dataRevision()) {
481 if (value.selectedPositions) {
484 if (!source->frame || value.selection.resource() != source->navigationResource) {
487 const auto frame = *source->frame;
488 auto positions = history->selectedPositions(value.selection.rows().size());
490 return std::unexpected(positions.error());
492 for (
auto id : value.selection.rows()) {
493 auto located = frame.locateRow(
id);
495 return std::unexpected(located.error());
501 value.selection.resource(),
502 {PositionKind::ITEM, id, located->index, frame.dataRevision(), PositionAffinity::FORWARD}, {}, options);
504 return std::unexpected(detail::navigationTreeError(position.error()));
506 (*positions)->positions.push_back(std::move(*position));
508 value.selectedPositions = std::move(*positions);
513std::expected<detail::ModelViewCheckpoint, TreeError> ManagedScene::resolveViewCheckpoint(
514 detail::ModelViewCheckpoint value,
const std::shared_ptr<detail::ManagedModelSourceOf<T>> &source,
516 PositionChangeMap changes,
const detail::ModelRestoreChannels *requestedChannels) {
517 if (!source->frame) {
520 const auto frame = *source->frame;
521 const auto originalCurrent = value.current;
522 const auto channels = requestedChannels ? *requestedChannels : detail::ModelRestoreChannels{};
523 if (!changes && source->navigationChanges.toRevision() == frame.dataRevision()) {
524 changes = source->navigationChanges;
526 auto resource = detail::modelNavigationResource(*source);
528 return std::unexpected(resource.error());
530 if (!frame.dataRevision()) {
531 auto unavailable = [&](
const std::optional<ModelBookmark> &bookmark,
PositionResolution previous) {
532 if (!bookmark && !detail::unresolvedPosition(previous)) {
538 if ((bookmark && bookmark->resource() != *resource) ||
539 (!bookmark && value.selection.resource().identity.instance && value.selection.resource() != *resource)) {
544 if (channels.current) {
545 value.currentResolution = unavailable(value.current, value.currentResolution);
547 if (channels.reading) {
548 value.readingResolution = unavailable(value.reading, value.readingResolution);
550 if (channels.selection && !value.selection.rows().empty()) {
551 value.selection.resolution_ =
554 const std::array outcomes{value.currentResolution, value.readingResolution, value.selection.resolution()};
555 const std::array enabled{channels.current, channels.reading, channels.selection};
557 for (std::size_t index = 0; index < outcomes.size(); ++index) {
558 if (enabled[index] && detail::unresolvedPosition(outcomes[index])) {
559 resolution = outcomes[index];
567 return std::unexpected(detail::navigationTreeError(resolver.error()));
569 for (
bool reading : {
false,
true}) {
570 if (reading ? !channels.reading : !channels.current) {
573 auto *bookmark = reading ? &value.reading : &value.current;
574 auto &outcome = reading ? value.readingResolution : value.currentResolution;
576 if (!detail::unresolvedPosition(outcome)) {
578 }
else if (value.selection.resource().identity.instance && value.selection.resource() != *resource) {
583 auto position = (*bookmark)->position();
584 std::optional<PositionReply> reply;
586 (*bookmark)->metadata().empty()) {
587 auto located = frame.locateRow(position.row);
589 return std::unexpected(located.error());
592 position.offset = located->index;
593 position.revision = frame.dataRevision();
600 return std::unexpected(row.error());
602 if (row->state() ==
RangeState::READY && !row->rows().empty() && row->rows().front().id == position.row) {
612 auto resolved = resolver->resolve({resource->identity, frame.dataRevision(), 1, **bookmark});
614 return std::unexpected(detail::navigationTreeError(resolved.error()));
616 reply = std::move(*resolved);
618 outcome = reply->state;
622 return std::unexpected(detail::navigationTreeError(updated.error()));
624 *bookmark = std::move(*updated);
630 value.first = value.reading->position().offset;
631 }
else if (!detail::unresolvedPosition(value.readingResolution)) {
634 auto aggregate = [&] {
636 const std::array outcomes{value.currentResolution, value.readingResolution, value.selection.resolution()};
637 const std::array enabled{channels.current, channels.reading, channels.selection};
638 for (std::size_t index = 0; index < outcomes.size(); ++index) {
639 if (!enabled[index]) {
642 const auto outcome = outcomes[index];
653 if (!channels.selection) {
654 resolution = aggregate();
657 const bool selectionCompatible = value.selection.resource() == *resource;
658 if (value.selection.rows().empty()) {
659 value.selection.resource_ = *resource;
662 if (!value.selection.rows().empty()) {
663 if (!selectionCompatible) {
665 resolution = aggregate();
668 const auto ids = value.selection.rows();
669 const auto hints = value.selectedPositions;
670 if (hints && hints->positions.size() != ids.size()) {
673 if (hints && !hints->positions.empty()) {
674 const auto revision = hints->positions.front().position().revision;
675 for (
const auto &hint : hints->positions) {
676 if (hint.position().revision != revision) {
681 bool requestedHistory{};
682 std::shared_ptr<std::vector<RowId>> selected;
683 std::shared_ptr<detail::ModelSelectionPositions> positions;
684 auto preparePositions = [&](std::size_t prefix) -> std::expected<void, TreeError> {
685 if (!hints || positions) {
688 auto allocated = history->selectedPositions(ids.size());
690 return std::unexpected(allocated.error());
692 positions = std::move(*allocated);
693 positions->positions.insert(positions->positions.end(), hints->positions.begin(),
694 hints->positions.begin() + prefix);
697 for (std::size_t index = 0; index < ids.size(); ++index) {
698 const auto id = ids[index];
699 if (hints && (hints->positions[index].resource() != value.selection.resource() ||
700 hints->positions[index].position().row !=
id)) {
703 auto located = frame.locateRow(
id);
705 return std::unexpected(located.error());
707 const bool currentConfirmed = value.current && value.current->position().row ==
id &&
711 const ModelBookmark *hint{};
713 hint = &hints->positions[index];
714 }
else if (originalCurrent && originalCurrent->position().row ==
id) {
715 hint = &*originalCurrent;
718 (!changes || changes.fromRevision() != hint->position().revision) && !requestedHistory) {
719 requestedHistory =
true;
720 auto proof = detail::modelPositionHistory(*frame.snapshot(), hint->position().revision);
722 return std::unexpected(detail::navigationTreeError(proof.error()));
726 resolution = aggregate();
729 changes = std::move(proof->changes);
732 changes.fromRevision() == hint->position().revision) {
733 auto mapped = changes.map(hint->position());
735 return std::unexpected(detail::navigationTreeError(mapped.error()));
737 if (mapped->removed) {
739 selected = std::make_shared<std::vector<RowId>>(ids.begin(), ids.begin() + index);
740 selected->reserve(ids.size());
742 auto prepared = preparePositions(index);
744 return std::unexpected(prepared.error());
751 resolution = aggregate();
755 selected->push_back(
id);
758 const auto offset = located->state ==
RowLookupState::FOUND ? located->index : value.current->position().offset;
759 const auto previous = hints->positions[index].position();
760 if (!positions && (previous.offset != offset || previous.revision != frame.dataRevision())) {
761 auto prepared = preparePositions(index);
763 return std::unexpected(prepared.error());
770 return std::unexpected(detail::navigationTreeError(updated.error()));
772 positions->positions.push_back(std::move(*updated));
777 value.selection.rows_ = std::move(selected);
780 value.selectedPositions = std::move(positions);
782 if (value.selection.rows().empty()) {
786 resolution = aggregate();
790template <
class T,
class W>
792 std::shared_ptr<detail::ManagedModelSourceOf<T>> source,
794 auto fail = [&](
TreeError cause) -> std::expected<Node<W>, ManagedError> {
796 auto removed =
remove(node);
799 failure.cleanup = std::get<TreeError>(removed.error().cause);
802 return std::unexpected(failure);
806 if constexpr (std::same_as<W, VirtualList<T>>) {
807 auto configured = app_.tree().edit(node, [&](W &list) {
808 list.clearMissingSelection_ = source->sinkOnly;
811 return fail(configured.error());
814 auto entry = find(node);
816 std::shared_ptr<detail::ManagedPreparedRegistration<T>> registration;
818 registration = std::make_shared<detail::ManagedPreparedRegistration<T>>();
819 registration->action = std::make_shared<ManagedViewHandler<T>>(std::move(handler));
820 std::erase_if(source->prepared, [](
const auto &weak) {
821 return weak.expired();
823 source->prepared.push_back(registration);
828 entry->viewSource = source;
829 entry->viewPrepare = ViewPreparation<T, W>{
this, node, source, registration, std::move(first)};
831 if constexpr (std::same_as<W, VirtualTable<T>> || std::same_as<W, VirtualList<T>>) {
833 if constexpr (std::same_as<W, VirtualTable<T>>) {
841 return fail(binding.error());
847 const char *
type = std::same_as<W, Chart<T>> ?
"Chart" : std::same_as<W, VirtualTable<T>> ?
"Table" :
"List";
849 if (!entry->target || entry->target->type.empty()) {
850 auto target = entry->target ? *entry->target : StyleTarget{};
853 entry->target = std::make_shared<StyleTarget>(target);
856 entry->stylePending =
true;
860 }
catch (
const std::bad_alloc &) {
869template <
class T,
class W>
struct ManagedScene::PreparedViewModelChange final : detail::PreparedModelViewChange {
870 ManagedScene *scene{};
871 std::weak_ptr<const void> lifetime;
873 std::shared_ptr<Entry> entry;
874 std::shared_ptr<detail::ManagedModelSourceOf<T>>
876 std::shared_ptr<detail::ManagedModelSourceOf<T>>
878 std::shared_ptr<detail::ManagedPreparedRegistration<T>>
880 std::shared_ptr<detail::ModelViewRestoreState>
882 std::optional<detail::ModelViewHistoryChange> outgoing;
883 std::optional<detail::ModelViewHistoryChange> destination;
884 std::function<std::expected<void, TreeError>(
const LayoutSnapshot &)>
886 ModelConsumer<T> consumer;
887 ModelConsumer<T> previousConsumer;
888 ModelRequest<T> previousRequest;
889 std::unique_ptr<typename W::Prepared> previousPrepared;
890 detail::ModelViewCheckpoint target;
891 std::optional<RowId> selected;
892 std::optional<RowId> anchor;
893 std::optional<std::uint64_t> intent;
894 std::uint64_t intentRevision{};
895 std::uint64_t anchorRevision{};
897 const typename W::Prepared *prepared{};
898 const void *binding{};
899 std::uint64_t sourceRevision{};
900 std::uint64_t navigationRevision{};
907 std::expected<void, TreeError> validate()
const override {
908 if (lifetime.expired() || source->retired || previousSource->retired || scene->find(node) != entry ||
909 entry->viewSource.lock() != previousSource ||
910 entry->viewPrepare.template target<ViewPreparation<T, W>>() != binding ||
911 (source->frame && source->frame->revision() != sourceRevision) ||
912 source->navigationRevision != navigationRevision || (outgoing && !restoration->history->valid(*outgoing)) ||
913 (destination && !restoration->history->valid(*destination))) {
914 return std::unexpected(TreeError::WOULD_BLOCK);
917 auto checked = scene->app_.tree().edit(node, [&](W &view) {
918 unchanged = view.selected_ == selected && view.anchor_ == anchor && view.intent_ == intent &&
919 view.intent_revision_ == intentRevision && view.anchorRevision_ == anchorRevision &&
920 view.scroll_.rasterOffset() == scroll.rasterOffset() &&
921 view.scroll_.fraction() == scroll.fraction() && view.prepared_.get() == prepared;
923 return !checked ? checked : unchanged ? std::expected<void, TreeError>{} : std::unexpected(TreeError::WOULD_BLOCK);
929 std::expected<void, TreeError> invalidate()
const override {
930 return reset ? scene->app_.tree().invalidate(node, Invalidation::PAINT) : std::expected<void, TreeError>{};
936 std::expected<void, TreeError> install()
override {
937 return scene->app_.tree().edit(node, [&](W &view) {
939 if (source != previousSource) {
940 previousConsumer = std::move(view.consumer_);
941 view.consumer_ = std::move(consumer);
943 previousRequest = std::move(view.request_);
944 previousPrepared = std::move(view.prepared_);
945 view.selected_ = !pending && target.current &&
946 (target.currentResolution == PositionResolution::EXACT ||
947 target.currentResolution == PositionResolution::NEAREST)
948 ? std::optional(target.current->position().row)
950 view.intent_.reset();
951 view.intent_revision_ = 0;
953 (void)view.scroll_.setOffset(target.first);
954 view.anchor_ = target.reading && target.reading->position().kind == PositionKind::ITEM
955 ? std::optional(target.reading->position().row)
957 view.anchorRevision_ = source->frame ? source->frame->dataRevision() : 0;
960 view.retryPending_ =
false;
961 view.retryFailedBase_ =
false;
962 view.retryFrameRevision_ = 0;
963 view.preparedSuppressed_ = pending;
964 if constexpr (std::same_as<W, VirtualList<T>>) {
965 view.clearMissingSelection_ = source->sinkOnly;
966 view.detachedCollection_ =
false;
970 source->prepared.push_back(registration);
972 entry->viewSource = source;
973 entry->viewPrepare.swap(preparation);
978 void commitHistory() noexcept
override {
980 restoration->history->commit(std::move(*outgoing));
983 restoration->history->commit(std::move(*destination));
988 void retire() noexcept
override {
989 previousRequest.cancel();
995template <
class T,
class W>
996std::expected<std::unique_ptr<detail::PreparedModelViewChange>,
ManagedError>
997ManagedScene::prepareViewModelChange(
Node<W> node,
const std::shared_ptr<detail::ManagedModelSourceOf<T>> &source,
999 std::shared_ptr<detail::ModelViewHistory> history,
1000 const detail::ModelViewCheckpoint *sharedPosition,
1002 auto entry = find(node);
1003 auto binding = entry ? entry->viewPrepare.template target<ViewPreparation<T, W>>() : nullptr;
1007 auto fail = [&](
TreeError failure) -> std::expected<std::unique_ptr<detail::PreparedModelViewChange>, ManagedError> {
1010 auto plan = std::make_unique<PreparedViewModelChange<T, W>>();
1012 plan->lifetime = lifetime_;
1014 plan->entry = entry;
1015 plan->previousSource = binding->source;
1016 plan->source = source;
1017 plan->navigationRevision = source->navigationRevision;
1018 plan->binding = binding;
1020 auto saved = binding->restoration;
1022 history = saved ? saved->history :
nullptr;
1025 auto created = detail::ModelViewHistory::create(lifetime_, options.checkpoints.value_or(ModelCheckpointOptions{}));
1027 return fail(created.error());
1029 history = std::move(*created);
1030 }
else if (options.checkpoints &&
1031 (options.checkpoints->maxBytes != history->options().maxBytes ||
1032 options.checkpoints->bookmarks.maxBytes != history->options().bookmarks.maxBytes)) {
1035 auto stateCredit = history->reserveState();
1037 return fail(stateCredit.error());
1039 plan->restoration = std::make_shared<detail::ModelViewRestoreState>();
1040 plan->restoration->credit = std::move(*stateCredit);
1041 plan->restoration->history = history;
1042 plan->restoration->shareCurrent = sharing && sharing->current;
1043 plan->restoration->shareReading = sharing && sharing->readingAnchor;
1044 if (saved && saved->history == history) {
1045 plan->restoration->role = saved->role;
1046 plan->restoration->participant = saved->participant;
1047 plan->restoration->pending = saved->pending;
1048 plan->restoration->attemptedRevision = saved->attemptedRevision;
1049 plan->restoration->attemptedProofRevision = saved->attemptedProofRevision;
1050 plan->restoration->resolution = saved->resolution;
1051 plan->restoration->attempted = saved->attempted;
1053 auto role = history->role();
1055 return fail(role.error());
1057 plan->restoration->role = *role;
1058 auto credit = history->reserveRole();
1060 return fail(credit.error());
1062 plan->restoration->participant = std::make_shared<SourceCredit>(std::move(*credit));
1064 auto action = prepared ? (*prepared ? std::make_shared<ManagedViewHandler<T>>(std::move(*prepared)) :
nullptr)
1065 : ((plan->previousSource == source || options.retainPreparedOverride) && binding->registration
1066 ? binding->registration->action
1069 plan->registration = std::make_shared<detail::ManagedPreparedRegistration<T>>();
1070 plan->registration->action = std::move(action);
1071 std::erase_if(source->prepared, [](
const auto ®istration) {
1072 return registration.expired();
1074 source->prepared.reserve(source->prepared.size() + 1);
1076 auto observed = app_.tree().read(node, [&](
const W &view) {
1077 plan->selected = view.selected_;
1078 plan->anchor = view.anchor_;
1079 plan->intent = view.intent_;
1080 plan->intentRevision = view.intent_revision_;
1081 plan->anchorRevision = view.anchorRevision_;
1082 plan->scroll = view.scroll_;
1083 plan->prepared = view.prepared_.get();
1086 return fail(observed.error());
1088 if (!sharedPosition) {
1089 auto pinned = source->pin();
1090 if (!pinned || plan->lifetime.expired()) {
1094 plan->sourceRevision = source->frame ? source->frame->revision() : 0;
1096 std::optional<detail::ModelViewCheckpoint> continuation;
1097 if (plan->previousSource != source) {
1098 auto captured = saved && saved->pending
1099 ? std::expected<detail::ModelViewCheckpoint, TreeError>(*saved->pending)
1100 : captureViewCheckpoint<T>(node, plan->previousSource, history->options().bookmarks);
1101 if (!captured || plan->lifetime.expired()) {
1102 return fail(!captured ? captured.error() : TreeError::CLOSED);
1104 if (plan->previousSource->navigationResource == source->navigationResource) {
1105 continuation = std::move(*captured);
1107 auto outgoing = history->stage(plan->previousSource, plan->restoration->role, std::move(*captured),
1108 plan->restoration->participant);
1110 return fail(outgoing.error());
1112 plan->outgoing = std::move(*outgoing);
1115 auto cached = history->find(source, plan->restoration->role);
1119 target = std::move(*continuation);
1121 if (sharedPosition) {
1122 if (!sharing || sharing->current) {
1123 target.current = sharedPosition->current;
1125 target.selection = sharedPosition->selection;
1126 target.selectedPositions = sharedPosition->selectedPositions;
1127 if (sharedPosition->reading) {
1128 target.reading = sharedPosition->reading;
1131 if (detail::hasModelRestoreIntent(target)) {
1132 plan->restoration->attempted =
true;
1133 const auto unresolved = target;
1134 auto shown = detail::listShown(app_.tree(), node);
1136 return fail(shown.error());
1139 auto resolved = resolveViewCheckpoint<T>(std::move(target), source, history, history->options().bookmarks,
1140 plan->restoration->resolution);
1141 if (!resolved || plan->lifetime.expired()) {
1144 target = std::move(*resolved);
1151 plan->restoration->pending = plan->pending ? std::optional(unresolved) : std::nullopt;
1152 plan->restoration->attemptedRevision = *shown ? source->frame->revision() : 0;
1153 plan->restoration->attemptedProofRevision = source->navigationRevision;
1155 plan->restoration->pending.reset();
1156 plan->restoration->attempted =
false;
1158 plan->target = target;
1160 auto destination = history->stage(source, plan->restoration->role, target, plan->restoration->participant);
1162 return fail(destination.error());
1164 plan->destination = std::move(*destination);
1166 if (plan->previousSource != source) {
1167 auto opened = source->model->openRange();
1169 return fail(opened.error());
1171 plan->consumer = std::move(*opened);
1174 if (!plan->sourceRevision) {
1175 plan->sourceRevision = source->frame ? source->frame->revision() : 0;
1177 plan->preparation = ViewPreparation<T, W>{this, node, source, plan->registration, {}, plan->restoration};
1178 return std::unique_ptr<detail::PreparedModelViewChange>(std::move(plan));
1181template <
class T,
class W>
1182std::expected<void, ManagedError> ManagedScene::replaceViewModel(Node<W> node, ManagedModel<T> model,
1183 std::optional<ManagedViewHandler<T>> prepared,
1184 ModelRebindOptions options) {
1185 auto allowed = boundary(ManagedPhase::INPUT, node);
1191 auto entry = find(node);
1192 auto binding = entry ? entry->viewPrepare.template target<ViewPreparation<T, W>>() : nullptr;
1195 return std::unexpected(error(ManagedPhase::INPUT, node, TreeError::INVALID_ARGUMENT));
1198 auto source = model.lock();
1201 return std::unexpected(error(ManagedPhase::INPUT, node, source.error()));
1204 if ((*source)->retired || !(*source)->model) {
1205 return std::unexpected(error(ManagedPhase::INPUT, node, TreeError::CLOSED));
1208 if ((*source)->scene != root_.id()) {
1209 return std::unexpected(error(ManagedPhase::INPUT, node, TreeError::INVALID_ARGUMENT));
1212 const bool sameModel = binding->source == *source;
1216 if (sameModel && prepared && options.restore == ModelRestorePolicy::REMEMBER) {
1217 struct ReplacingCallback {
1218 ManagedScene &scene;
1219 std::weak_ptr<const void> lifetime;
1221 ~ReplacingCallback() {
1222 if (!lifetime.expired()) {
1223 scene.preparing_ =
false;
1226 } guard{*
this, lifetime_};
1230 const auto original = binding;
1231 auto restoration = binding->restoration;
1232 auto first = binding->first;
1233 auto action = *prepared ? std::make_shared<ManagedViewHandler<T>>(std::move(*prepared)) : nullptr;
1234 std::shared_ptr<detail::ManagedPreparedRegistration<T>> registration;
1236 registration = std::make_shared<detail::ManagedPreparedRegistration<T>>();
1237 registration->action = std::move(action);
1238 std::erase_if((*source)->prepared, [](
const auto &value) {
1239 return value.expired();
1241 (*source)->prepared.reserve((*source)->prepared.size() + 1);
1243 std::function<std::expected<void, TreeError>(
const LayoutSnapshot &)> next =
1244 ViewPreparation<T, W>{
this, node, *source, registration, std::move(first), std::move(restoration)};
1245 if (guard.lifetime.expired() || (*source)->retired || find(node) != entry ||
1246 entry->viewPrepare.template target<ViewPreparation<T, W>>() != original) {
1247 return std::unexpected(error(ManagedPhase::INPUT, node, TreeError::WOULD_BLOCK));
1249 auto live = app_.tree().withScope(node, [](
const UiScope &) {
1252 return std::unexpected(error(ManagedPhase::INPUT, node,
live.error()));
1255 (*source)->prepared.push_back(registration);
1257 entry->viewPrepare.swap(next);
1259 }
catch (
const std::bad_alloc &) {
1260 return std::unexpected(error(ManagedPhase::INPUT, node, TreeError::NO_MEMORY));
1262 return std::unexpected(error(ManagedPhase::INPUT, node, TreeError::CALLBACK_FAILED));
1267 for (
const auto &member : navigation_->bindings) {
1268 if (member->node == node) {
1269 if (member->options.projection != NavigationProjection::SAME_MODEL) {
1270 return std::unexpected(error(ManagedPhase::INPUT, node, TreeError::INVALID_ARGUMENT));
1272 if (
auto record = member->context.lock()) {
1273 return replaceNavigationModel(record, std::move(model), options, node, std::move(prepared));
1279 if (sameModel && !prepared && options.restore == ModelRestorePolicy::REMEMBER) {
1286 ManagedScene &scene;
1287 std::weak_ptr<const void> lifetime;
1290 if (!lifetime.expired()) {
1291 scene.preparing_ =
false;
1294 } guard{*
this, lifetime_};
1299 auto staged = prepareViewModelChange<T>(node, *source, std::move(prepared), options, {});
1301 return std::unexpected(staged.error());
1303 auto valid = (*staged)->validate();
1305 return std::unexpected(error(ManagedPhase::INPUT, node, valid.error()));
1307 auto invalidated = (*staged)->invalidate();
1309 return std::unexpected(error(ManagedPhase::INPUT, node, invalidated.error()));
1311 auto installed = (*staged)->install();
1313 return std::unexpected(error(ManagedPhase::INPUT, node, installed.error()));
1315 (*staged)->commitHistory();
1316 (*staged)->retire();
1318 }
catch (
const std::bad_alloc &) {
1319 return std::unexpected(error(ManagedPhase::INPUT, node, TreeError::NO_MEMORY));
1321 return std::unexpected(error(ManagedPhase::INPUT, node, TreeError::CALLBACK_FAILED));
1326std::expected<void, ManagedError>
1330 return replaceViewModel(node, std::move(
model), std::move(prepared), options);
1334std::expected<void, ManagedError>
1338 return replaceViewModel(node, std::move(
model), std::move(prepared), options);
1342std::expected<std::optional<PositionResolution>,
ManagedError>
1344 if (owner_ != std::this_thread::get_id()) {
1350 auto allowed = app_.tree().withScope(node, [](
const UiScope &) {
1355 auto entry = find(node);
1356 auto binding = entry ? entry->viewPrepare.template target<ViewPreparation<T, VirtualList<T>>>() :
nullptr;
1360 return binding->restoration && binding->restoration->attempted ? std::optional(binding->restoration->resolution)
1365std::expected<std::optional<PositionResolution>,
ManagedError>
1367 if (owner_ != std::this_thread::get_id()) {
1373 auto allowed = app_.tree().withScope(node, [](
const UiScope &) {
1378 auto entry = find(node);
1379 auto binding = entry ? entry->viewPrepare.template target<ViewPreparation<T, VirtualTable<T>>>() :
nullptr;
1383 return binding->restoration && binding->restoration->attempted ? std::optional(binding->restoration->resolution)
1392 auto source = modelSource(
model, parent);
1395 return std::unexpected(source.error());
1398 auto range = (*source)->model->openRange();
1410 return attachView(*node, *source, std::move(prepared));
1418 auto source = modelSource(
model, parent);
1421 return std::unexpected(source.error());
1424 auto range = (*source)->model->openRange();
1436 return attachView(*node, *source, std::move(prepared));
1444 auto source = modelSource(
model, parent);
1447 return std::unexpected(source.error());
1450 auto range = (*source)->model->openRange();
1456 auto node =
emplace<Chart<T>>(parent, std::move(*range), std::move(accessor), options, policy);
1462 return attachView(*node, *source, std::move(prepared), std::move(first));
static std::expected< FinitePositionResolver, SourceError > create(ModelResource resource, SourceStamp session, std::shared_ptr< const ModelSnapshot< T > > snapshot, PositionChangeMap changes={})
Definition model_position_finite.hpp:62
Weak UI handle to a model owned by one ManagedScene. Handles may be copied and destroyed on any threa...
Definition managed_model.hpp:120
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< 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< std::optional< PositionResolution >, ManagedError > restoreStatus(Node< VirtualList< T > > node) const
Definition managed_views.hpp:1343
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< 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 > 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< 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< 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 > id(Node< Widget > node, std::string_view value)
std::expected< void, ManagedError > remove(Node< Widget > node)
Retire one managed subtree and immediately reclaim its managed entry budget.
static std::expected< ModelBookmark, SourceError > create(ModelResource resource, ModelPosition position, std::span< const std::byte > metadata={}, BookmarkOptions options={})
static std::expected< ModelRange, TreeError > read(std::shared_ptr< const ModelSnapshot< T > > owner, RowRange range, std::size_t max_rows)
Read only memory and retain its snapshot. Bounds/provider contract failures are explicit....
Definition model.hpp:244
Immutable list/table provider storage, independent of view/source lifetime. Implement read as bounded...
Definition model.hpp:94
static std::expected< std::unique_ptr< Model >, TreeError > create(WidgetTree &tree, Node< Widget > context, std::shared_ptr< const ModelSnapshot< T > > initial, ModelOptions options={})
Create two bounded Scheduler endpoints in the context's scope; initial snapshot is required.
Definition model.hpp:900
Copyable typed observer; never owns or exposes an unchecked widget pointer.
Definition widget.hpp:92
Immutable bounded provider proof between two revisions of a finite order. The provider must report al...
Definition model_position.hpp:224
UI-owned scope disconnecting all its subscriptions and timers, in any token order....
Definition scheduler.hpp:154
One UI-owned view with bounded owning row text and one independent model consumer....
Definition virtual_list.hpp:133
One UI-owned table with bounded owning cell text and one independent model consumer....
Definition virtual_table.hpp:154
std::expected< VisibleModelSnapshot< T >, VisibleModelReadError > visibleSnapshot(const NodeGeometry &geometry) const
Capture prepared ready body rows intersecting final arranged geometry.
Definition virtual_table.hpp:215
Copyable immutable ready values for one physically visible table interval.
Definition visible_model.hpp:31
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
Public Portals API.
Definition action.hpp:8
std::expected< ActionBinding, TreeError > bindVirtualTable(EventRouter &router, WidgetTree &tree, Node< VirtualTable< T > > node)
Bind arrows/Home/End, left press and integral wheel scrolling to the existing router....
Definition virtual_table.hpp:870
@ FORWARD
Prefer the following item; an end boundary falls back to the preceding item.
Definition model_position.hpp:43
std::variant< ManagedError, VisibleModelReadError > VisibleModelError
Exact scene access failure or owning table preparation/provider failure.
Definition managed.hpp:43
std::expected< std::optional< ModelRequest< T > >, TreeError > prepareChart(WidgetTree &tree, Node< Chart< T > > node, const ModelFrame< T > &frame, CellSize viewport, std::uint64_t first=0)
Prepare at most one domain bucket per viewport column between frames. Shares the caller's ModelFrame ...
Definition chart.hpp:349
std::expected< ActionBinding, TreeError > bindVirtualList(EventRouter &router, WidgetTree &tree, Node< VirtualList< T > > node)
Bind arrows/Home/End, left press and integral wheel scrolling to the existing router....
Definition virtual_list.hpp:718
@ NOT_PREPARED
No current preparation, including after scroll or configuration changes.
Definition visible_model.hpp:12
PositionKind
Position interpretation; a row, a gap, and a text mark are not interchangeable.
Definition model_position.hpp:35
@ ITEM
Full RowId with a version-qualified ordinal hint.
Definition model_position.hpp:36
@ GAP
Boundary between rows, including the entry and end gaps.
Definition model_position.hpp:37
@ READY
Exactly the requested immutable rows are available.
Definition model.hpp:47
@ PENDING
Data is not ready; reading must not block or start work.
Definition model.hpp:46
PositionResolution
Successful protocol outcomes; absence of support differs from missing history.
Definition model_position.hpp:123
@ UNAVAILABLE
Supported position history or storage is no longer available.
Definition model_position.hpp:130
@ UNSUPPORTED
The provider does not implement the requested kind or identity capability.
Definition model_position.hpp:128
@ INCOMPATIBLE
Resource, lineage or change proof cannot identify this position safely.
Definition model_position.hpp:129
@ NEAREST
The original item was removed; a declared surviving neighbor was selected.
Definition model_position.hpp:125
@ EMPTY
Compatible source is empty and has no current item.
Definition model_position.hpp:126
@ EXACT
The same item or a proven mapped gap/mark is present.
Definition model_position.hpp:124
@ PENDING
Provider has not materialized the required bounded data yet.
Definition model_position.hpp:127
std::expected< std::optional< ModelRequest< T > >, TreeError > prepareVirtualList(WidgetTree &tree, Node< VirtualList< T > > node, const ModelFrame< T > &frame, CellSize viewport)
Prepare a local final viewport between frames, using the same pin as every sibling view....
Definition virtual_list.hpp:624
@ REMEMBER
Restore this navigation session's saved resource position.
Definition managed_navigation.hpp:33
@ RESET
Forget the target checkpoint and use its initial position/selection.
Definition managed_navigation.hpp:34
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
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
@ LAYOUT
Read final arranged geometry or deliver a deferred owning layout observation.
Definition managed_diagnostics.hpp:58
@ STATE
Create and retain a scene-owned property.
Definition managed_diagnostics.hpp:50
@ MOUNT
Create the scene root or attach and register a managed widget.
Definition managed_diagnostics.hpp:49
@ 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
@ PREPARE
Synchronize managed presentation, focus and pending updates before a frame.
Definition managed_diagnostics.hpp:53
std::expected< std::optional< ModelRequest< T > >, TreeError > prepareVirtualTable(WidgetTree &tree, Node< VirtualTable< T > > node, const ModelFrame< T > &frame, const Geometry &layout)
Prepare a table using its captured local layout extent, including its header.
Definition virtual_preparation.hpp:50
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
@ FOUND
The index identifies this RowId in the same snapshot.
Definition model.hpp:74
@ UNSUPPORTED
Provider does not implement an identity index; ordinal scrolling remains available.
Definition model.hpp:72
@ NOT_FOUND
Provider supports lookup, but this full RowId is absent.
Definition model.hpp:73
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
@ 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
Checked bookmark capacity, independent of logical source length.
Definition model_position.hpp:57
Owning chart settings, validated during preparation.
Definition chart.hpp:61
Original error plus independent runner/restoration and cleanup failures.
Definition managed_diagnostics.hpp:62
Finite per-model storage and work budgets; all fields must be positive.
Definition model.hpp:165
Explicit rebinding policy; omitted history options inherit the session's settings.
Definition managed_navigation.hpp:44
Independent opt-in view channels; scrolling never changes current by itself.
Definition managed_navigation.hpp:108
Owning independent policies for width and height.
Definition layout.hpp:35
A typed owning column definition; identity is independent of visual order.
Definition virtual_table.hpp:25
Owning fixed-row presentation settings; invalid heights are rejected at preparation.
Definition virtual_list.hpp:18
Owning table settings; preparation rejects invalid dimensions and exceeded budgets....
Definition virtual_table.hpp:13
Owning preparation/provider failure, independent of the table and provider lifetime.
Definition visible_model.hpp:18