Portals0.7.0 · dev (544a5c68c72e · 2026-11-28 UTC)
Loading...
Searching...
No Matches
managed_views.hpp
1// Copyright (c) 2026 ttldtor.
2// SPDX-License-Identifier: BSL-1.0
3#pragma once
4
5// Included by managed.hpp after the scene definition; no additional runtime lives here.
6namespace portals {
7template <class T>
8std::expected<VisibleModelSnapshot<T>, VisibleModelError>
10 auto allowed = boundary(ManagedPhase::LAYOUT, node);
11
12 if (!allowed) {
13 return std::unexpected(allowed.error());
14 }
15
16 auto revision = app_.tree().geometryRevision();
17
18 if (!revision) {
19 return std::unexpected(error(ManagedPhase::PREPARE, node, revision.error()));
20 }
21
22 if (*revision != layoutRevision_) {
24 }
25
26 auto shown = detail::listShown(app_.tree(), node);
27
28 if (!shown) {
29 return std::unexpected(error(ManagedPhase::PREPARE, node, shown.error()));
30 }
31
32 if (!*shown) {
34 }
35
36 auto geometry = app_.tree().observeGeometry(node);
37
38 if (!geometry) {
39 return std::unexpected(error(ManagedPhase::PREPARE, node, geometry.error()));
40 }
41
42 std::expected<VisibleModelSnapshot<T>, VisibleModelError> result;
43 auto read = app_.tree().read(node, [&](const VirtualTable<T> &table) {
44 try {
45 auto snapshot = table.visibleSnapshot(geometry->geometry);
46
47 if (snapshot) {
48 result = std::move(*snapshot);
49 } else {
50 result = std::unexpected(std::move(snapshot.error()));
51 }
52 } catch (const std::bad_alloc &) {
53 result = std::unexpected(error(ManagedPhase::PREPARE, node, TreeError::NO_MEMORY));
54 }
55 });
56
57 if (!read) {
58 return std::unexpected(error(ManagedPhase::PREPARE, node, read.error()));
59 }
60
61 return result;
62}
63
64template <class T>
65std::expected<ManagedModel<T>, ManagedError> ManagedScene::model(std::shared_ptr<const ModelSnapshot<T>> initial,
66 ModelOptions options, ManagedViewHandler<T> prepared) {
67 auto allowed = boundary(ManagedPhase::STATE, root_);
68
69 if (!allowed) {
70 return std::unexpected(allowed.error());
71 }
72
73 if (models_.size() >= options_.maxModels) {
74 return std::unexpected(error(ManagedPhase::STATE, root_, TreeError::NODE_LIMIT));
75 }
76
77 try {
78 auto created = Model<T>::create(app_.tree(), root_, std::move(initial), options);
79
80 if (!created) {
81 return std::unexpected(error(ManagedPhase::STATE, root_, created.error()));
82 }
83
84 auto source = std::make_shared<detail::ManagedModelSourceOf<T>>();
85 ManagedModel<T> handle;
86
87 source->model = std::move(*created);
88 source->scene = root_.id();
89 if (rowOrigin_) {
90 source->origin = rowOrigin_;
91 source->receiver = rowOrigin_->node;
92 }
93 if (prepared) {
94 source->preparation = std::make_shared<ManagedViewHandler<T>>(std::move(prepared));
95 }
96 handle.source_ = source;
97 handle.owner_ = owner_;
98 models_.push_back(std::move(source));
99
100 return handle;
101 } catch (const std::bad_alloc &) {
102 return std::unexpected(error(ManagedPhase::STATE, root_, TreeError::NO_MEMORY));
103 }
104}
105
106template <class T>
107std::expected<std::shared_ptr<detail::ManagedModelSourceOf<T>>, ManagedError>
108ManagedScene::modelSource(ManagedModel<T> model, Node<Widget> parent) {
109 auto allowed = boundary(ManagedPhase::MOUNT, parent);
110
111 if (!allowed) {
112 return std::unexpected(allowed.error());
113 }
114
115 auto source = model.lock();
116
117 if (!source) {
118 return std::unexpected(error(ManagedPhase::MOUNT, parent, source.error()));
119 }
120
121 if ((*source)->retired || !(*source)->model) {
122 return std::unexpected(error(ManagedPhase::MOUNT, parent, TreeError::CLOSED));
123 }
124
125 if ((*source)->scene != root_.id()) {
126 return std::unexpected(error(ManagedPhase::MOUNT, parent, TreeError::INVALID_ARGUMENT));
127 }
128
129 return *source;
130}
131
133// Keep the binding in the existing preparation slot. Its concrete type lets model replacement
134// inspect the source and callback without adding optional-feature storage to every scene entry.
135template <class T, class W> struct ManagedScene::ViewPreparation {
136 ManagedScene *scene;
137 Node<W> node;
138 std::shared_ptr<detail::ManagedModelSourceOf<T>> source;
139 std::shared_ptr<detail::ManagedPreparedRegistration<T>> registration;
140 ManagedChartOrigin first;
141 [[no_unique_address]] std::conditional_t<std::same_as<W, Chart<T>>, std::monostate,
142 std::shared_ptr<detail::ModelViewRestoreState>> restoration;
143
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();
148
149 if (!live) {
150 if (!source->origin->retired && !source->origin->closed) {
151 return std::unexpected(live.error());
152 }
153
154 scene->pruneLiveText();
155 }
156 }
157
158 return {};
159 };
160 auto live = retireOrigin();
161
162 if (!live) {
163 return live;
164 }
165
166 if (!source->frame) {
167 return std::unexpected(TreeError::INVALID_ARGUMENT);
168 }
169
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);
180 };
181 if (current && reading &&
182 ((restoration->shareCurrent && navigated(*current, restoration->currentRevision)) ||
183 (restoration->shareReading && navigated(*reading, restoration->readingRevision)))) {
184 // A newer explicit navigation command supersedes the retained restore intent.
185 restoration->pending.reset();
186 restoration->attempted = false;
187 auto cleared = scene->app_.tree().edit(node, [](W &view) {
188 view.preparedSuppressed_ = false;
189 });
190 if (!cleared) {
191 return cleared;
192 }
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;
208 });
209 if (!cleared) {
210 return cleared;
211 }
212 }
213 }
214 }
215 }
216 if (restoration && restoration->pending) {
217 auto retained = restoration;
218 auto model = source;
219 const auto lifetime = std::weak_ptr<const void>(scene->lifetime_);
220 auto shown = detail::listShown(scene->app_.tree(), node);
221 if (!shown) {
222 return std::unexpected(shown.error());
223 }
224 if (!*shown) {
225 return {};
226 }
227 const auto revision = source->frame->revision();
228 const auto proofRevision = source->navigationRevision;
229
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);
237
238 if (lifetime.expired()) {
239 return std::unexpected(TreeError::CLOSED);
240 }
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);
245 }
246 if (source->retired || !source->frame || source->frame->revision() != revision ||
247 source->navigationRevision != proofRevision) {
248 return {};
249 }
250
251 if (!resolved) {
252 return std::unexpected(resolved.error());
253 }
254
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)
265 : std::nullopt;
266 // A uint64 row with the default zero fraction is always valid.
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)
270 : std::nullopt;
271 view.anchorRevision_ = source->frame->dataRevision();
272 view.dirty_ = true;
273 view.preparedSuppressed_ = false;
274 });
275
276 if (!installed) {
277 return installed;
278 }
279 restoration->pending.reset();
280 }
281 }
282
283 if (restoration->pending) {
284 // A saved unresolved anchor has no safe row-zero substitute. Readiness
285 // publications retry it; redraw alone does not start another attempt.
286 return {};
287 }
288 }
289 }
290
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();
296 view.request_ = {};
297 view.consumer_ = {};
298 });
299
300 if (!detached) {
301 return detached;
302 }
303 }
304 }
305
306 auto navigation = scene->navigationBefore(node);
307
308 if (!navigation) {
309 return navigation;
310 }
311
312 auto work = [&]() -> std::expected<std::optional<ModelRequest<T>>, TreeError> {
313 if constexpr (std::same_as<W, VirtualList<T>>) {
314 return prepareVirtualList(scene->app_.tree(), node, *source->frame, layout);
315 } else if constexpr (std::same_as<W, VirtualTable<T>>) {
316 return prepareVirtualTable(scene->app_.tree(), node, *source->frame, layout);
317 } else {
318 auto origin = first ? first() : std::expected<std::uint64_t, TreeError>(0);
319
320 if (!origin) {
321 return std::unexpected(origin.error());
322 }
323
324 return prepareChart(scene->app_.tree(), node, *source->frame, layout, *origin);
325 }
326 }();
327
328 if (!work) {
329 return std::unexpected(work.error());
330 }
331
332 navigation = scene->navigationAfter(node);
333
334 if (!navigation) {
335 return navigation;
336 }
337
338 live = retireOrigin();
339
340 if (!live) {
341 return live;
342 }
343
344 if (source->retired) {
345 return {};
346 }
347
348 // Disconnecting registration never destroys the std::function currently being invoked.
349 auto action = registration && registration->action ? registration->action : source->preparation;
350
351 if (action) {
352 try {
353 auto result = (*action)(*source->frame, *work);
354 auto retired = retireOrigin();
355
356 return result ? retired : result;
357 } catch (...) {
358 (void)retireOrigin();
359 throw;
360 }
361 }
362
363 // Without a provider callback there is nobody to retain and dispatch a receipt.
364 if (*work) {
365 (*work)->cancel();
366
367 return std::unexpected(TreeError::INVALID_ARGUMENT);
368 }
369
370 return {};
371 }
372};
373
375
376template <class T, class W>
377std::expected<detail::ModelViewCheckpoint, TreeError>
378ManagedScene::captureViewCheckpoint(Node<W> node, const std::shared_ptr<detail::ManagedModelSourceOf<T>> &source,
379 BookmarkOptions options) {
380 auto resource = detail::modelNavigationResource(*source);
381 if (!resource) {
382 return std::unexpected(resource.error());
383 }
384
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{};
390 bool versionKnown{};
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_) {
396 versionKnown = true;
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;
401 break;
402 }
403 }
404 } else if (anchor) {
405 versionKnown = true;
406 revision = view.anchorRevision_;
407 }
408 });
409 if (!read) {
410 return std::unexpected(read.error());
411 }
412 if (!versionKnown) {
413 auto pinned = source->pin();
414 if (!pinned) {
415 return std::unexpected(pinned.error());
416 }
417 revision = source->frame->dataRevision();
418 }
419 const auto readingRevision = revision;
420
421 if (!revision) {
422 // Data-only models may be unversioned. Retain unsupported metadata without
423 // inventing a positive bookmark revision or rejecting a healthy new binding.
424 value.selection.resource_ = *resource;
425 if (selected) {
426 value.currentResolution = PositionResolution::UNSUPPORTED;
427 value.selection.rows_ = std::make_shared<const std::vector<RowId>>(std::initializer_list<RowId>{*selected});
428 value.selection.resolution_ = PositionResolution::UNSUPPORTED;
429 }
430 value.readingResolution = PositionResolution::UNSUPPORTED;
431 return value;
432 }
433
434 if (selected && !selectedOffset) {
435 auto located = source->frame->locateRow(*selected);
436 if (!located) {
437 return std::unexpected(located.error());
438 }
439 if (located->state != RowLookupState::FOUND) {
440 return std::unexpected(TreeError::WOULD_BLOCK);
441 }
442 selectedOffset = located->index;
443 revision = source->frame->dataRevision();
444 }
445 auto make = [&](PositionKind kind, RowId row, std::uint64_t offset, std::uint64_t dataRevision) {
446 return ModelBookmark::create(*resource, {kind, row, offset, dataRevision, PositionAffinity::FORWARD}, {}, options);
447 };
448 if (selected) {
449 auto mark = make(PositionKind::ITEM, *selected, *selectedOffset, revision);
450 if (!mark) {
451 return std::unexpected(detail::navigationTreeError(mark.error()));
452 }
453 value.current = std::move(*mark);
454 value.currentResolution = PositionResolution::EXACT;
455 value.selection.rows_ = std::make_shared<const std::vector<RowId>>(std::initializer_list<RowId>{*selected});
456 value.selection.resolution_ = PositionResolution::EXACT;
457 }
458 value.selection.resource_ = *resource;
459 auto reading =
460 make(anchor ? PositionKind::ITEM : PositionKind::GAP, anchor.value_or(RowId{}), value.first, readingRevision);
461 if (!reading) {
462 return std::unexpected(detail::navigationTreeError(reading.error()));
463 }
464 value.reading = std::move(*reading);
465 value.readingResolution = PositionResolution::EXACT;
466
467 return value;
468}
469
470template <class T>
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()) {
475 return {};
476 }
477 if (source->frame && !source->frame->dataRevision()) {
478 value.selection.resolution_ = PositionResolution::UNSUPPORTED;
479 return {};
480 }
481 if (value.selectedPositions) {
482 return {};
483 }
484 if (!source->frame || value.selection.resource() != source->navigationResource) {
485 return std::unexpected(TreeError::WOULD_BLOCK);
486 }
487 const auto frame = *source->frame;
488 auto positions = history->selectedPositions(value.selection.rows().size());
489 if (!positions) {
490 return std::unexpected(positions.error());
491 }
492 for (auto id : value.selection.rows()) {
493 auto located = frame.locateRow(id);
494 if (!located) {
495 return std::unexpected(located.error());
496 }
497 if (located->state != RowLookupState::FOUND) {
498 return std::unexpected(TreeError::WOULD_BLOCK);
499 }
500 auto position = ModelBookmark::create(
501 value.selection.resource(),
502 {PositionKind::ITEM, id, located->index, frame.dataRevision(), PositionAffinity::FORWARD}, {}, options);
503 if (!position) {
504 return std::unexpected(detail::navigationTreeError(position.error()));
505 }
506 (*positions)->positions.push_back(std::move(*position));
507 }
508 value.selectedPositions = std::move(*positions);
509 return {};
510}
511
512template <class T>
513std::expected<detail::ModelViewCheckpoint, TreeError> ManagedScene::resolveViewCheckpoint(
514 detail::ModelViewCheckpoint value, const std::shared_ptr<detail::ManagedModelSourceOf<T>> &source,
515 const std::shared_ptr<detail::ModelViewHistory> &history, BookmarkOptions options, PositionResolution &resolution,
516 PositionChangeMap changes, const detail::ModelRestoreChannels *requestedChannels) {
517 if (!source->frame) {
518 return std::unexpected(TreeError::WOULD_BLOCK);
519 }
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;
525 }
526 auto resource = detail::modelNavigationResource(*source);
527 if (!resource) {
528 return std::unexpected(resource.error());
529 }
530 if (!frame.dataRevision()) {
531 auto unavailable = [&](const std::optional<ModelBookmark> &bookmark, PositionResolution previous) {
532 if (!bookmark && !detail::unresolvedPosition(previous)) {
534 }
536 return previous;
537 }
538 if ((bookmark && bookmark->resource() != *resource) ||
539 (!bookmark && value.selection.resource().identity.instance && value.selection.resource() != *resource)) {
541 }
543 };
544 if (channels.current) {
545 value.currentResolution = unavailable(value.current, value.currentResolution);
546 }
547 if (channels.reading) {
548 value.readingResolution = unavailable(value.reading, value.readingResolution);
549 }
550 if (channels.selection && !value.selection.rows().empty()) {
551 value.selection.resolution_ =
552 value.selection.resource() == *resource ? PositionResolution::UNSUPPORTED : PositionResolution::INCOMPATIBLE;
553 }
554 const std::array outcomes{value.currentResolution, value.readingResolution, value.selection.resolution()};
555 const std::array enabled{channels.current, channels.reading, channels.selection};
556 resolution = frame.rowCount() ? PositionResolution::EXACT : PositionResolution::EMPTY;
557 for (std::size_t index = 0; index < outcomes.size(); ++index) {
558 if (enabled[index] && detail::unresolvedPosition(outcomes[index])) {
559 resolution = outcomes[index];
560 break;
561 }
562 }
563 return value;
564 }
565 auto resolver = FinitePositionResolver<T>::create(*resource, resource->identity, frame.snapshot(), changes);
566 if (!resolver) {
567 return std::unexpected(detail::navigationTreeError(resolver.error()));
568 }
569 for (bool reading : {false, true}) {
570 if (reading ? !channels.reading : !channels.current) {
571 continue;
572 }
573 auto *bookmark = reading ? &value.reading : &value.current;
574 auto &outcome = reading ? value.readingResolution : value.currentResolution;
575 if (!*bookmark) {
576 if (!detail::unresolvedPosition(outcome)) {
578 } else if (value.selection.resource().identity.instance && value.selection.resource() != *resource) {
580 }
581 continue;
582 }
583 auto position = (*bookmark)->position();
584 std::optional<PositionReply> reply;
585 if ((*bookmark)->resource() == *resource && position.kind == PositionKind::ITEM &&
586 (*bookmark)->metadata().empty()) {
587 auto located = frame.locateRow(position.row);
588 if (!located) {
589 return std::unexpected(located.error());
590 }
591 if (located->state == RowLookupState::FOUND) {
592 position.offset = located->index;
593 position.revision = frame.dataRevision();
594 reply =
595 PositionReply{*resource, resource->identity, frame.dataRevision(), 1, PositionResolution::EXACT, position};
596 } else if (located->state == RowLookupState::UNSUPPORTED && position.revision == frame.dataRevision()) {
597 // A revision-qualified hint is verified with exactly one bounded row read.
598 auto row = ModelRange<T>::read(frame.snapshot(), {position.offset, 1}, 1);
599 if (!row) {
600 return std::unexpected(row.error());
601 }
602 if (row->state() == RangeState::READY && !row->rows().empty() && row->rows().front().id == position.row) {
603 reply =
604 PositionReply{*resource, resource->identity, frame.dataRevision(), 1, PositionResolution::EXACT, position};
605 } else if (row->state() == RangeState::PENDING) {
606 reply =
607 PositionReply{*resource, resource->identity, frame.dataRevision(), 1, PositionResolution::PENDING, {}};
608 }
609 }
610 }
611 if (!reply) {
612 auto resolved = resolver->resolve({resource->identity, frame.dataRevision(), 1, **bookmark});
613 if (!resolved) {
614 return std::unexpected(detail::navigationTreeError(resolved.error()));
615 }
616 reply = std::move(*resolved);
617 }
618 outcome = reply->state;
619 if (reply->state == PositionResolution::EXACT || reply->state == PositionResolution::NEAREST) {
620 auto updated = ModelBookmark::create(*resource, reply->position, (*bookmark)->metadata(), options);
621 if (!updated) {
622 return std::unexpected(detail::navigationTreeError(updated.error()));
623 }
624 *bookmark = std::move(*updated);
625 } else if (reply->state == PositionResolution::EMPTY) {
626 bookmark->reset();
627 }
628 }
629 if (value.reading) {
630 value.first = value.reading->position().offset;
631 } else if (!detail::unresolvedPosition(value.readingResolution)) {
632 value.first = 0;
633 }
634 auto aggregate = [&] {
635 bool nearest{};
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]) {
640 continue;
641 }
642 const auto outcome = outcomes[index];
643 if (outcome != PositionResolution::EXACT && outcome != PositionResolution::NEAREST &&
644 outcome != PositionResolution::EMPTY) {
645 return outcome;
646 }
647 nearest = nearest || outcome == PositionResolution::NEAREST;
648 }
649 return !frame.rowCount() ? PositionResolution::EMPTY
652 };
653 if (!channels.selection) {
654 resolution = aggregate();
655 return value;
656 }
657 const bool selectionCompatible = value.selection.resource() == *resource;
658 if (value.selection.rows().empty()) {
659 value.selection.resource_ = *resource;
660 }
661 value.selection.resolution_ = value.selection.rows().empty() ? PositionResolution::EMPTY : PositionResolution::EXACT;
662 if (!value.selection.rows().empty()) {
663 if (!selectionCompatible) {
664 value.selection.resolution_ = PositionResolution::INCOMPATIBLE;
665 resolution = aggregate();
666 return value;
667 }
668 const auto ids = value.selection.rows();
669 const auto hints = value.selectedPositions;
670 if (hints && hints->positions.size() != ids.size()) {
671 return std::unexpected(TreeError::INVALID_ARGUMENT);
672 }
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) {
677 return std::unexpected(TreeError::INVALID_ARGUMENT);
678 }
679 }
680 }
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) {
686 return {};
687 }
688 auto allocated = history->selectedPositions(ids.size());
689 if (!allocated) {
690 return std::unexpected(allocated.error());
691 }
692 positions = std::move(*allocated);
693 positions->positions.insert(positions->positions.end(), hints->positions.begin(),
694 hints->positions.begin() + prefix);
695 return {};
696 };
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)) {
701 return std::unexpected(TreeError::INVALID_ARGUMENT);
702 }
703 auto located = frame.locateRow(id);
704 if (!located) {
705 return std::unexpected(located.error());
706 }
707 const bool currentConfirmed = value.current && value.current->position().row == id &&
708 (value.currentResolution == PositionResolution::EXACT ||
709 value.currentResolution == PositionResolution::NEAREST);
710 if (located->state != RowLookupState::FOUND && !currentConfirmed) {
711 const ModelBookmark *hint{};
712 if (hints) {
713 hint = &hints->positions[index];
714 } else if (originalCurrent && originalCurrent->position().row == id) {
715 hint = &*originalCurrent;
716 }
717 if (located->state == RowLookupState::NOT_FOUND && hint && hint->resource() == *resource &&
718 (!changes || changes.fromRevision() != hint->position().revision) && !requestedHistory) {
719 requestedHistory = true;
720 auto proof = detail::modelPositionHistory(*frame.snapshot(), hint->position().revision);
721 if (!proof) {
722 return std::unexpected(detail::navigationTreeError(proof.error()));
723 }
724 if (proof->state == PositionResolution::UNAVAILABLE) {
725 value.selection.resolution_ = PositionResolution::UNAVAILABLE;
726 resolution = aggregate();
727 return value;
728 }
729 changes = std::move(proof->changes);
730 }
731 if (located->state == RowLookupState::NOT_FOUND && hint && hint->resource() == *resource && changes &&
732 changes.fromRevision() == hint->position().revision) {
733 auto mapped = changes.map(hint->position());
734 if (!mapped) {
735 return std::unexpected(detail::navigationTreeError(mapped.error()));
736 }
737 if (mapped->removed) {
738 if (!selected) {
739 selected = std::make_shared<std::vector<RowId>>(ids.begin(), ids.begin() + index);
740 selected->reserve(ids.size());
741 }
742 auto prepared = preparePositions(index);
743 if (!prepared) {
744 return std::unexpected(prepared.error());
745 }
746 continue;
747 }
748 }
749 value.selection.resolution_ = located->state == RowLookupState::UNSUPPORTED ? PositionResolution::UNSUPPORTED
751 resolution = aggregate();
752 return value;
753 }
754 if (selected) {
755 selected->push_back(id);
756 }
757 if (hints) {
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);
762 if (!prepared) {
763 return std::unexpected(prepared.error());
764 }
765 }
766 if (positions) {
767 auto updated = ModelBookmark::create(
768 *resource, {PositionKind::ITEM, id, offset, frame.dataRevision(), PositionAffinity::FORWARD}, {}, options);
769 if (!updated) {
770 return std::unexpected(detail::navigationTreeError(updated.error()));
771 }
772 positions->positions.push_back(std::move(*updated));
773 }
774 }
775 }
776 if (selected) {
777 value.selection.rows_ = std::move(selected);
778 }
779 if (positions) {
780 value.selectedPositions = std::move(positions);
781 }
782 if (value.selection.rows().empty()) {
783 value.selection.resolution_ = PositionResolution::EMPTY;
784 }
785 }
786 resolution = aggregate();
787 return value;
788}
789
790template <class T, class W>
791std::expected<Node<W>, ManagedError> ManagedScene::attachView(Node<W> node,
792 std::shared_ptr<detail::ManagedModelSourceOf<T>> source,
794 auto fail = [&](TreeError cause) -> std::expected<Node<W>, ManagedError> {
795 auto failure = error(ManagedPhase::BIND, node, cause);
796 auto removed = remove(node);
797
798 if (!removed) {
799 failure.cleanup = std::get<TreeError>(removed.error().cause);
800 }
801
802 return std::unexpected(failure);
803 };
804
805 try {
806 if constexpr (std::same_as<W, VirtualList<T>>) {
807 auto configured = app_.tree().edit(node, [&](W &list) {
808 list.clearMissingSelection_ = source->sinkOnly;
809 });
810 if (!configured) {
811 return fail(configured.error());
812 }
813 }
814 auto entry = find(node);
815
816 std::shared_ptr<detail::ManagedPreparedRegistration<T>> registration;
817 if (handler) {
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();
822 });
823 source->prepared.push_back(registration);
824 }
825
826 // Factory-created nodes cannot carry another binding. Construct the whole callback
827 // before publishing it, so allocation failure retires the new child transactionally.
828 entry->viewSource = source;
829 entry->viewPrepare = ViewPreparation<T, W>{this, node, source, registration, std::move(first)};
830
831 if constexpr (std::same_as<W, VirtualTable<T>> || std::same_as<W, VirtualList<T>>) {
832 auto binding = [&] {
833 if constexpr (std::same_as<W, VirtualTable<T>>) {
834 return bindVirtualTable(app_.router(), app_.tree(), node);
835 } else {
836 return bindVirtualList(app_.router(), app_.tree(), node);
837 }
838 }();
839
840 if (!binding) {
841 return fail(binding.error());
842 }
843
844 entry->binding.template emplace<ActionBinding>(std::move(*binding));
845 }
846
847 const char *type = std::same_as<W, Chart<T>> ? "Chart" : std::same_as<W, VirtualTable<T>> ? "Table" : "List";
848
849 if (!entry->target || entry->target->type.empty()) {
850 auto target = entry->target ? *entry->target : StyleTarget{};
851
852 target.type = type;
853 entry->target = std::make_shared<StyleTarget>(target);
854 }
855
856 entry->stylePending = true;
857 stylesDirty_ = true;
858
859 return node;
860 } catch (const std::bad_alloc &) {
861 return fail(TreeError::NO_MEMORY);
862 } catch (...) {
863 return fail(TreeError::CALLBACK_FAILED);
864 }
865}
866
868
869template <class T, class W> struct ManagedScene::PreparedViewModelChange final : detail::PreparedModelViewChange {
870 ManagedScene *scene{};
871 std::weak_ptr<const void> lifetime;
872 Node<W> node;
873 std::shared_ptr<Entry> entry;
874 std::shared_ptr<detail::ManagedModelSourceOf<T>>
875 previousSource;
876 std::shared_ptr<detail::ManagedModelSourceOf<T>>
877 source;
878 std::shared_ptr<detail::ManagedPreparedRegistration<T>>
879 registration;
880 std::shared_ptr<detail::ModelViewRestoreState>
881 restoration;
882 std::optional<detail::ModelViewHistoryChange> outgoing;
883 std::optional<detail::ModelViewHistoryChange> destination;
884 std::function<std::expected<void, TreeError>(const LayoutSnapshot &)>
885 preparation;
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{};
896 ScrollState scroll;
897 const typename W::Prepared *prepared{};
898 const void *binding{};
899 std::uint64_t sourceRevision{};
900 std::uint64_t navigationRevision{};
901 bool reset{};
902 bool pending{};
903
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);
915 }
916 bool unchanged{};
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;
922 });
923 return !checked ? checked : unchanged ? std::expected<void, TreeError>{} : std::unexpected(TreeError::WOULD_BLOCK);
924 }
925
929 std::expected<void, TreeError> invalidate() const override {
930 return reset ? scene->app_.tree().invalidate(node, Invalidation::PAINT) : std::expected<void, TreeError>{};
931 }
932
936 std::expected<void, TreeError> install() override {
937 return scene->app_.tree().edit(node, [&](W &view) {
938 if (reset) {
939 if (source != previousSource) {
940 previousConsumer = std::move(view.consumer_);
941 view.consumer_ = std::move(consumer);
942 }
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)
949 : std::nullopt;
950 view.intent_.reset();
951 view.intent_revision_ = 0;
952 view.scroll_ = {};
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)
956 : std::nullopt;
957 view.anchorRevision_ = source->frame ? source->frame->dataRevision() : 0;
958 view.dirty_ = true;
959 view.retry_ = false;
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;
967 }
968 }
969 if (registration) {
970 source->prepared.push_back(registration);
971 }
972 entry->viewSource = source;
973 entry->viewPrepare.swap(preparation);
974 });
975 }
976
978 void commitHistory() noexcept override {
979 if (outgoing) {
980 restoration->history->commit(std::move(*outgoing));
981 }
982 if (destination) {
983 restoration->history->commit(std::move(*destination));
984 }
985 }
986
988 void retire() noexcept override {
989 previousRequest.cancel();
990 }
991};
992
994
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,
998 std::optional<ManagedViewHandler<T>> prepared, ModelRebindOptions options,
999 std::shared_ptr<detail::ModelViewHistory> history,
1000 const detail::ModelViewCheckpoint *sharedPosition,
1001 const NavigationBindingOptions *sharing) {
1002 auto entry = find(node);
1003 auto binding = entry ? entry->viewPrepare.template target<ViewPreparation<T, W>>() : nullptr;
1004 if (!binding) {
1005 return std::unexpected(error(ManagedPhase::INPUT, node, TreeError::INVALID_ARGUMENT));
1006 }
1007 auto fail = [&](TreeError failure) -> std::expected<std::unique_ptr<detail::PreparedModelViewChange>, ManagedError> {
1008 return std::unexpected(error(ManagedPhase::INPUT, node, failure));
1009 };
1010 auto plan = std::make_unique<PreparedViewModelChange<T, W>>();
1011 plan->scene = this;
1012 plan->lifetime = lifetime_;
1013 plan->node = node;
1014 plan->entry = entry;
1015 plan->previousSource = binding->source;
1016 plan->source = source;
1017 plan->navigationRevision = source->navigationRevision;
1018 plan->binding = binding;
1019 plan->reset = plan->previousSource != source || options.restore == ModelRestorePolicy::RESET;
1020 auto saved = binding->restoration;
1021 if (!history) {
1022 history = saved ? saved->history : nullptr;
1023 }
1024 if (!history) {
1025 auto created = detail::ModelViewHistory::create(lifetime_, options.checkpoints.value_or(ModelCheckpointOptions{}));
1026 if (!created) {
1027 return fail(created.error());
1028 }
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)) {
1033 return fail(TreeError::INVALID_ARGUMENT);
1034 }
1035 auto stateCredit = history->reserveState();
1036 if (!stateCredit) {
1037 return fail(stateCredit.error());
1038 }
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;
1052 } else {
1053 auto role = history->role();
1054 if (!role) {
1055 return fail(role.error());
1056 }
1057 plan->restoration->role = *role;
1058 auto credit = history->reserveRole();
1059 if (!credit) {
1060 return fail(credit.error());
1061 }
1062 plan->restoration->participant = std::make_shared<SourceCredit>(std::move(*credit));
1063 }
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
1067 : nullptr);
1068 if (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 &registration) {
1072 return registration.expired();
1073 });
1074 source->prepared.reserve(source->prepared.size() + 1);
1075 }
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();
1084 });
1085 if (!observed) {
1086 return fail(observed.error());
1087 }
1088 if (!sharedPosition) {
1089 auto pinned = source->pin();
1090 if (!pinned || plan->lifetime.expired()) {
1091 return fail(!pinned ? pinned.error() : TreeError::CLOSED);
1092 }
1093 }
1094 plan->sourceRevision = source->frame ? source->frame->revision() : 0;
1095 if (plan->reset) {
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);
1103 }
1104 if (plan->previousSource->navigationResource == source->navigationResource) {
1105 continuation = std::move(*captured);
1106 } else {
1107 auto outgoing = history->stage(plan->previousSource, plan->restoration->role, std::move(*captured),
1108 plan->restoration->participant);
1109 if (!outgoing) {
1110 return fail(outgoing.error());
1111 }
1112 plan->outgoing = std::move(*outgoing);
1113 }
1114 }
1115 auto cached = history->find(source, plan->restoration->role);
1116 auto target =
1117 options.restore == ModelRestorePolicy::REMEMBER && cached ? cached->value : detail::ModelViewCheckpoint{};
1118 if (continuation && options.restore == ModelRestorePolicy::REMEMBER) {
1119 target = std::move(*continuation);
1120 }
1121 if (sharedPosition) {
1122 if (!sharing || sharing->current) {
1123 target.current = sharedPosition->current;
1124 }
1125 target.selection = sharedPosition->selection;
1126 target.selectedPositions = sharedPosition->selectedPositions;
1127 if (sharedPosition->reading) {
1128 target.reading = sharedPosition->reading;
1129 }
1130 }
1131 if (detail::hasModelRestoreIntent(target)) {
1132 plan->restoration->attempted = true;
1133 const auto unresolved = target;
1134 auto shown = detail::listShown(app_.tree(), node);
1135 if (!shown) {
1136 return fail(shown.error());
1137 }
1138 if (*shown) {
1139 auto resolved = resolveViewCheckpoint<T>(std::move(target), source, history, history->options().bookmarks,
1140 plan->restoration->resolution);
1141 if (!resolved || plan->lifetime.expired()) {
1142 return fail(!resolved ? resolved.error() : TreeError::CLOSED);
1143 }
1144 target = std::move(*resolved);
1145 } else {
1146 plan->restoration->resolution = PositionResolution::PENDING;
1147 }
1148 plan->pending = !*shown || (plan->restoration->resolution != PositionResolution::EXACT &&
1149 plan->restoration->resolution != PositionResolution::NEAREST &&
1150 plan->restoration->resolution != PositionResolution::EMPTY);
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;
1154 } else {
1155 plan->restoration->pending.reset();
1156 plan->restoration->attempted = false;
1157 }
1158 plan->target = target;
1159 if (options.restore == ModelRestorePolicy::RESET || detail::hasModelRestoreIntent(target)) {
1160 auto destination = history->stage(source, plan->restoration->role, target, plan->restoration->participant);
1161 if (!destination) {
1162 return fail(destination.error());
1163 }
1164 plan->destination = std::move(*destination);
1165 }
1166 if (plan->previousSource != source) {
1167 auto opened = source->model->openRange();
1168 if (!opened) {
1169 return fail(opened.error());
1170 }
1171 plan->consumer = std::move(*opened);
1172 }
1173 }
1174 if (!plan->sourceRevision) {
1175 plan->sourceRevision = source->frame ? source->frame->revision() : 0;
1176 }
1177 plan->preparation = ViewPreparation<T, W>{this, node, source, plan->registration, {}, plan->restoration};
1178 return std::unique_ptr<detail::PreparedModelViewChange>(std::move(plan));
1179}
1180
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);
1186
1187 if (!allowed) {
1188 return allowed;
1189 }
1190
1191 auto entry = find(node);
1192 auto binding = entry ? entry->viewPrepare.template target<ViewPreparation<T, W>>() : nullptr;
1193
1194 if (!binding) {
1195 return std::unexpected(error(ManagedPhase::INPUT, node, TreeError::INVALID_ARGUMENT));
1196 }
1197
1198 auto source = model.lock();
1199
1200 if (!source) {
1201 return std::unexpected(error(ManagedPhase::INPUT, node, source.error()));
1202 }
1203
1204 if ((*source)->retired || !(*source)->model) {
1205 return std::unexpected(error(ManagedPhase::INPUT, node, TreeError::CLOSED));
1206 }
1207
1208 if ((*source)->scene != root_.id()) {
1209 return std::unexpected(error(ManagedPhase::INPUT, node, TreeError::INVALID_ARGUMENT));
1210 }
1211
1212 const bool sameModel = binding->source == *source;
1213
1214 // Callback-only changes do not navigate: in particular, they must not rebuild
1215 // channel outcomes or revoke a caller's outstanding beginResolve receipt.
1216 if (sameModel && prepared && options.restore == ModelRestorePolicy::REMEMBER) {
1217 struct ReplacingCallback {
1218 ManagedScene &scene;
1219 std::weak_ptr<const void> lifetime;
1220
1221 ~ReplacingCallback() {
1222 if (!lifetime.expired()) {
1223 scene.preparing_ = false;
1224 }
1225 }
1226 } guard{*this, lifetime_};
1227
1228 preparing_ = true;
1229 try {
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;
1235 if (action) {
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();
1240 });
1241 (*source)->prepared.reserve((*source)->prepared.size() + 1);
1242 }
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));
1248 }
1249 auto live = app_.tree().withScope(node, [](const UiScope &) {
1250 });
1251 if (!live) {
1252 return std::unexpected(error(ManagedPhase::INPUT, node, live.error()));
1253 }
1254 if (registration) {
1255 (*source)->prepared.push_back(registration);
1256 }
1257 entry->viewPrepare.swap(next);
1258 return {};
1259 } catch (const std::bad_alloc &) {
1260 return std::unexpected(error(ManagedPhase::INPUT, node, TreeError::NO_MEMORY));
1261 } catch (...) {
1262 return std::unexpected(error(ManagedPhase::INPUT, node, TreeError::CALLBACK_FAILED));
1263 }
1264 }
1265
1266 if (navigation_) {
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));
1271 }
1272 if (auto record = member->context.lock()) {
1273 return replaceNavigationModel(record, std::move(model), options, node, std::move(prepared));
1274 }
1275 }
1276 }
1277 }
1278
1279 if (sameModel && !prepared && options.restore == ModelRestorePolicy::REMEMBER) {
1280 return {};
1281 }
1282
1283 // Model admission and retiring old storage can release provider-owned data. Block scene
1284 // reentry until the whole transaction (including callback destruction) has completed.
1285 struct Rebinding {
1286 ManagedScene &scene;
1287 std::weak_ptr<const void> lifetime;
1288
1289 ~Rebinding() {
1290 if (!lifetime.expired()) {
1291 scene.preparing_ = false;
1292 }
1293 }
1294 } guard{*this, lifetime_};
1295
1296 preparing_ = true;
1297
1298 try {
1299 auto staged = prepareViewModelChange<T>(node, *source, std::move(prepared), options, {});
1300 if (!staged) {
1301 return std::unexpected(staged.error());
1302 }
1303 auto valid = (*staged)->validate();
1304 if (!valid) {
1305 return std::unexpected(error(ManagedPhase::INPUT, node, valid.error()));
1306 }
1307 auto invalidated = (*staged)->invalidate();
1308 if (!invalidated) {
1309 return std::unexpected(error(ManagedPhase::INPUT, node, invalidated.error()));
1310 }
1311 auto installed = (*staged)->install();
1312 if (!installed) {
1313 return std::unexpected(error(ManagedPhase::INPUT, node, installed.error()));
1314 }
1315 (*staged)->commitHistory();
1316 (*staged)->retire();
1317 return {};
1318 } catch (const std::bad_alloc &) {
1319 return std::unexpected(error(ManagedPhase::INPUT, node, TreeError::NO_MEMORY));
1320 } catch (...) {
1321 return std::unexpected(error(ManagedPhase::INPUT, node, TreeError::CALLBACK_FAILED));
1322 }
1323}
1324
1325template <class T>
1326std::expected<void, ManagedError>
1328 std::type_identity_t<std::optional<ManagedViewHandler<T>>> prepared,
1329 ModelRebindOptions options) {
1330 return replaceViewModel(node, std::move(model), std::move(prepared), options);
1331}
1332
1333template <class T>
1334std::expected<void, ManagedError>
1336 std::type_identity_t<std::optional<ManagedViewHandler<T>>> prepared,
1337 ModelRebindOptions options) {
1338 return replaceViewModel(node, std::move(model), std::move(prepared), options);
1339}
1340
1341template <class T>
1342std::expected<std::optional<PositionResolution>, ManagedError>
1344 if (owner_ != std::this_thread::get_id()) {
1345 return std::unexpected(error(ManagedPhase::STATE, node, TreeError::WRONG_THREAD));
1346 }
1347 if (closed_) {
1348 return std::unexpected(error(ManagedPhase::STATE, node, TreeError::CLOSED));
1349 }
1350 auto allowed = app_.tree().withScope(node, [](const UiScope &) {
1351 });
1352 if (!allowed) {
1353 return std::unexpected(error(ManagedPhase::STATE, node, allowed.error()));
1354 }
1355 auto entry = find(node);
1356 auto binding = entry ? entry->viewPrepare.template target<ViewPreparation<T, VirtualList<T>>>() : nullptr;
1357 if (!binding) {
1358 return std::unexpected(error(ManagedPhase::STATE, node, TreeError::INVALID_ARGUMENT));
1359 }
1360 return binding->restoration && binding->restoration->attempted ? std::optional(binding->restoration->resolution)
1361 : std::nullopt;
1362}
1363
1364template <class T>
1365std::expected<std::optional<PositionResolution>, ManagedError>
1367 if (owner_ != std::this_thread::get_id()) {
1368 return std::unexpected(error(ManagedPhase::STATE, node, TreeError::WRONG_THREAD));
1369 }
1370 if (closed_) {
1371 return std::unexpected(error(ManagedPhase::STATE, node, TreeError::CLOSED));
1372 }
1373 auto allowed = app_.tree().withScope(node, [](const UiScope &) {
1374 });
1375 if (!allowed) {
1376 return std::unexpected(error(ManagedPhase::STATE, node, allowed.error()));
1377 }
1378 auto entry = find(node);
1379 auto binding = entry ? entry->viewPrepare.template target<ViewPreparation<T, VirtualTable<T>>>() : nullptr;
1380 if (!binding) {
1381 return std::unexpected(error(ManagedPhase::STATE, node, TreeError::INVALID_ARGUMENT));
1382 }
1383 return binding->restoration && binding->restoration->attempted ? std::optional(binding->restoration->resolution)
1384 : std::nullopt;
1385}
1386
1387template <class T>
1388std::expected<Node<VirtualTable<T>>, ManagedError>
1390 std::type_identity_t<std::span<const TableColumn<T>>> columns, VirtualTableOptions options,
1391 SizePolicy policy, std::type_identity_t<ManagedViewHandler<T>> prepared) {
1392 auto source = modelSource(model, parent);
1393
1394 if (!source) {
1395 return std::unexpected(source.error());
1396 }
1397
1398 auto range = (*source)->model->openRange();
1399
1400 if (!range) {
1401 return std::unexpected(error(ManagedPhase::MOUNT, parent, range.error()));
1402 }
1403
1404 auto node = emplace<VirtualTable<T>>(parent, std::move(*range), columns, options, policy);
1405
1406 if (!node) {
1407 return node;
1408 }
1409
1410 return attachView(*node, *source, std::move(prepared));
1411}
1412
1413template <class T>
1414std::expected<Node<VirtualList<T>>, ManagedError>
1416 std::type_identity_t<ManagedListFormatter<T>> delegate, VirtualListOptions options,
1417 SizePolicy policy, std::type_identity_t<ManagedViewHandler<T>> prepared) {
1418 auto source = modelSource(model, parent);
1419
1420 if (!source) {
1421 return std::unexpected(source.error());
1422 }
1423
1424 auto range = (*source)->model->openRange();
1425
1426 if (!range) {
1427 return std::unexpected(error(ManagedPhase::MOUNT, parent, range.error()));
1428 }
1429
1430 auto node = emplace<VirtualList<T>>(parent, std::move(*range), std::move(delegate), options, policy);
1431
1432 if (!node) {
1433 return node;
1434 }
1435
1436 return attachView(*node, *source, std::move(prepared));
1437}
1438
1439template <class T>
1440std::expected<Node<Chart<T>>, ManagedError>
1442 ChartOptions options, ManagedChartOrigin first,
1443 std::type_identity_t<ManagedViewHandler<T>> prepared, SizePolicy policy) {
1444 auto source = modelSource(model, parent);
1445
1446 if (!source) {
1447 return std::unexpected(source.error());
1448 }
1449
1450 auto range = (*source)->model->openRange();
1451
1452 if (!range) {
1453 return std::unexpected(error(ManagedPhase::MOUNT, parent, range.error()));
1454 }
1455
1456 auto node = emplace<Chart<T>>(parent, std::move(*range), std::move(accessor), options, policy);
1457
1458 if (!node) {
1459 return node;
1460 }
1461
1462 return attachView(*node, *source, std::move(prepared), std::move(first));
1463}
1464} // namespace portals
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