Portals0.7.0 · dev (544a5c68c72e · 2026-11-28 UTC)
Loading...
Searching...
No Matches
ui_virtual_rows.hpp
1// Copyright (c) 2026 ttldtor.
2// SPDX-License-Identifier: BSL-1.0
3#pragma once
4
5namespace portals::ui::detail {
7
8template <class T, class Source, class Factory>
9struct RowsController : VirtualRowsState,
10 SceneActivity,
11 portals::detail::VirtualRowsModelBinding<T>,
12 portals::detail::EditNavigationParticipant,
13 std::enable_shared_from_this<RowsController<T, Source, Factory>> {
14 RowsController(ManagedScene &owner, Source descriptor, Factory create, ControlContext defaults)
15 : scene(owner), source(std::move(descriptor)), factory(std::move(create)), controls(std::move(defaults)),
16 lifetime(Access::lifetime(owner)) {
17 }
18
19 ~RowsController() override {
20 retire();
21 }
22
23 ManagedScene &scene;
24 Source source;
25 Factory factory;
26 ControlContext controls;
27 std::weak_ptr<const void> lifetime;
28 Node<VirtualRows<T>> node;
29 ManagedModel<T> initialModel;
30 std::shared_ptr<const void> layoutLease;
31 std::optional<ActionBinding> inputBinding;
32 std::optional<ActionBinding> focusBinding;
33 std::shared_ptr<ScrollController> scrollController;
34 std::uint64_t scrollRevision{};
35 std::optional<std::uint64_t> desiredCurrent;
36 std::optional<RowId> desiredCurrentRow;
37
38 struct EnterIntent {
39 ModelResource resource;
40 std::uint64_t focusGeneration{};
41 };
42
43 std::optional<EnterIntent> pendingEnter;
44 std::size_t retainedColumn{};
45 std::optional<EditFieldKey> retainedField;
46 bool selecting{};
47 std::optional<RowId> restoredCurrent;
48 std::vector<std::shared_ptr<RowAssignment<T>>> rows = std::vector<std::shared_ptr<RowAssignment<T>>>(0);
49 std::shared_ptr<RowAssignment<T>> editPin;
50 std::weak_ptr<portals::detail::ManagedModelSourceOf<T>> previousSource;
51 std::uint64_t revision{};
52 std::uint64_t dataRevision{};
53 std::uint64_t desiredFirst{};
54 CellSize viewport;
55 bool dirty{true};
56 std::optional<bool> desiredAutoHeight;
57 std::uint64_t measuredGeometryRevision{};
58 std::uint64_t blockedGeometryRevision{};
59 bool recordHasBefore{};
60 bool recordHasAfter{};
61 bool allowEndBackfill{};
62 bool lastPage{};
63 std::int32_t desiredCellOffset{};
64 std::int64_t pendingCells{};
65 bool offsetFromEnd{};
66 bool awaitingCellMove{};
67 bool retiredHost{};
68 std::uint64_t intentGeneration{};
69 std::uint64_t committedIntent{};
70 bool resetRestoration{};
71 std::shared_ptr<portals::detail::ModelViewHistory> history;
72 std::uint64_t historyRole{};
73 std::optional<NavigationPosition> observedCurrent;
74 std::optional<NavigationPosition> observedReading;
75
76 struct Attempt {
77 std::weak_ptr<portals::detail::ManagedModelSourceOf<T>> source;
78 std::uint64_t revision{};
79 std::uint64_t intent{};
80 CellSize viewport;
81 } attempt;
82
83 bool blockedAttempt{};
84 Node<Widget> focusedNode;
85 bool deferredRefresh{};
86 double wheelFraction{};
87 std::weak_ptr<portals::detail::ManagedModelSourceOf<T>> consumerSource;
88 std::optional<ModelConsumer<T>> finiteConsumer;
89 std::optional<ModelRequest<T>> finiteRequest;
90 RowRange finiteRange;
91 std::uint64_t finiteRevision{};
92 std::shared_ptr<ModelRange<T>> pendingViewport;
93 std::weak_ptr<portals::detail::ManagedModelSourceOf<T>> pendingViewportSource;
94 RowRange pendingViewportRows;
95 std::uint64_t pendingViewportRevision{};
96
97 std::expected<void, TreeError> replaceModel(Model<T> target, ModelRebindOptions rebind) override try {
98 if (!active()) {
99 return std::unexpected(TreeError::CLOSED);
100 }
101 if constexpr (std::same_as<Source, Navigation<T>>) {
102 auto changed = source.setModel(std::move(target), rebind);
103 if (!changed) {
104 return std::unexpected(EditAccess::cause(changed.error()));
105 }
106 } else {
107 MountContext context;
108 auto model = ModelAccess::resolve(scene, target, context);
109 if (!model) {
110 return std::unexpected(EditAccess::cause(model.error()));
111 }
112 if (!active()) {
113 return std::unexpected(TreeError::CLOSED);
114 }
115 auto actual = RowAccess::source(*model);
116 if (!actual) {
117 return std::unexpected(actual.error());
118 }
119 auto allowed = beforeTransition(nullptr, *actual);
120 if (!allowed) {
121 return allowed;
122 }
123 auto invalidated = RowAccess::tree(scene).invalidate(node, Invalidation::LAYOUT);
124 if (!invalidated) {
125 return invalidated;
126 }
127 auto previous = source;
128 initialModel = *model;
129 source = std::move(target);
130 ModelAccess::publish(context);
131 }
132 resetRestoration = rebind.restore == ModelRestorePolicy::RESET;
133 ++intentGeneration;
134 dirty = true;
135 blockedAttempt = false;
136 return {};
137 } catch (const std::bad_alloc &) {
138 return std::unexpected(TreeError::NO_MEMORY);
139 } catch (...) {
140 return std::unexpected(TreeError::CALLBACK_FAILED);
141 }
142
143 void closed() noexcept override {
144 retire();
145 }
146
147 std::expected<void, TreeError>
148 beforeTransition(const NavigationPosition *next,
149 const std::shared_ptr<portals::detail::ManagedModelSource> &targetSource) override {
150 for (const auto &row : rows) {
151 if (!row->dirty() || row->edit->options.mode != EditMode::ON_COMPLETION) {
152 continue;
153 }
154 const bool sameSource = row->edit->fixed->source == targetSource;
155 const bool visibleTarget = next && next->row && std::ranges::any_of(rows, [&](const auto &entry) {
156 return entry->id == *next->row;
157 });
158 if (!sameSource || !visibleTarget) {
159 return std::unexpected(TreeError::WOULD_BLOCK);
160 }
161 }
162 return {};
163 }
164
165 std::expected<void, TreeError> registerNavigation(ManagedNavigation navigation) {
166 auto record = EditAccess::context(navigation);
167 if (!record) {
168 return std::unexpected(record.error());
169 }
170 if ((*record)->admittingEdit) {
171 return std::unexpected(TreeError::WOULD_BLOCK);
172 }
173 if (!(*record)->editors) {
174 (*record)->editors = std::make_unique<std::vector<std::weak_ptr<portals::detail::EditNavigationParticipant>>>(0);
175 }
176 (*record)->editors->push_back(this->shared_from_this());
177 return {};
178 }
179
180 std::expected<void, TreeError> prepareChrome() {
181 auto glyph = GraphemeText::from(">", scene.widthPolicy());
182 if (!glyph) {
183 return std::unexpected(TreeError::INVALID_ARGUMENT);
184 }
185 this->currentGlyph = std::move(*glyph);
186 auto scope = RowAccess::app(scene).router().focusScope(node, node);
187 if (!scope) {
188 return std::unexpected(scope.error());
189 }
190 focusBinding.emplace(std::move(*scope));
191 auto composite = portals::detail::RowTreeAccess::focusScope(RowAccess::app(scene).router(), node);
192 if (!composite) {
193 return composite;
194 }
195 if (options.scrollbar) {
196 auto controller = ScrollController::create();
197 if (!controller) {
198 return std::unexpected(controller.error());
199 }
200 scrollController = *controller;
201 auto bar = scene.scrollBar(node, scrollController);
202 if (!bar) {
203 return std::unexpected(EditAccess::cause(bar.error()));
204 }
205 this->scrollbar = *bar;
206 auto chrome = portals::detail::RowTreeAccess::focusScope(RowAccess::app(scene).router(), node, {}, *bar);
207 if (!chrome) {
208 return chrome;
209 }
210 auto hidden = RowAccess::tree(scene).setVisible(*bar, false);
211 if (!hidden) {
212 return hidden;
213 }
214 }
215 return {};
216 }
217
218 EventReply handleInput(const RoutedEvent &event) {
219 const auto *mouse = std::get_if<MouseInputEvent>(&event);
220 const auto *key = std::get_if<KeyEvent>(&event);
221 const auto *action = std::get_if<ActionEvent>(&event);
222 if ((key && key->action != KeyAction::RELEASE && key->key == InputKey::F2) ||
223 (action && action->action == portals::Action::ACTIVATE)) {
224 auto entered = this->enterEditing();
225 if (!entered) {
226 this->failure = entered.error();
227 } else {
228 this->failure.reset();
229 }
230 return EventReply::HANDLED;
231 }
232 if (action && action->action == portals::Action::CANCEL) {
233 auto left = this->leaveEditing();
234 if (!left) {
235 this->failure = left.error();
236 } else {
237 this->failure.reset();
238 }
239 return EventReply::HANDLED;
240 }
241 const bool wheel = mouse && mouse->action == MouseAction::SCROLL &&
242 (mouse->button == MouseButton::WHEEL_UP || mouse->button == MouseButton::WHEEL_DOWN);
243 const bool page =
244 key && key->action != KeyAction::RELEASE && (key->key == InputKey::PAGE_UP || key->key == InputKey::PAGE_DOWN);
245 if (wheel || page) {
246 pendingEnter.reset();
247 const bool backwards = wheel ? mouse->button == MouseButton::WHEEL_UP : key->key == InputKey::PAGE_UP;
248 if (wheel &&
249 (mouse->modifiers.alt || mouse->modifiers.control || mouse->modifiers.super || mouse->modifiers.shift)) {
250 return EventReply::IGNORED;
251 }
252 const auto step = static_cast<std::int64_t>(std::max<std::size_t>(1, this->rows.size()));
253 auto changed = page ? (this->natural() || this->position.editing ? this->requestPage(backwards)
254 : this->moveCurrent(backwards ? -step : step))
255 : this->requestWheel(mouse->wheelDelta, backwards);
256 if (!changed) {
257 this->failure = changed.error();
258 }
259 return EventReply::HANDLED;
260 }
261 if (!action || (action->action != portals::Action::MOVE_UP && action->action != portals::Action::MOVE_DOWN &&
262 action->action != portals::Action::MOVE_HOME && action->action != portals::Action::MOVE_END)) {
263 return EventReply::IGNORED;
264 }
265 auto focused = RowAccess::app(this->scene).router().focused();
266 if (!focused || *focused != this->node) {
267 // An editor owns its arrow grammar. An ignored direction still belongs to
268 // the row, rather than becoming a spatial jump to an unrelated outer control.
269 return EventReply::HANDLED;
270 }
271 std::expected<void, TreeError> changed;
272 pendingEnter.reset();
273 if (action->action == portals::Action::MOVE_UP) {
274 changed = this->moveCurrent(-1);
275 } else if (action->action == portals::Action::MOVE_DOWN) {
276 changed = this->moveCurrent(1);
277 } else if (action->action == portals::Action::MOVE_HOME) {
278 changed = this->sourceCapabilities ? this->selectAnchor({}, SourceDirection::FORWARD) : this->selectCurrent(0);
279 } else if (this->exactCount) {
280 changed = this->selectCurrent(*this->exactCount ? *this->exactCount - 1 : 0, true);
281 } else {
282 if (this->sourceCapabilities && (!this->sourceCapabilities->tail || !this->sourceCapabilities->backward)) {
283 return EventReply::HANDLED;
284 }
285 changed = this->selectAnchor({SourceAnchorKind::TAIL, {}, {}}, SourceDirection::BACKWARD);
286 }
287 if (!changed) {
288 this->failure = changed.error();
289 }
290 return EventReply::HANDLED;
291 }
292
293 std::expected<void, TreeError> bindInput() {
294 auto prepared = prepareChrome();
295 if (!prepared) {
296 return prepared;
297 }
298 auto binding = RowAccess::app(scene).router().bind(
299 node, [weak = this->weak_from_this()](VirtualRows<T> &, const RoutedEvent &event) {
300 auto owner = weak.lock();
301 return owner && owner->active() ? owner->handleInput(event) : EventReply::IGNORED;
302 });
303 if (!binding) {
304 return std::unexpected(binding.error());
305 }
306 inputBinding.emplace(std::move(*binding));
307 return {};
308 }
309
310 std::expected<void, TreeError> publishPosition() {
311 if (this->positionState) {
312 auto changed = this->positionState->value.set(this->position);
313 if (!changed) {
314 return std::unexpected(changed.error());
315 }
316 }
317 return {};
318 }
319
320 std::expected<void, TreeError> enterEditing() {
321 if (rows.empty() || !this->position.current) {
322 return {};
323 }
324 const auto found = std::ranges::find(rows, *this->position.current, [](const auto &row) {
325 return row->id;
326 });
327 if (found == rows.end()) {
328 const auto generation = portals::detail::RowTreeAccess::focusGeneration(RowAccess::app(scene).router());
329 if (!generation) {
330 return std::unexpected(TreeError::WOULD_BLOCK);
331 }
332 auto revealed = moveCurrent(0);
333 if (revealed && active() &&
334 generation == portals::detail::RowTreeAccess::focusGeneration(RowAccess::app(scene).router())) {
335 pendingEnter = EnterIntent{this->position.resource, generation};
336 }
337 return revealed;
338 }
339 if (retainedField) {
340 for (const auto &weak : (*found)->edit->bindings) {
341 auto binding = weak.lock();
342 if (!binding || binding->closed) {
343 continue;
344 }
345 const auto definition = std::ranges::find_if((*found)->edit->definitions, [&](const auto &entry) {
346 return entry.get() == binding->definition && entry->key == *retainedField;
347 });
348 auto eligible = RowAccess::tree(scene).inputEligible(binding->receiver);
349 if (definition != (*found)->edit->definitions.end() && eligible && *eligible) {
350 auto local = portals::detail::RowTreeAccess::focusScope(RowAccess::app(scene).router(), node, (*found)->root);
351 auto focused = local ? RowAccess::app(scene).router().setFocus(binding->receiver) : local;
352 if (!focused) {
353 return focused;
354 }
355 this->position.editing = true;
356 return publishPosition();
357 }
358 }
359 }
360 auto entered =
361 portals::detail::RowTreeAccess::enterRow(RowAccess::app(scene).router(), node, (*found)->root, retainedColumn);
362 if (!entered) {
363 return std::unexpected(entered.error());
364 }
365 this->position.editing = *entered != node;
366 return publishPosition();
367 }
368
369 std::expected<void, TreeError> leaveEditing() {
370 pendingEnter.reset();
371 auto observed = observeFocus();
372 if (!observed) {
373 return observed;
374 }
375 for (const auto &row : rows) {
376 if (focusedNode == node || !RowAccess::tree(scene).contains(row->root, focusedNode).value_or(false)) {
377 continue;
378 }
379 for (const auto &participant : row->participants) {
380 auto allowed = participant->beforeLeave();
381 if (!allowed) {
382 return allowed;
383 }
384 }
385 if (row->dirty() && row->edit->options.mode == EditMode::ON_COMPLETION) {
386 return std::unexpected(TreeError::WOULD_BLOCK);
387 }
388 }
389 auto collapsed = portals::detail::RowTreeAccess::focusScope(RowAccess::app(scene).router(), node);
390 if (!collapsed) {
391 return collapsed;
392 }
393 auto focused = RowAccess::app(scene).router().setFocus(node);
394 if (!focused) {
395 return focused;
396 }
397 this->position.editing = false;
398 return publishPosition();
399 }
400
401 std::expected<void, TreeError> selectCurrent(std::uint64_t target, bool endPage = false) {
402 if (!this->exactCount) {
403 return std::unexpected(TreeError::INVALID_ARGUMENT);
404 }
405 target = *this->exactCount ? std::min(target, *this->exactCount - 1) : 0;
406 const auto visible = std::max<std::uint64_t>(1, natural() ? rows.size() : viewport.height / options.rowHeight);
407 auto nextFirst = desiredFirst;
408 if (target < nextFirst) {
409 nextFirst = target;
410 } else if (target - nextFirst >= visible) {
411 nextFirst = natural() ? target : target - visible + 1;
412 }
413 auto allowed = requestFirst(nextFirst);
414 if (!allowed) {
415 return allowed;
416 }
417 desiredCurrent = target;
418 lastPage = natural() && endPage;
419 desiredCellOffset = 0;
420 pendingCells = 0;
421 offsetFromEnd = false;
422 selecting = true;
423 return {};
424 }
425
426 virtual std::expected<void, TreeError> moveCurrent(std::int64_t delta) {
427 const auto current = desiredCurrent.value_or(this->position.currentIndex.value_or(first));
428 const auto amount = delta < 0 ? static_cast<std::uint64_t>(-(delta + 1)) + 1 : static_cast<std::uint64_t>(delta);
429 if (delta < 0) {
430 return selectCurrent(current - std::min(current, amount));
431 }
432 return selectCurrent(current + std::min(amount, std::numeric_limits<std::uint64_t>::max() - current));
433 }
434
435 std::expected<void, TreeError> selectAnchor(SourceAnchor anchor, SourceDirection direction) {
436 auto admitted = this->requestAnchor(anchor, direction);
437 if (!admitted) {
438 return admitted;
439 }
440 this->currentSlot = direction == SourceDirection::BACKWARD ? options.maxRows - 1 : 0;
441 selecting = true;
442 return {};
443 }
444
445 std::expected<void, TreeError> syncScrollBar() {
446 if (!scrollController) {
447 return {};
448 }
449 auto snapshot = scrollController->snapshot();
450 if (!snapshot) {
451 return std::unexpected(snapshot.error());
452 }
453 if (natural() && this->exactCount == std::optional<std::uint64_t>{1} && placements.size() == 1) {
454 if (scrollRevision && snapshot->revision != scrollRevision) {
455 auto changed = requestCells(static_cast<std::int64_t>(snapshot->vertical.offset.raster) - desiredCellOffset);
456 if (!changed) {
457 return changed;
458 }
459 }
460 scrollRevision = snapshot->revision;
461 return {};
462 }
463 if (scrollRevision && snapshot->revision != scrollRevision && this->exactCount &&
464 snapshot->vertical.offset.raster != desiredFirst) {
465 auto admitted = requestFirst(snapshot->vertical.offset.raster);
466 if (!admitted) {
467 // The bar has already published its user intent. A checked editor refusal
468 // restores only that presentation; the committed viewport and draft never move.
469 auto restored = setScrollOffset(RowAccess::tree(scene), this->scrollbar, ScrollAxis::VERTICAL, {first});
470 if (restored) {
471 auto current = scrollController->snapshot();
472 if (current) {
473 scrollRevision = current->revision;
474 }
475 }
476 return admitted;
477 }
478 }
479 scrollRevision = snapshot->revision;
480 return {};
481 }
482
483 void updateOrientation(ModelResource resource) {
484 auto next = this->position;
485 const bool same = next.resource == resource;
486 next.resource = resource;
487 next.count = this->exactCount;
488 next.firstIndex = this->exactCount ? std::optional(first) : std::nullopt;
489 next.visible = rows.size();
490 next.windowStatus = this->sourceStatus;
491 this->visibleCurrentSlot.reset();
492 if (this->exactCount) {
493 if (*this->exactCount) {
494 const auto index = std::min(desiredCurrent.value_or(first), *this->exactCount - 1);
495 next.current = desiredCurrentRow;
496 next.currentIndex = next.current ? std::optional(index) : std::nullopt;
497 if (index >= first && index - first < rows.size()) {
498 next.current = rows[static_cast<std::size_t>(index - first)]->id;
499 this->currentSlot = static_cast<std::size_t>(index - first);
500 this->visibleCurrentSlot = this->currentSlot;
501 }
502 } else {
503 next.current.reset();
504 next.currentIndex.reset();
505 }
506 recordHasBefore = first > 0;
507 recordHasAfter = first + rows.size() < *this->exactCount;
508 next.hasBefore = recordHasBefore || firstCellOffset > 0;
509 next.hasAfter =
510 recordHasAfter || (!placements.empty() &&
511 static_cast<std::int64_t>(placements.back().y) + placements.back().height > viewport.height);
512 } else {
513 next.currentIndex.reset();
514 if (!same) {
515 this->currentSlot = 0;
516 next.current = restoredCurrent;
517 restoredCurrent.reset();
518 }
519 const auto found = next.current ? std::ranges::find(rows, *next.current,
520 [](const auto &row) {
521 return row->id;
522 })
523 : rows.end();
524 if (selecting && !rows.empty()) {
525 this->currentSlot = std::min(this->currentSlot, rows.size() - 1);
526 next.current = rows[this->currentSlot]->id;
527 this->visibleCurrentSlot = this->currentSlot;
528 } else if (found != rows.end()) {
529 this->currentSlot = static_cast<std::size_t>(found - rows.begin());
530 this->visibleCurrentSlot = this->currentSlot;
531 } else if (!rows.empty() && !next.current) {
532 this->currentSlot = std::min(this->currentSlot, rows.size() - 1);
533 next.current = rows[this->currentSlot]->id;
534 this->visibleCurrentSlot = this->currentSlot;
535 } else if (rows.empty() && !same) {
536 next.current.reset();
537 }
538 }
539 this->position = next;
540 selecting = false;
541 }
542
543 std::expected<void, TreeError> admitCurrent(std::optional<RowId> row, ModelResource resource) {
544 if constexpr (std::same_as<Source, Navigation<T>>) {
545 if (ModelAccess::bindings(source).current) {
546 auto navigation = source.managed();
547 if (!navigation) {
548 return std::unexpected(EditAccess::cause(navigation.error()));
549 }
550 auto channel = navigation->current();
551 if (!channel) {
552 return std::unexpected(channel.error());
553 }
554 auto current = channel->snapshot();
555 if (!current) {
556 return std::unexpected(current.error());
557 }
558 if ((*current)->value.resource != resource) {
559 return std::unexpected(TreeError::WOULD_BLOCK);
560 }
561 if (observedCurrent && *observedCurrent != (*current)->value && (*current)->value.row != row) {
562 return std::unexpected(TreeError::WOULD_BLOCK);
563 }
564 if ((*current)->value.row == row) {
565 observedCurrent = (*current)->value;
566 return {};
567 }
568 auto moved = row ? navigation->navigate(*row) : navigation->clearCurrent();
569 if (!moved) {
570 return moved;
571 }
572 auto accepted = channel ? channel->snapshot()
573 : std::expected<std::shared_ptr<const PropertyChange<NavigationPosition>>, TreeError>(
574 std::unexpected(channel.error()));
575 if (!accepted) {
576 return std::unexpected(accepted.error());
577 }
578 if ((*accepted)->value.resource == resource && (*accepted)->value.row == row) {
579 observedCurrent = (*accepted)->value;
580 }
581 }
582 } else {
583 (void)row;
584 (void)resource;
585 }
586 return {};
587 }
588
589 std::expected<void, TreeError> publishScrollBar() {
590 if (scrollController && this->exactCount) {
591 if (natural() && *this->exactCount == 1 && placements.size() == 1) {
592 auto metrics = setScrollMetrics(
593 RowAccess::tree(scene), this->scrollbar,
594 {static_cast<std::uint64_t>(placements.front().height), static_cast<std::uint64_t>(viewport.height)});
595 if (!metrics) {
596 return metrics;
597 }
598 auto moved = setScrollOffset(RowAccess::tree(scene), this->scrollbar, ScrollAxis::VERTICAL,
599 {static_cast<std::uint64_t>(firstCellOffset)});
600 if (!moved) {
601 return moved;
602 }
603 auto snapshot = scrollController->snapshot();
604 if (!snapshot) {
605 return std::unexpected(snapshot.error());
606 }
607 scrollRevision = snapshot->revision;
608 return {};
609 }
610 auto metrics = setScrollMetrics(RowAccess::tree(scene), this->scrollbar,
611 {*this->exactCount, static_cast<std::uint64_t>(rows.size())});
612 if (!metrics) {
613 return metrics;
614 }
615 auto offset = setScrollOffset(RowAccess::tree(scene), this->scrollbar, ScrollAxis::VERTICAL, {first});
616 if (!offset) {
617 return offset;
618 }
619 auto snapshot = scrollController->snapshot();
620 if (!snapshot) {
621 return std::unexpected(snapshot.error());
622 }
623 scrollRevision = snapshot->revision;
624 }
625 return {};
626 }
627
628 std::expected<void, TreeError> publishOrientation(ModelResource resource, bool announce = true) {
629 updateOrientation(resource);
630 if (!announce) {
631 return {};
632 }
633 auto bar = publishScrollBar();
634 return bar ? publishPosition() : bar;
635 }
636
637 bool active() const noexcept override {
638 if (retiredHost || lifetime.expired()) {
639 return false;
640 }
641 return RowAccess::tree(scene)
642 .withScope(node,
643 [](const UiScope &) {
644 })
645 .has_value();
646 }
647
648 virtual bool acceptedResource(ModelResource resource) {
649 if (!active()) {
650 return false;
651 }
652 auto actual = currentSource();
653 return actual && (*actual)->navigationResource == resource;
654 }
655
656 void cancel() noexcept override {
657 retire();
658 }
659
660 void retire() noexcept override {
661 retiredHost = true;
662 if (finiteRequest) {
663 finiteRequest->cancel();
664 }
665 if (finiteConsumer) {
666 (void)finiteConsumer->close();
667 }
668 pendingViewport.reset();
669 for (auto &row : rows) {
670 row->close();
671 }
672 if (editPin) {
673 editPin->close();
674 }
675 }
676
677 bool natural() const noexcept {
678 return desiredAutoHeight.value_or(options.autoRowHeight);
679 }
680
681 std::expected<void, TreeError> autoHeight(bool enabled) override {
682 if (!active()) {
683 return std::unexpected(TreeError::CLOSED);
684 }
685 if (natural() == enabled) {
686 return {};
687 }
688 if (!enabled && std::ranges::any_of(placements, [&](const auto &value) {
689 return value.height > options.rowHeight;
690 })) {
691 return std::unexpected(TreeError::INVALID_GEOMETRY);
692 }
693 auto invalidated = RowAccess::tree(scene).invalidate(node, Invalidation::LAYOUT);
694 if (!invalidated) {
695 return invalidated;
696 }
697 desiredAutoHeight = enabled;
698 desiredCellOffset = 0;
699 pendingCells = 0;
700 offsetFromEnd = false;
701 ++intentGeneration;
702 dirty = true;
703 blockedAttempt = false;
704 return {};
705 }
706
707 std::size_t rowDemand() const noexcept {
708 if (viewport.width <= 0 || viewport.height <= 0) {
709 return 0;
710 }
711 return natural() ? std::min(options.maxRows, static_cast<std::size_t>(viewport.height))
712 : static_cast<std::size_t>(viewport.height / options.rowHeight +
713 (viewport.height % options.rowHeight != 0));
714 }
715
716 std::int32_t contentWidth(bool bar) const noexcept {
717 return std::max(0, viewport.width - static_cast<std::int32_t>(options.currentIndicator) -
718 static_cast<std::int32_t>(bar));
719 }
720
721 std::expected<void, TreeError> refreshNaturalLayout() {
722 if (!natural() || dirty || rows.empty() || !rowDemand()) {
723 return {};
724 }
725 auto styled = RowAccess::flushStyles(scene);
726 if (!styled) {
727 return styled;
728 }
729 auto geometry = portals::detail::RowTreeAccess::geometryRevision(RowAccess::tree(scene));
730 if (!geometry) {
731 return std::unexpected(geometry.error());
732 }
733 if (*geometry == measuredGeometryRevision) {
734 return {};
735 }
736 std::int64_t y = -firstCellOffset;
737 for (std::size_t index = 0; index < rows.size(); ++index) {
738 auto size = portals::detail::RowTreeAccess::measure(RowAccess::tree(scene), rows[index]->root,
739 {contentWidth(scrollbarVisible), viewport.height});
740 if (!size) {
741 return std::unexpected(size.error());
742 }
743 const auto height = std::max(1, size->height);
744 if (placements[index].height != height || placements[index].y != y) {
745 auto invalidated = RowAccess::tree(scene).invalidate(node, Invalidation::LAYOUT);
746 if (!invalidated) {
747 return invalidated;
748 }
749 dirty = true;
750 return {};
751 }
752 y += height;
753 }
754 measuredGeometryRevision = *geometry;
755 return {};
756 }
757
758 std::expected<void, TreeError> admitDraft(const RowAssignment<T> *candidate) {
759 if (!active()) {
760 return std::unexpected(TreeError::CLOSED);
761 }
762 if (editPin && editPin.get() != candidate && editPin->dirty()) {
763 return std::unexpected(TreeError::WOULD_BLOCK);
764 }
765 for (const auto &row : rows) {
766 if (row.get() != candidate && row->dirty()) {
767 return std::unexpected(TreeError::WOULD_BLOCK);
768 }
769 }
770 return {};
771 }
772
773 std::expected<void, TreeError> preflight(std::uint64_t target, std::size_t visible) {
774 for (std::size_t index = 0; index < rows.size(); ++index) {
775 const auto &row = rows[index];
776 const auto ordinal = first + index;
777 if (ordinal < target || ordinal - target >= visible) {
778 for (const auto &participant : row->participants) {
779 auto allowed = participant->beforeLeave();
780 if (!allowed) {
781 return allowed;
782 }
783 }
784 }
785 if ((ordinal < target || ordinal - target >= visible) && row->dirty() &&
786 row->edit->options.mode == EditMode::ON_COMPLETION) {
787 return std::unexpected(TreeError::WOULD_BLOCK);
788 }
789 }
790 return {};
791 }
792
793 std::expected<void, TreeError> requestFirst(std::uint64_t target) override {
794 if (!active()) {
795 return std::unexpected(TreeError::CLOSED);
796 }
797 const auto visible = rowDemand();
798 auto allowed = preflight(target, visible);
799 if (!allowed) {
800 return allowed;
801 }
802 auto invalidated = RowAccess::tree(scene).invalidate(node, Invalidation::PAINT);
803 if (!invalidated) {
804 return invalidated;
805 }
806 if (desiredFirst != target) {
807 desiredCellOffset = 0;
808 offsetFromEnd = false;
809 }
810 desiredFirst = target;
811 lastPage = false;
812 allowEndBackfill = true;
813 ++intentGeneration;
814 dirty = true;
815 return {};
816 }
817
818 virtual bool rowMovePending() const noexcept {
819 return desiredFirst != first;
820 }
821
822 std::expected<void, TreeError> requestCells(std::int64_t delta) {
823 if (!active()) {
824 return std::unexpected(TreeError::CLOSED);
825 }
826 const auto limit = options.maxPendingRows;
827 const auto carried = offsetFromEnd ? desiredCellOffset : 0;
828 if (delta < -limit - pendingCells - carried || delta > limit - pendingCells - carried) {
829 return std::unexpected(TreeError::WOULD_BLOCK);
830 }
831 auto invalidated = RowAccess::tree(scene).invalidate(node, Invalidation::LAYOUT);
832 if (!invalidated) {
833 return invalidated;
834 }
835 pendingCells += delta;
836 allowEndBackfill = true;
837 dirty = true;
838 blockedAttempt = false;
839 ++intentGeneration;
840 return {};
841 }
842
843 std::expected<void, TreeError> applyCellIntent() {
844 if (!natural() || !pendingCells || rows.empty() || rowMovePending() || awaitingCellMove || lastPage) {
845 return {};
846 }
847 auto remaining = pendingCells;
848 auto offset = static_cast<std::int64_t>(desiredCellOffset);
849 std::int64_t movement{};
850 bool fromEnd{};
851 if (remaining < 0) {
852 const auto consumed = std::min(-remaining, offset);
853 offset -= consumed;
854 remaining += consumed;
855 if (remaining && recordHasBefore) {
856 movement = -1;
857 offset = remaining;
858 remaining = 0;
859 fromEnd = true;
860 } else if (remaining) {
861 remaining = 0;
862 }
863 } else {
864 if (!recordHasAfter && !placements.empty()) {
865 const auto bottom = static_cast<std::int64_t>(placements.back().y) + placements.back().height;
866 remaining = std::min(remaining, std::max<std::int64_t>(0, bottom - viewport.height));
867 }
868 std::size_t index{};
869 while (remaining && index < placements.size()) {
870 const auto available = static_cast<std::int64_t>(placements[index].height) - offset;
871 if (remaining < available) {
872 offset += remaining;
873 remaining = 0;
874 break;
875 }
876 if (index + 1 == placements.size() && !recordHasAfter) {
877 offset = placements[index].height - 1;
878 remaining = 0;
879 break;
880 }
881 remaining -= available;
882 offset = 0;
883 ++movement;
884 ++index;
885 }
886 }
887 if (movement) {
888 auto moved = requestMove(movement);
889 if (!moved) {
890 return moved;
891 }
892 awaitingCellMove = rowMovePending();
893 }
894 pendingCells = remaining;
895 desiredCellOffset = static_cast<std::int32_t>(offset);
896 offsetFromEnd = fromEnd;
897 dirty = true;
898 return {};
899 }
900
901 std::expected<void, TreeError> requestWheel(double magnitude, bool backwards) {
902 if (!std::isfinite(magnitude) || magnitude <= 0) {
903 return std::unexpected(TreeError::INVALID_ARGUMENT);
904 }
905 const auto accumulated = wheelFraction + (backwards ? -magnitude : magnitude);
906 if (!std::isfinite(accumulated) || std::abs(accumulated) >= 0x1p63) {
907 return std::unexpected(TreeError::INVALID_ARGUMENT);
908 }
909 const auto whole = std::trunc(accumulated);
910 if (whole == 0) {
911 wheelFraction = accumulated;
912 return {};
913 }
914 auto moved =
915 natural() ? requestCells(static_cast<std::int64_t>(whole)) : requestMove(static_cast<std::int64_t>(whole));
916 if (moved) {
917 wheelFraction = accumulated - whole;
918 }
919 return moved;
920 }
921
922 std::expected<void, TreeError> requestMove(std::int64_t delta) override {
923 if (delta < 0) {
924 const auto amount = static_cast<std::uint64_t>(-(delta + 1)) + 1;
925 return requestFirst(desiredFirst - std::min(desiredFirst, amount));
926 }
927 const auto amount = static_cast<std::uint64_t>(delta);
928 if (amount > std::numeric_limits<std::uint64_t>::max() - desiredFirst) {
929 return std::unexpected(TreeError::INVALID_ARGUMENT);
930 }
931 return requestFirst(desiredFirst + amount);
932 }
933
934 std::expected<void, TreeError> requestPage(bool backwards) override {
935 if (natural()) {
936 return requestCells(backwards ? -viewport.height : viewport.height);
937 }
938 const auto step = std::max<std::uint64_t>(1, rowDemand());
939 if (!backwards && desiredFirst > std::numeric_limits<std::uint64_t>::max() - step) {
940 return std::unexpected(TreeError::INVALID_ARGUMENT);
941 }
942 return requestFirst(backwards ? desiredFirst - std::min(desiredFirst, step) : desiredFirst + step);
943 }
944
945 void prepared() noexcept override {
946 service();
947 }
948
949 void layoutCompleted() noexcept override {
950 if (dirty && active()) {
951 service();
952 }
953 }
954
955 void layoutPrepared(const LayoutSnapshot &layout) noexcept override {
956 if (natural() && this->position.editing && !rowMovePending() && !pendingCells && !rows.empty()) {
957 try {
958 auto focused = RowAccess::app(scene).router().focused();
959 auto hostGeometry = RowAccess::tree(scene).inspect(node);
960 if (focused && *focused != node && hostGeometry && hostGeometry->geometry.valid) {
961 auto child = RowAccess::tree(scene).inspect(*focused);
962 if (child && child->geometry.valid) {
963 const auto &host = hostGeometry->geometry.surface;
964 const auto &bounds = child->geometry.surface;
965 const auto hostTop = host.origin().y;
966 const auto hostBottom = static_cast<std::int64_t>(hostTop) + host.size().height;
967 const auto childTop = bounds.origin().y;
968 const auto childBottom = static_cast<std::int64_t>(childTop) + bounds.size().height;
969 const auto delta = childTop < hostTop ? static_cast<std::int64_t>(childTop) - hostTop
970 : childBottom > hostBottom ? childBottom - hostBottom
971 : 0;
972 if (delta && bounds.size().height <= host.size().height) {
973 auto admitted = requestCells(delta);
974 if (!admitted) {
975 failure = admitted.error();
976 }
977 }
978 }
979 }
980 } catch (const std::bad_alloc &) {
981 failure = TreeError::NO_MEMORY;
982 } catch (...) {
983 failure = TreeError::CALLBACK_FAILED;
984 }
985 }
986 auto next = layout.viewport(node);
987 if (next && *next != viewport) {
988 viewport = *next;
989 dirty = true;
990 if (active()) {
991 (void)RowAccess::tree(scene).invalidate(node, Invalidation::LAYOUT);
992 }
993 }
994 }
995
996 std::expected<std::shared_ptr<portals::detail::ManagedModelSourceOf<T>>, TreeError> currentSource() {
997 if constexpr (std::same_as<Source, Navigation<T>>) {
998 auto handle = source.managed();
999 if (!handle) {
1000 return std::unexpected(EditAccess::cause(handle.error()));
1001 }
1002 auto record = EditAccess::context(*handle);
1003 if (!record) {
1004 return std::unexpected(record.error());
1005 }
1006 auto typed = std::dynamic_pointer_cast<portals::detail::ManagedModelSourceOf<T>>((*record)->model.lock());
1007 return typed ? std::expected<std::shared_ptr<portals::detail::ManagedModelSourceOf<T>>, TreeError>(typed)
1008 : std::unexpected(TreeError::CLOSED);
1009 } else {
1010 return RowAccess::source(initialModel);
1011 }
1012 }
1013
1014 void dispose(const std::shared_ptr<RowAssignment<T>> &row) noexcept {
1015 row->close();
1016 if (!lifetime.expired()) {
1017 (void)scene.remove(row->root);
1018 }
1019 }
1020
1021 std::expected<std::shared_ptr<RowAssignment<T>>, TreeError>
1022 construct(const std::shared_ptr<portals::detail::ManagedModelSourceOf<T>> &actual,
1023 const std::shared_ptr<const void> &pin, const DeliveredRow<T> &value, ModelResource resource,
1024 SourceStamp incarnation) {
1025 auto row = std::make_shared<RowAssignment<T>>();
1026 auto root = scene.emplace<SizedWidget>(node, natural() ? DEFAULT_FLEX_WIDTH_POLICY : DEFAULT_VIEWPORT_POLICY);
1027 if (!root) {
1028 return std::unexpected(EditAccess::cause(root.error()));
1029 }
1030 row->root = *root;
1031
1032 struct Rollback {
1033 RowsController &host;
1034 std::shared_ptr<RowAssignment<T>> row;
1035 bool committed{};
1036
1037 ~Rollback() {
1038 if (!committed) {
1039 host.dispose(row);
1040 }
1041 }
1042 } rollback{*this, row};
1043
1044 row->id = value.id;
1045 row->value = value.value;
1046 row->valueRevision = row->snapshotRevision = value.valueRevision;
1047 row->pin = pin;
1048 row->origin = std::make_shared<portals::detail::ManagedOrigin>();
1049 row->origin->tree = &RowAccess::tree(scene);
1050 row->origin->node = row->root;
1051 row->origin->lifetime = lifetime;
1052 row->model = EditAccess::model<T>(actual);
1053 row->edit = std::make_shared<EditState<T>>(Navigation<T>{}, options.editing);
1054 row->edit->fixed = std::make_unique<FixedEditContext<T>>();
1055 row->edit->fixed->position = NavigationPosition{resource, PositionKind::ITEM, row->id,
1056 0, PositionAffinity::FORWARD, PositionResolution::EXACT};
1057 row->edit->fixed->source = actual;
1058 row->edit->fixed->sourceSession = incarnation;
1059 row->edit->fixed->origin = row->origin;
1060 row->edit->fixed->admitDraft = [host = this->weak_from_this(),
1061 weak = std::weak_ptr(row)]() -> std::expected<void, TreeError> {
1062 auto owner = host.lock();
1063 auto target = weak.lock();
1064 return owner && target ? owner->admitDraft(target.get()) : std::unexpected(TreeError::CLOSED);
1065 };
1066 row->erase = [weak = std::weak_ptr(row)]() -> std::expected<void, TreeError> {
1067 auto target = weak.lock();
1068 if (!target || !target->origin->check()) {
1069 return std::unexpected(TreeError::CLOSED);
1070 }
1071 auto sequence = EditAccess::sequence(target->model);
1072 if (!sequence || !sequence->current) {
1073 return std::unexpected(TreeError::INVALID_ARGUMENT);
1074 }
1075 auto lookup = sequence->current->locateRow(target->id);
1076 if (lookup.state != RowLookupState::FOUND) {
1077 return std::unexpected(TreeError::STALE_NODE);
1078 }
1079 auto removed = target->model.erase(lookup.index);
1080 return removed ? std::expected<void, TreeError>{} : std::unexpected(EditAccess::cause(removed.error()));
1081 };
1082 auto hidden = RowAccess::tree(scene).setVisible(row->root, false);
1083 if (!hidden) {
1084 dispose(row);
1085 return std::unexpected(hidden.error());
1086 }
1087 try {
1088 RowAccess::Scope scope(scene, row->origin);
1089 row->building = true;
1090 auto recipe = std::invoke(factory, RowContext<T>(row));
1091 row->building = false;
1092 auto mounted = mountAt(scene, row->root, std::move(recipe), controls);
1093 if (!mounted) {
1094 dispose(row);
1095 return std::unexpected(EditAccess::cause(mounted.error()));
1096 }
1097 auto supported = RowAccess::validateEditors(scene, row->root, row->edit->bindings, !row->participants.empty());
1098 if (!supported) {
1099 dispose(row);
1100 return std::unexpected(supported.error());
1101 }
1102 if (!active() || !row->origin->check()) {
1103 dispose(row);
1104 return std::unexpected(TreeError::CLOSED);
1105 }
1106 rollback.committed = true;
1107 return row;
1108 } catch (...) {
1109 dispose(row);
1110 throw;
1111 }
1112 }
1113
1114 std::expected<void, TreeError> observeFocus() {
1115 if (editPin && !editPin->dirty()) {
1116 dirty = true;
1117 blockedAttempt = false;
1118 }
1119 auto focused = RowAccess::app(scene).router().focused();
1120 if (!focused) {
1121 return std::unexpected(focused.error());
1122 }
1123 if (focusedNode != *focused && deferredRefresh) {
1124 dirty = true;
1125 blockedAttempt = false;
1126 }
1127 focusedNode = *focused;
1128 this->hasFocus = *focused == node ||
1129 (*focused != Node<Widget>{} && RowAccess::tree(scene).contains(node, *focused).value_or(false));
1130 auto editing = false;
1131 for (std::size_t index = 0; index < rows.size(); ++index) {
1132 const auto &row = rows[index];
1133 if (*focused != Node<Widget>{} && RowAccess::tree(scene).contains(row->root, *focused).value_or(false)) {
1134 auto column = portals::detail::RowTreeAccess::column(RowAccess::app(scene).router(), row->root, *focused);
1135 if (!column) {
1136 return std::unexpected(column.error());
1137 }
1138 retainedColumn = *column;
1139 retainedField.reset();
1140 for (const auto &weak : row->edit->bindings) {
1141 auto binding = weak.lock();
1142 if (!binding || binding->closed || binding->receiver != *focused) {
1143 continue;
1144 }
1145 const auto definition = std::ranges::find_if(row->edit->definitions, [&](const auto &entry) {
1146 return entry.get() == binding->definition && entry->key.persistent();
1147 });
1148 if (definition != row->edit->definitions.end()) {
1149 retainedField = (*definition)->key;
1150 }
1151 }
1152 this->currentSlot = index;
1153 dirty = dirty || this->position.current != row->id;
1154 selecting = selecting || this->position.current != row->id;
1155 if (this->exactCount) {
1156 desiredCurrent = first + index;
1157 }
1158 auto local = portals::detail::RowTreeAccess::focusScope(RowAccess::app(scene).router(), node, row->root);
1159 if (!local) {
1160 return local;
1161 }
1162 editing = true;
1163 break;
1164 }
1165 }
1166 if (!editing) {
1167 auto collapsed = portals::detail::RowTreeAccess::focusScope(RowAccess::app(scene).router(), node);
1168 if (!collapsed) {
1169 return collapsed;
1170 }
1171 }
1172 this->position.editing = editing;
1173 return publishPosition();
1174 }
1175
1176 std::expected<void, TreeError> ensureHistory() {
1177 if (history) {
1178 return {};
1179 }
1180 auto created = portals::detail::ModelViewHistory::create(lifetime, options.checkpoints);
1181 if (!created) {
1182 return std::unexpected(created.error());
1183 }
1184 auto role = (*created)->role();
1185 if (!role) {
1186 return std::unexpected(role.error());
1187 }
1188 historyRole = *role;
1189 history = std::move(*created);
1190 return {};
1191 }
1192
1193 std::expected<std::optional<portals::detail::ModelViewHistoryChange>, TreeError>
1194 stageHistory(const std::shared_ptr<portals::detail::ManagedModelSourceOf<T>> &actual) {
1195 auto previous = previousSource.lock();
1196 if (!previous || previous == actual) {
1197 return std::optional<portals::detail::ModelViewHistoryChange>{};
1198 }
1199 auto ready = ensureHistory();
1200 if (!ready) {
1201 return std::unexpected(ready.error());
1202 }
1203 portals::detail::ModelViewCheckpoint checkpoint;
1204 checkpoint.first = first;
1205 if (natural()) {
1206 checkpoint.readingCellOffset = firstCellOffset;
1207 }
1208 if (this->position.current && this->position.currentIndex) {
1209 auto bookmark = ModelBookmark::create(previous->navigationResource,
1210 {PositionKind::ITEM, *this->position.current, *this->position.currentIndex,
1211 dataRevision, PositionAffinity::FORWARD},
1212 {}, options.checkpoints.bookmarks);
1213 if (!bookmark) {
1214 return std::unexpected(portals::detail::navigationTreeError(bookmark.error()));
1215 }
1216 checkpoint.current = *bookmark;
1217 }
1218 if (!rows.empty()) {
1219 auto bookmark = ModelBookmark::create(
1220 previous->navigationResource,
1221 {PositionKind::ITEM, rows.front()->id, first, rows.front()->valueRevision, PositionAffinity::FORWARD}, {},
1222 options.checkpoints.bookmarks);
1223 if (!bookmark) {
1224 return std::unexpected(portals::detail::navigationTreeError(bookmark.error()));
1225 }
1226 checkpoint.reading = *bookmark;
1227 }
1228 auto staged = history->stage(previous, historyRole, std::move(checkpoint), this->weak_from_this());
1229 return staged ? std::expected<std::optional<portals::detail::ModelViewHistoryChange>, TreeError>(
1230 std::optional(std::move(*staged)))
1231 : std::unexpected(staged.error());
1232 }
1233
1234 std::expected<std::uint64_t, TreeError>
1235 restoredFirst(const std::shared_ptr<portals::detail::ManagedModelSourceOf<T>> &actual, const ModelFrame<T> &frame,
1236 SourceStamp incarnation) {
1237 const bool switched = previousSource.lock() && previousSource.lock() != actual;
1238 desiredCurrentRow.reset();
1239 auto target = switched ? std::uint64_t{} : desiredFirst;
1240 if (switched) {
1241 desiredCellOffset = 0;
1242 pendingCells = 0;
1243 lastPage = false;
1244 allowEndBackfill = false;
1245 desiredCurrent = 0;
1246 } else if (!selecting && this->position.current) {
1247 auto located = frame.locateRow(*this->position.current);
1248 if (!located) {
1249 return std::unexpected(located.error());
1250 }
1251 if (located->state == RowLookupState::FOUND) {
1252 desiredCurrent = located->index;
1253 desiredCurrentRow = this->position.current;
1254 } else {
1255 desiredCurrent = frame.rowCount() ? std::min(this->position.currentIndex.value_or(0), frame.rowCount() - 1) : 0;
1256 }
1257 }
1258 if (switched && history && !resetRestoration) {
1259 auto saved = history->find(actual, historyRole);
1260 if (saved) {
1261 target = saved->value.first;
1262 desiredCellOffset = natural() ? saved->value.readingCellOffset.value_or(0) : 0;
1263 if (saved->value.current) {
1264 auto resolver = FinitePositionResolver<T>::create(actual->navigationResource, incarnation, frame.snapshot(),
1265 actual->navigationChanges);
1266 if (!resolver) {
1267 return std::unexpected(portals::detail::navigationTreeError(resolver.error()));
1268 }
1269 auto restored = resolver->resolve({incarnation, frame.dataRevision(), 1, *saved->value.current}, {});
1270 if (!restored) {
1271 return std::unexpected(portals::detail::navigationTreeError(restored.error()));
1272 }
1273 if (restored->state == PositionResolution::EXACT || restored->state == PositionResolution::NEAREST) {
1274 desiredCurrent = restored->position.offset;
1275 desiredCurrentRow = restored->position.row;
1276 }
1277 }
1278 if (saved->value.reading) {
1279 auto resolver = FinitePositionResolver<T>::create(actual->navigationResource, incarnation, frame.snapshot(),
1280 actual->navigationChanges);
1281 if (!resolver) {
1282 return std::unexpected(portals::detail::navigationTreeError(resolver.error()));
1283 }
1284 auto resolved = resolver->resolve({incarnation, frame.dataRevision(), 1, *saved->value.reading}, {});
1285 if (!resolved) {
1286 return std::unexpected(portals::detail::navigationTreeError(resolved.error()));
1287 }
1288 if (resolved->state == PositionResolution::EXACT || resolved->state == PositionResolution::NEAREST) {
1289 target = resolved->position.offset;
1290 }
1291 }
1292 }
1293 } else if (!switched && committedIntent == intentGeneration && revision != frame.revision() && !rows.empty()) {
1294 auto anchor = frame.locateRow(rows.front()->id);
1295 if (!anchor) {
1296 return std::unexpected(anchor.error());
1297 }
1298 if (anchor->state == RowLookupState::FOUND) {
1299 target = anchor->index;
1300 }
1301 }
1302 if constexpr (std::same_as<Source, Navigation<T>>) {
1303 auto navigation = source.managed();
1304 if (!navigation) {
1305 return std::unexpected(EditAccess::cause(navigation.error()));
1306 }
1307 const auto binding = ModelAccess::bindings(source);
1308 auto observe = [&](bool enabled, bool reading,
1309 std::optional<NavigationPosition> &observed) -> std::expected<void, TreeError> {
1310 if (!enabled) {
1311 return {};
1312 }
1313 auto channel = reading ? navigation->readingAnchor() : navigation->current();
1314 if (!channel) {
1315 return std::unexpected(channel.error());
1316 }
1317 auto value = channel->snapshot();
1318 if (!value) {
1319 return std::unexpected(value.error());
1320 }
1321 const auto &position = (*value)->value;
1322 const bool changed = !observed || position != *observed;
1323 observed = position;
1324 if (changed && position.row && position.resource == actual->navigationResource && (!switched || reading)) {
1325 auto found = frame.locateRow(*position.row);
1326 if (!found) {
1327 return std::unexpected(found.error());
1328 }
1329 if (!reading && found->state == RowLookupState::FOUND) {
1330 desiredCurrent = found->index;
1331 desiredCurrentRow = position.row;
1332 }
1333 const auto visible = static_cast<std::uint64_t>(rowDemand());
1334 if (found->state == RowLookupState::FOUND &&
1335 (reading || found->index < target || found->index - target >= visible)) {
1336 target = found->index;
1337 }
1338 }
1339 return {};
1340 };
1341 auto current = observe(binding.current, false, observedCurrent);
1342 if (!current) {
1343 return std::unexpected(current.error());
1344 }
1345 auto reading = observe(binding.readingAnchor, true, observedReading);
1346 if (!reading) {
1347 return std::unexpected(reading.error());
1348 }
1349 }
1350 return frame.rowCount() ? std::min(target, frame.rowCount() - 1) : 0;
1351 }
1352
1353 std::expected<std::optional<ModelRange<T>>, TreeError>
1354 readFiniteRange(const std::shared_ptr<portals::detail::ManagedModelSourceOf<T>> &actual, const ModelFrame<T> &frame,
1355 RowRange requested) {
1356 auto range = frame.read(requested);
1357 if (!range) {
1358 return std::unexpected(range.error());
1359 }
1360 if (range->state() == RangeState::PENDING) {
1361 if (consumerSource.lock() != actual) {
1362 auto opened = actual->model->openRange();
1363 if (!opened) {
1364 return std::unexpected(opened.error());
1365 }
1366 finiteRequest.reset();
1367 finiteConsumer.emplace(std::move(*opened));
1368 consumerSource = actual;
1369 }
1370 const bool sameRequest = finiteRequest && finiteRevision == frame.dataRevision() &&
1371 finiteRange.first == requested.first && finiteRange.count == requested.count;
1372 if (sameRequest) {
1373 auto completed = frame.range(finiteConsumer->id());
1374 if (!completed) {
1375 return std::unexpected(completed.error());
1376 }
1377 range = std::move(completed);
1378 } else {
1379 auto action = actual->preparation;
1380 if (!action) {
1381 return std::unexpected(TreeError::INVALID_ARGUMENT);
1382 }
1383 auto work = finiteConsumer->request(requested);
1384 if (!work) {
1385 return std::unexpected(work.error());
1386 }
1387 finiteRange = requested;
1388 finiteRevision = frame.dataRevision();
1389 finiteRequest = std::move(*work);
1390 auto sent = (*action)(frame, finiteRequest);
1391 if (!sent) {
1392 return std::unexpected(sent.error());
1393 }
1394 return std::optional<ModelRange<T>>{};
1395 }
1396 }
1397 if (range->state() == RangeState::PENDING) {
1398 return std::optional<ModelRange<T>>{};
1399 }
1400 if (range->state() != RangeState::READY) {
1401 return std::unexpected(TreeError::CALLBACK_FAILED);
1402 }
1403 return std::optional<ModelRange<T>>(std::move(*range));
1404 }
1405
1406 std::expected<bool, TreeError>
1407 prepareFiniteCurrent(const std::shared_ptr<portals::detail::ManagedModelSourceOf<T>> &actual,
1408 const ModelFrame<T> &frame, std::uint64_t target, std::span<const DeliveredRow<T>> values) {
1409 if (!frame.rowCount()) {
1410 desiredCurrentRow.reset();
1411 return true;
1412 }
1413 const auto index = std::min(desiredCurrent.value_or(target), frame.rowCount() - 1);
1414 desiredCurrent = index;
1415 if (index >= target && index - target < values.size()) {
1416 desiredCurrentRow = values[static_cast<std::size_t>(index - target)].id;
1417 return true;
1418 }
1419 if (desiredCurrentRow) {
1420 return true;
1421 }
1422 // Resolve one qualified record independently of the visible page. The existing
1423 // single range consumer handles PENDING; no synchronous provider I/O or scan is added.
1424 auto point = readFiniteRange(actual, frame, {index, 1});
1425 if (!point) {
1426 return std::unexpected(point.error());
1427 }
1428 if (!*point) {
1429 return false;
1430 }
1431 desiredCurrentRow = (**point).rows().front().id;
1432 return true;
1433 }
1434
1435 std::expected<void, TreeError> update() {
1436 auto scrolled = syncScrollBar();
1437 if (!scrolled) {
1438 return scrolled;
1439 }
1440 auto actual = currentSource();
1441 if (!actual || (*actual)->retired || !(*actual)->model) {
1442 return std::unexpected(actual ? TreeError::CLOSED : actual.error());
1443 }
1444 auto resource = portals::detail::modelNavigationResource(**actual);
1445 if (!resource) {
1446 return std::unexpected(resource.error());
1447 }
1448 auto frame = (*actual)->model->pin();
1449 if (!frame) {
1450 return std::unexpected(frame.error());
1451 }
1452 auto focus = observeFocus();
1453 if (!focus) {
1454 return focus;
1455 }
1456 const auto count = frame->rowCount();
1457 exactCount = count;
1458 if (blockedAttempt && !dirty && attempt.source.lock() == *actual && attempt.revision == frame->revision() &&
1459 attempt.intent == intentGeneration && attempt.viewport == viewport &&
1460 (!natural() || blockedGeometryRevision ==
1461 portals::detail::RowTreeAccess::geometryRevision(RowAccess::tree(scene)).value_or(0))) {
1462 return {};
1463 }
1464 auto incarnation = EditAccess::sourceSession<T>(*actual);
1465 if (!incarnation) {
1466 return std::unexpected(incarnation.error());
1467 }
1468 auto saved = stageHistory(*actual);
1469 if (!saved) {
1470 return std::unexpected(saved.error());
1471 }
1472 auto restored = restoredFirst(*actual, *frame, *incarnation);
1473 if (!restored) {
1474 return std::unexpected(restored.error());
1475 }
1476 const auto requestedFirst = *restored;
1477 auto target = requestedFirst;
1478 if (natural() && allowEndBackfill && count - target < rowDemand()) {
1479 target = count - std::min<std::uint64_t>(count, rowDemand());
1480 }
1481 const auto leadingRows = static_cast<std::size_t>(requestedFirst - target);
1482 const auto visible = viewport.width && viewport.height
1483 ? static_cast<std::size_t>(std::min<std::uint64_t>(count - target, rowDemand()))
1484 : 0;
1485 if (visible > options.maxRows) {
1486 return std::unexpected(TreeError::NODE_LIMIT);
1487 }
1488 if (!dirty && previousSource.lock() == *actual && revision == frame->revision() && target == first) {
1489 auto measured = refreshNaturalLayout();
1490 if (!measured) {
1491 return measured;
1492 }
1493 }
1494 if (!dirty && previousSource.lock() == *actual && revision == frame->revision() && target == first &&
1495 desiredCurrent == this->position.currentIndex) {
1496 return {};
1497 }
1498 auto allowed = preflight(target, visible);
1499 if (!allowed) {
1500 return allowed;
1501 }
1502 if (!visible) {
1503 pendingViewport.reset();
1504 return commitRows(*actual, {}, {}, frame->revision(), target, (*actual)->navigationResource, *incarnation,
1505 std::move(*saved));
1506 }
1507 auto pin = pendingViewport;
1508 if (!pin || pendingViewportSource.lock() != *actual || pendingViewportRevision != frame->dataRevision() ||
1509 pendingViewportRows.first != target || pendingViewportRows.count != visible) {
1510 pendingViewport.reset();
1511 auto range = readFiniteRange(*actual, *frame, {target, visible});
1512 if (!range) {
1513 return std::unexpected(range.error());
1514 }
1515 if (!*range) {
1516 return {};
1517 }
1518 pin = std::make_shared<ModelRange<T>>(std::move(**range));
1519 }
1520 attempt = {*actual, frame->revision(), intentGeneration, viewport};
1521 std::vector<DeliveredRow<T>> values(0);
1522 values.reserve(visible);
1523 for (const auto &value : pin->rows()) {
1524 values.push_back({value.id, &value.value, frame->dataRevision()});
1525 }
1526 auto current = prepareFiniteCurrent(*actual, *frame, target, values);
1527 if (!current) {
1528 return std::unexpected(current.error());
1529 }
1530 if (!*current) {
1531 // Retain this one bounded ready viewport while the same consumer resolves
1532 // an offscreen current; otherwise two PENDING intervals could replace each other forever.
1533 pendingViewport = pin;
1534 pendingViewportSource = *actual;
1535 pendingViewportRows = {target, visible};
1536 pendingViewportRevision = frame->dataRevision();
1537 return {};
1538 }
1539 pendingViewport.reset();
1540 return commitRows(*actual, pin, values, frame->revision(), target, (*actual)->navigationResource, *incarnation,
1541 std::move(*saved), {}, leadingRows, target + values.size() == count, target > 0);
1542 }
1543
1544 struct NaturalGeometry {
1545 std::vector<RowPlacement> placements = std::vector<RowPlacement>(0);
1546 std::size_t first{};
1547 std::int32_t offset{};
1548 };
1549
1550 std::expected<NaturalGeometry, TreeError>
1551 measureNaturalRows(std::span<const std::shared_ptr<RowAssignment<T>>> staging, std::size_t leadingRows,
1552 bool finalWindow, bool reserveBar, bool beforeWindow) {
1553 NaturalGeometry result;
1554 result.placements.reserve(staging.size());
1555 for (const auto &row : staging) {
1556 auto measured = portals::detail::RowTreeAccess::measure(RowAccess::tree(scene), row->root,
1557 {contentWidth(reserveBar), viewport.height});
1558 if (!measured || !active()) {
1559 return std::unexpected(measured ? TreeError::CLOSED : measured.error());
1560 }
1561 const auto height = std::max(1, measured->height);
1562 result.placements.push_back({row->root, 0, height});
1563 }
1564 if (result.placements.empty()) {
1565 return std::expected<NaturalGeometry, TreeError>(std::in_place, result);
1566 }
1567 result.first = std::min(leadingRows, result.placements.size() - 1);
1568 const auto firstHeight = result.placements[result.first].height;
1569 const auto requested = offsetFromEnd ? static_cast<std::int64_t>(firstHeight) + desiredCellOffset
1570 : static_cast<std::int64_t>(desiredCellOffset);
1571 result.offset = static_cast<std::int32_t>(std::clamp<std::int64_t>(requested, 0, firstHeight - 1));
1572 std::int64_t remaining = -result.offset;
1573 for (std::size_t index = result.first; index < result.placements.size(); ++index) {
1574 remaining += result.placements[index].height;
1575 }
1576 if (finalWindow && (lastPage || (allowEndBackfill && remaining < viewport.height))) {
1577 result.first = result.placements.size();
1578 remaining = 0;
1579 while (result.first && remaining < viewport.height) {
1580 remaining += result.placements[--result.first].height;
1581 }
1582 result.offset = static_cast<std::int32_t>(std::max<std::int64_t>(0, remaining - viewport.height));
1583 }
1584 if (remaining < viewport.height && staging.size() == options.maxRows &&
1585 (!finalWindow || beforeWindow || result.first > 0)) {
1586 return std::unexpected(TreeError::NODE_LIMIT);
1587 }
1588 std::int64_t y = -result.offset;
1589 std::size_t retained{};
1590 for (std::size_t index = result.first; index < result.placements.size() && y < viewport.height; ++index) {
1591 auto &placement = result.placements[index];
1592 if (y > std::numeric_limits<std::int32_t>::max() - placement.height) {
1593 return std::unexpected(TreeError::INVALID_GEOMETRY);
1594 }
1595 placement.y = static_cast<std::int32_t>(y);
1596 y += placement.height;
1597 ++retained;
1598 }
1599 result.placements.erase(result.placements.begin(),
1600 result.placements.begin() + static_cast<std::ptrdiff_t>(result.first));
1601 result.placements.resize(retained);
1602 return std::expected<NaturalGeometry, TreeError>(std::in_place, result);
1603 }
1604
1605 std::expected<void, TreeError> commitRows(const std::shared_ptr<portals::detail::ManagedModelSourceOf<T>> &actual,
1606 const std::shared_ptr<const void> &pin,
1607 std::span<const DeliveredRow<T>> values, std::uint64_t publication,
1608 std::uint64_t target, ModelResource resource, SourceStamp incarnation,
1609 std::optional<portals::detail::ModelViewHistoryChange> saved = {},
1610 RowsCommitPublication metadata = {}, std::size_t leadingRows = 0,
1611 bool finalWindow = false, bool beforeWindow = false) {
1612 const auto visible = values.size();
1613 const auto stagedIntent = intentGeneration;
1614 std::vector<std::shared_ptr<RowAssignment<T>>> staging(0);
1615 std::vector<RowPlacement> placement(0);
1616 staging.reserve(visible);
1617 placement.reserve(visible);
1618
1619 struct Refresh {
1620 std::shared_ptr<RowAssignment<T>> row;
1621 const T *value{};
1622 std::uint64_t revision{};
1623 std::shared_ptr<const void> next;
1624 std::shared_ptr<const void> retired;
1625 };
1626
1627 std::vector<Refresh> refresh(0);
1628 refresh.reserve(visible);
1629 bool deferred{};
1630 auto rollback = [&] {
1631 for (auto &row : staging) {
1632 if (std::ranges::find(rows, row) == rows.end() && row != editPin) {
1633 dispose(row);
1634 }
1635 }
1636 };
1637 try {
1638 for (const auto &value : values) {
1639 std::shared_ptr<RowAssignment<T>> row;
1640 const auto found = std::ranges::find_if(rows, [&](const auto &existing) {
1641 return existing->id == value.id && existing->edit->fixed->source == actual &&
1642 existing->edit->fixed->sourceSession == incarnation &&
1643 (existing->snapshotRevision == value.valueRevision || existing->retainsMountedState() ||
1644 (focusedNode != Node<Widget>{} &&
1645 RowAccess::tree(scene).contains(existing->root, focusedNode).value_or(false)));
1646 });
1647 if (found != rows.end()) {
1648 row = *found;
1649 } else if (editPin && editPin->id == value.id && editPin->edit->fixed->source == actual &&
1650 editPin->edit->fixed->sourceSession == incarnation) {
1651 row = editPin;
1652 } else {
1653 auto created = construct(actual, value.pin ? value.pin : pin, value, resource, incarnation);
1654 if (!created) {
1655 rollback();
1656 return std::unexpected(created.error());
1657 }
1658 row = std::move(*created);
1659 }
1660 if (row->value != value.value || row->valueRevision != value.valueRevision) {
1661 refresh.push_back({row, value.value, value.valueRevision, value.pin ? value.pin : pin, {}});
1662 }
1663 deferred = deferred || row->snapshotRevision != value.valueRevision;
1664 placement.push_back(
1665 {row->root, static_cast<std::int32_t>(staging.size() * options.rowHeight), options.rowHeight});
1666 staging.push_back(std::move(row));
1667 }
1668 if (desiredAutoHeight && !*desiredAutoHeight && options.autoRowHeight) {
1669 auto styled = RowAccess::flushStyles(scene);
1670 if (!styled) {
1671 rollback();
1672 return styled;
1673 }
1674 for (const auto &row : staging) {
1675 auto measured = portals::detail::RowTreeAccess::measure(RowAccess::tree(scene), row->root,
1676 {contentWidth(scrollbarVisible), viewport.height});
1677 if (!measured || measured->height > options.rowHeight) {
1678 rollback();
1679 return std::unexpected(measured ? TreeError::INVALID_GEOMETRY : measured.error());
1680 }
1681 }
1682 }
1683 std::int32_t nextCellOffset{};
1684 if (natural() && !staging.empty()) {
1685 auto styled = RowAccess::flushStyles(scene);
1686 if (!styled) {
1687 rollback();
1688 return styled;
1689 }
1690 const bool reserveBar = this->scrollbar != Node<ScrollBar>{} && this->exactCount && viewport.width > 1;
1691 auto measured = measureNaturalRows(staging, leadingRows, finalWindow, reserveBar, beforeWindow);
1692 if (!measured) {
1693 rollback();
1694 return std::unexpected(measured.error());
1695 }
1696 const auto retained = measured->placements.size();
1697 const auto skip = measured->first;
1698 for (std::size_t index = 0; index < staging.size(); ++index) {
1699 if ((index < skip || index - skip >= retained) && std::ranges::find(rows, staging[index]) == rows.end() &&
1700 staging[index] != editPin) {
1701 dispose(staging[index]);
1702 }
1703 }
1704 staging.erase(staging.begin(), staging.begin() + static_cast<std::ptrdiff_t>(skip));
1705 staging.resize(retained);
1706 placement.swap(measured->placements);
1707 nextCellOffset = measured->offset;
1708 target += skip;
1709 std::erase_if(refresh, [&](const auto &value) {
1710 return std::ranges::find(staging, value.row) == staging.end();
1711 });
1712 }
1713 for (const auto &row : rows) {
1714 if (std::ranges::find(staging, row) != staging.end()) {
1715 continue;
1716 }
1717 for (const auto &participant : row->participants) {
1718 auto allowed = participant->beforeLeave();
1719 if (!allowed) {
1720 rollback();
1721 return allowed;
1722 }
1723 }
1724 if (row->dirty() && row->edit->options.mode == EditMode::ON_COMPLETION) {
1725 rollback();
1726 return std::unexpected(TreeError::WOULD_BLOCK);
1727 }
1728 }
1729 std::shared_ptr<RowAssignment<T>> nextPin;
1730 if (editPin && editPin->dirty() && std::ranges::find(staging, editPin) == staging.end()) {
1731 nextPin = editPin;
1732 }
1733 for (const auto &row : rows) {
1734 if (row->dirty() && std::ranges::find(staging, row) == staging.end()) {
1735 if (nextPin && nextPin != row) {
1736 rollback();
1737 return std::unexpected(TreeError::WOULD_BLOCK);
1738 }
1739 nextPin = row;
1740 }
1741 }
1742 const bool retiringFocus = focusedNode != Node<Widget>{} && std::ranges::any_of(rows, [&](const auto &row) {
1743 return std::ranges::find(staging, row) == staging.end() &&
1744 RowAccess::tree(scene).contains(row->root, focusedNode).value_or(false);
1745 });
1746 if (!active() || intentGeneration != stagedIntent) {
1747 rollback();
1748 return std::unexpected(TreeError::WOULD_BLOCK);
1749 }
1750 auto admitted = admitCurrent(desiredCurrentRow, resource);
1751 if (!admitted) {
1752 rollback();
1753 return admitted;
1754 }
1755 if (!active() || intentGeneration != stagedIntent) {
1756 rollback();
1757 return std::unexpected(TreeError::WOULD_BLOCK);
1758 }
1759 if (retiringFocus) {
1760 auto collapsed = portals::detail::RowTreeAccess::focusScope(RowAccess::app(scene).router(), node);
1761 auto focused = collapsed ? RowAccess::app(scene).router().setFocus(node) : collapsed;
1762 if (!focused) {
1763 rollback();
1764 return focused;
1765 }
1766 focusedNode = node;
1767 this->position.editing = false;
1768 }
1769 if (!active() || intentGeneration != stagedIntent) {
1770 rollback();
1771 return std::unexpected(TreeError::WOULD_BLOCK);
1772 }
1773 auto nextDataRevision = dataRevision;
1774 if (actual) {
1775 auto latest = currentSource();
1776 auto latestFrame = actual->model ? actual->model->pin()
1777 : std::expected<ModelFrame<T>, TreeError>(std::unexpected(TreeError::CLOSED));
1778 if (!latest || *latest != actual || !latestFrame || latestFrame->revision() != publication) {
1779 rollback();
1780 return std::unexpected(TreeError::WOULD_BLOCK);
1781 }
1782 nextDataRevision = latestFrame->dataRevision();
1783 }
1784 auto &tree = RowAccess::tree(scene);
1785 // Validate every identity before the allocation/callback-free visibility publication.
1786 for (const auto &row : rows) {
1787 auto live = tree.inspect(row->root);
1788 if (!live) {
1789 rollback();
1790 return std::unexpected(live.error());
1791 }
1792 }
1793 for (const auto &row : staging) {
1794 auto live = tree.inspect(row->root);
1795 if (!live) {
1796 rollback();
1797 return std::unexpected(live.error());
1798 }
1799 }
1800 if (editPin) {
1801 auto live = tree.inspect(editPin->root);
1802 if (!live) {
1803 rollback();
1804 return std::unexpected(live.error());
1805 }
1806 }
1807 std::vector<Node<Widget>> visibleNodes(0);
1808 visibleNodes.reserve(staging.size() + 1);
1809 for (const auto &row : staging) {
1810 visibleNodes.push_back(row->root);
1811 }
1812 const bool showBar = this->scrollbar != Node<ScrollBar>{} && this->exactCount &&
1813 ((natural() && *this->exactCount > 0) || *this->exactCount > staging.size()) &&
1814 viewport.width > 1 && viewport.height > 0;
1815 if (showBar) {
1816 visibleNodes.push_back(this->scrollbar);
1817 }
1818 if (saved && !history->valid(*saved)) {
1819 rollback();
1820 return std::unexpected(TreeError::WOULD_BLOCK);
1821 }
1822 auto published = portals::detail::RowTreeAccess::publish(tree, node, visibleNodes);
1823 if (!published) {
1824 rollback();
1825 return std::unexpected(published.error());
1826 }
1827 for (auto &change : refresh) {
1828 change.retired.swap(change.row->pin);
1829 change.row->pin = change.next;
1830 change.row->value = change.value;
1831 change.row->valueRevision = change.revision;
1832 }
1833 rows.swap(staging);
1834 placements.swap(placement);
1835 if (desiredAutoHeight) {
1836 options.autoRowHeight = *desiredAutoHeight;
1837 desiredAutoHeight.reset();
1838 }
1839 if (natural() && offsetFromEnd && !placements.empty()) {
1840 const auto remainder = static_cast<std::int64_t>(placements.front().height) + desiredCellOffset;
1841 if (remainder < 0) {
1842 pendingCells += remainder;
1843 }
1844 }
1845 this->firstCellOffset = desiredCellOffset = nextCellOffset;
1846 offsetFromEnd = false;
1847 awaitingCellMove = false;
1848 // Empty committed data consumes queued movement; a zero-sized hidden viewport
1849 // retains it for later, and loading pages never reach this publication path.
1850 if (rows.empty() &&
1851 ((actual && this->exactCount == std::optional<std::uint64_t>{0}) ||
1852 (!actual && finalWindow &&
1853 (this->sourceStatus == WindowStatus::FINAL_END || this->sourceStatus == WindowStatus::TEMPORARY_TAIL)))) {
1854 pendingCells = 0;
1855 }
1856 allowEndBackfill = false;
1857 lastPage = false;
1858 this->scrollbarVisible = showBar;
1859 editPin.swap(nextPin);
1860 first = desiredFirst = target;
1861 previousSource = actual;
1862 revision = publication;
1863 dataRevision = nextDataRevision;
1864 dirty = false;
1865 blockedAttempt = false;
1866 committedIntent = intentGeneration;
1867 deferredRefresh = deferred;
1868 resetRestoration = false;
1869 failure.reset();
1870 if (metadata.publish) {
1871 metadata.publish(metadata.context);
1872 }
1873 if (saved) {
1874 history->commit(std::move(*saved));
1875 }
1876 auto orientation = publishOrientation(resource, false);
1877 if (!orientation) {
1878 return orientation;
1879 }
1880 // Destructors and unmount callbacks see the fully published assignment set.
1881 for (const auto &row : staging) {
1882 if (std::ranges::find(rows, row) == rows.end() && row != editPin) {
1883 dispose(row);
1884 }
1885 }
1886 if (nextPin && std::ranges::find(rows, nextPin) == rows.end() && nextPin != editPin) {
1887 dispose(nextPin);
1888 }
1889 if (!active()) {
1890 return {};
1891 }
1892 orientation = publishOrientation(resource);
1893 if (!orientation || !active()) {
1894 return orientation;
1895 }
1896 if constexpr (std::same_as<Source, Navigation<T>>) {
1897 if (!rows.empty() && ModelAccess::bindings(source).readingAnchor) {
1898 auto navigation = source.managed();
1899 if (!navigation) {
1900 return std::unexpected(EditAccess::cause(navigation.error()));
1901 }
1902 auto bookmark = ModelBookmark::create(
1903 resource,
1904 {PositionKind::ITEM, rows.front()->id, target, rows.front()->valueRevision, PositionAffinity::FORWARD}, {},
1905 options.checkpoints.bookmarks);
1906 if (!bookmark) {
1907 return std::unexpected(portals::detail::navigationTreeError(bookmark.error()));
1908 }
1909 auto anchored = navigation->setReadingAnchor(*bookmark);
1910 if (!anchored) {
1911 return anchored;
1912 }
1913 if (!active()) {
1914 return {};
1915 }
1916 }
1917 }
1918 for (const auto &row : rows) {
1919 for (const auto label : row->reactiveLabels) {
1920 auto synced = RowAccess::syncCaption(scene, label);
1921 if (!synced) {
1922 return std::unexpected(EditAccess::cause(synced.error()));
1923 }
1924 if (!active()) {
1925 return {};
1926 }
1927 }
1928 }
1929 measuredGeometryRevision = portals::detail::RowTreeAccess::geometryRevision(RowAccess::tree(scene)).value_or(0);
1930 if (natural() && pendingCells && !rows.empty()) {
1931 dirty = true;
1932 auto invalidated = RowAccess::tree(scene).invalidate(node, Invalidation::LAYOUT);
1933 if (!invalidated) {
1934 return invalidated;
1935 }
1936 }
1937 if (pendingEnter) {
1938 const auto requested = *std::exchange(pendingEnter, {});
1939 auto focused = RowAccess::app(scene).router().focused();
1940 if (!focused) {
1941 return std::unexpected(focused.error());
1942 }
1943 if (requested.resource == resource && *focused == node && requested.focusGeneration &&
1944 requested.focusGeneration ==
1945 portals::detail::RowTreeAccess::focusGeneration(RowAccess::app(scene).router()) &&
1946 acceptedResource(requested.resource)) {
1947 return enterEditing();
1948 }
1949 }
1950 return {};
1951 } catch (...) {
1952 rollback();
1953 throw;
1954 }
1955 }
1956
1957 void recordFailure(TreeError error) noexcept {
1958 failure = error;
1959 blockedAttempt = true;
1960 blockedGeometryRevision =
1961 lifetime.expired() ? 0 : portals::detail::RowTreeAccess::geometryRevision(RowAccess::tree(scene)).value_or(0);
1962 if (desiredAutoHeight) {
1963 desiredCellOffset = firstCellOffset;
1964 pendingCells = 0;
1965 offsetFromEnd = false;
1966 awaitingCellMove = false;
1967 desiredAutoHeight.reset();
1968 }
1969 dirty = false;
1970 }
1971
1972 void service() noexcept override {
1973 if (!active()) {
1974 retire();
1975 return;
1976 }
1977 if (portals::detail::RowTreeAccess::dispatching(RowAccess::app(scene).router())) {
1978 return;
1979 }
1980 try {
1981 auto result = applyCellIntent();
1982 if (result) {
1983 result = update();
1984 }
1985 if (!result) {
1986 recordFailure(result.error());
1987 }
1988 } catch (const std::bad_alloc &) {
1989 recordFailure(TreeError::NO_MEMORY);
1990 } catch (...) {
1991 recordFailure(TreeError::CALLBACK_FAILED);
1992 }
1993 }
1994};
1995
1996inline TreeError rowSourceError(SourceError error) noexcept {
1997 switch (error) {
1998 case SourceError::WRONG_THREAD:
1999 return TreeError::WRONG_THREAD;
2000 case SourceError::CLOSED:
2001 return TreeError::CLOSED;
2002 case SourceError::NO_MEMORY:
2003 return TreeError::NO_MEMORY;
2004 case SourceError::WOULD_BLOCK:
2005 return TreeError::WOULD_BLOCK;
2006 case SourceError::IDENTITY_EXHAUSTED:
2007 return TreeError::IDENTITY_EXHAUSTED;
2008 case SourceError::CALLBACK_FAILED:
2009 return TreeError::CALLBACK_FAILED;
2010 default:
2011 return TreeError::INVALID_ARGUMENT;
2012 }
2013}
2014
2015template <class T> class RowWindowJob final : public BackgroundJob {
2016public:
2017 explicit RowWindowJob(WindowRequest<T> request) : request_(std::move(request)) {
2018 }
2019
2020 void run(std::stop_token stop) noexcept override {
2021 try {
2022 result_ = request_.load(stop);
2023 } catch (const std::bad_alloc &) {
2024 result_ = std::unexpected(SourceError::NO_MEMORY);
2025 } catch (...) {
2026 result_ = std::unexpected(SourceError::CALLBACK_FAILED);
2027 }
2028 }
2029
2030 std::expected<void, AsyncError> publish() override {
2031 auto sent = request_.complete(result_);
2032 if (sent) {
2033 return {};
2034 }
2035 switch (sent.error()) {
2036 case SchedulerError::WOULD_BLOCK:
2037 return std::unexpected(AsyncError::WOULD_BLOCK);
2038 case SchedulerError::NO_MEMORY:
2039 return std::unexpected(AsyncError::NO_MEMORY);
2040 case SchedulerError::CLOSED:
2041 return std::unexpected(AsyncError::CLOSED);
2042 default:
2043 return std::unexpected(AsyncError::CALLBACK_FAILED);
2044 }
2045 }
2046
2047private:
2048 WindowRequest<T> request_;
2049 std::expected<SourceReadReply<T>, SourceError> result_{std::unexpected(SourceError::WOULD_BLOCK)};
2050};
2051
2052template <class T, class Factory> struct WindowRowsController final : RowsController<T, Model<T>, Factory> {
2053 using Base = RowsController<T, Model<T>, Factory>;
2054
2055 bool acceptedResource(ModelResource resource) override {
2056 return this->active() && declaration.resource == resource;
2057 }
2058 enum class LoadKind {
2059 NONE,
2060 REPLACE,
2061 APPEND,
2062 PREPEND
2063 };
2064
2065 struct Segment {
2066 WindowPin<T> pin;
2067 bool beforeEnd{};
2068 bool afterEnd{};
2069 bool temporaryAfter{};
2070 };
2071
2072 WindowRowsController(ManagedScene &scene, WindowRowsModel<T> source, Factory create, ControlContext defaults)
2073 : Base(scene, Model<T>{}, std::move(create), std::move(defaults)), declaration(std::move(source)) {
2074 }
2075
2076 ~WindowRowsController() override {
2077 retire();
2078 }
2079
2080 WindowRowsModel<T> declaration;
2081 std::unique_ptr<WindowSource<T>> window;
2082 std::optional<WindowConsumer<T>> consumer;
2083 std::unique_ptr<BackgroundLatest> worker;
2084 std::optional<WindowRequest<T>> pending;
2085 std::array<Segment, 2> segments;
2086 std::size_t segmentCount{};
2087 std::size_t visibleRows{};
2088 std::size_t requestedRows{};
2089 std::int64_t offset{};
2090 std::int64_t wanted{};
2091 std::int64_t replacementOffset{};
2092 LoadKind loading{LoadKind::NONE};
2093 SourceAnchor anchor;
2094 SourceDirection direction{SourceDirection::FORWARD};
2095 bool initialLoad{true};
2096 bool entryKnown{true};
2097 const WindowRow<T> *lastRows{};
2098 std::uint64_t lastRevision{};
2099 std::uint64_t seenRevision{};
2100 std::uint64_t bufferRevision{};
2101 std::uint64_t bufferSerial{};
2102 std::uint64_t renderedSerial{};
2103 std::uint64_t publication{};
2104 std::uint64_t failedSerial{};
2105 std::uint64_t failedIntent{};
2106 std::int64_t failedOffset{};
2107 std::weak_ptr<WindowProvider<T>> preparedProvider;
2108 ModelResource preparedResource;
2109 std::uint64_t preparedRevision{};
2110 std::optional<std::int64_t> deferredCurrentDelta;
2111
2112 std::expected<void, TreeError> protocol(SourceError error) {
2113 this->sourceFailure = error;
2114 return std::unexpected(rowSourceError(error));
2115 }
2116
2117 void retire() noexcept override {
2118 Base::retire();
2119 if (consumer) {
2120 consumer->close();
2121 }
2122 if (window) {
2123 window->close();
2124 }
2125 if (worker) {
2126 worker->cancel();
2127 }
2128 pending.reset();
2129 }
2130
2131 std::size_t storedRows() const noexcept {
2132 std::size_t result{};
2133 for (std::size_t index = 0; index < segmentCount; ++index) {
2134 result += segments[index].pin.size();
2135 }
2136 return result;
2137 }
2138
2139 SourceCursor before() const noexcept {
2140 return segmentCount ? segments[0].pin.page(0).before() : SourceCursor{};
2141 }
2142
2143 SourceCursor after() const noexcept {
2144 if (!segmentCount) {
2145 return {};
2146 }
2147 const auto &pin = segments[segmentCount - 1].pin;
2148 return pin.page(pin.pageCount() - 1).after();
2149 }
2150
2151 std::optional<RowId> rowAt(std::size_t index) const noexcept {
2152 for (std::size_t segment = 0; segment < segmentCount; ++segment) {
2153 for (std::size_t page = 0; page < segments[segment].pin.pageCount(); ++page) {
2154 const auto rows = segments[segment].pin.page(page).rows();
2155 if (index < rows.size()) {
2156 return rows[index].id;
2157 }
2158 index -= rows.size();
2159 }
2160 }
2161 return {};
2162 }
2163
2164 std::expected<void, TreeError> initialize() {
2165 if (!window) {
2166 auto created = WindowSource<T>::create(RowAccess::tree(this->scene), this->node, declaration.provider,
2167 declaration.options, declaration.budget);
2168 if (!created) {
2169 return protocol(created.error());
2170 }
2171 this->sourceCapabilities = (*created)->capabilities();
2172 seenRevision = declaration.options.initialRevision;
2173 window = std::move(*created);
2174 }
2175 if (!consumer) {
2176 auto opened = window->openConsumer();
2177 if (!opened) {
2178 return protocol(opened.error());
2179 }
2180 consumer.emplace(std::move(*opened));
2181 }
2182 return {};
2183 }
2184
2185 std::expected<void, TreeError> beforeMove(std::int64_t target, bool all = false) {
2186 for (std::size_t index = 0; index < this->rows.size(); ++index) {
2187 const auto ordinal = offset + static_cast<std::int64_t>(index);
2188 if (!all && ordinal >= target && ordinal - target < static_cast<std::int64_t>(visibleRows)) {
2189 continue;
2190 }
2191 const auto &row = this->rows[index];
2192 for (const auto &participant : row->participants) {
2193 auto allowed = participant->beforeLeave();
2194 if (!allowed) {
2195 return allowed;
2196 }
2197 }
2198 if (row->dirty() && row->edit->options.mode == EditMode::ON_COMPLETION) {
2199 return std::unexpected(TreeError::WOULD_BLOCK);
2200 }
2201 }
2202 return {};
2203 }
2204
2205 std::expected<void, TreeError> startLoad(SourceAnchor target, SourceDirection traversal, LoadKind kind,
2206 std::int64_t replacement = 0) {
2207 auto request = consumer->request(target, traversal, std::max<std::size_t>(1, requestedRows));
2208 if (!request) {
2209 return protocol(request.error());
2210 }
2211 if (!this->active()) {
2212 request->cancel();
2213 return std::unexpected(TreeError::CLOSED);
2214 }
2215 pending = *request;
2216 loading = kind;
2217 replacementOffset = replacement;
2218 anchor = target;
2219 direction = traversal;
2220 this->sourceStatus = WindowStatus::LOADING;
2221 this->sourceFailure.reset();
2222 return {};
2223 }
2224
2225 std::expected<void, TreeError> requestFirst(std::uint64_t) override {
2226 return protocol(SourceError::UNSUPPORTED);
2227 }
2228
2229 std::expected<void, TreeError> requestMove(std::int64_t delta) override {
2230 if (!this->active()) {
2231 return std::unexpected(TreeError::CLOSED);
2232 }
2233 auto ready = initialize();
2234 if (!ready) {
2235 return ready;
2236 }
2237 if ((delta > 0 && wanted > std::numeric_limits<std::int64_t>::max() - delta) ||
2238 (delta < 0 && wanted < std::numeric_limits<std::int64_t>::min() - delta)) {
2239 return protocol(SourceError::POSITION_EXHAUSTED);
2240 }
2241 auto target = wanted + delta;
2242 if (target < 0 && entryKnown) {
2243 target = 0;
2244 }
2245 if (target < 0 && !window->capabilities().backward) {
2246 return protocol(SourceError::UNSUPPORTED);
2247 }
2248 if (target < offset - this->options.maxPendingRows || target > offset + this->options.maxPendingRows) {
2249 return protocol(SourceError::WOULD_BLOCK);
2250 }
2251 auto allowed = beforeMove(target, loading == LoadKind::REPLACE);
2252 if (!allowed) {
2253 return allowed;
2254 }
2255 if (target == wanted) {
2256 return {};
2257 }
2258 auto invalidated = RowAccess::tree(this->scene).invalidate(this->node, Invalidation::PAINT);
2259 if (!invalidated) {
2260 return invalidated;
2261 }
2262 wanted = target;
2263 this->lastPage = false;
2264 this->allowEndBackfill = true;
2265 this->desiredCellOffset = 0;
2266 this->offsetFromEnd = false;
2267 ++this->intentGeneration;
2268 this->dirty = true;
2269 this->blockedAttempt = false;
2270 return {};
2271 }
2272
2273 bool rowMovePending() const noexcept override {
2274 return wanted != offset;
2275 }
2276
2277 std::expected<void, TreeError> requestPage(bool backwards) override {
2278 if (this->natural()) {
2279 return this->requestCells(backwards ? -this->viewport.height : this->viewport.height);
2280 }
2281 const auto page = static_cast<std::int64_t>(std::max<std::size_t>(1, visibleRows));
2282 return requestMove(backwards ? -page : page);
2283 }
2284
2285 std::expected<void, TreeError> moveCurrent(std::int64_t delta) override {
2286 const auto limit = this->options.maxPendingRows;
2287 if (deferredCurrentDelta) {
2288 if (delta < -limit - *deferredCurrentDelta || delta > limit - *deferredCurrentDelta) {
2289 return protocol(SourceError::WOULD_BLOCK);
2290 }
2291 *deferredCurrentDelta += delta;
2292 return {};
2293 }
2294 if (this->rows.empty()) {
2295 return requestMove(delta);
2296 }
2297 auto current = wanted + static_cast<std::int64_t>(this->currentSlot);
2298 if (!this->selecting && this->position.current) {
2299 std::optional<std::size_t> found;
2300 for (std::size_t index = 0; index < storedRows(); ++index) {
2301 if (rowAt(index) == this->position.current) {
2302 found = index;
2303 break;
2304 }
2305 }
2306 if (found) {
2307 current = static_cast<std::int64_t>(*found);
2308 } else if (window->capabilities().seekRow) {
2309 auto requested = requestAnchor({SourceAnchorKind::ROW, {}, *this->position.current}, SourceDirection::FORWARD);
2310 if (!requested) {
2311 return requested;
2312 }
2313 deferredCurrentDelta = std::clamp(delta, -limit, limit);
2314 return {};
2315 } else {
2316 return protocol(SourceError::UNSUPPORTED);
2317 }
2318 }
2319 const auto boundedDelta = std::clamp(delta, -limit, limit);
2320 auto target = current + boundedDelta;
2321 if (entryKnown) {
2322 target = std::max(std::int64_t{}, target);
2323 }
2324 const auto visible =
2325 static_cast<std::int64_t>(std::max<std::size_t>(1, this->natural() ? this->rows.size() : visibleRows));
2326 const auto nextFirst = target < wanted ? target
2327 : target - wanted >= visible ? (this->natural() ? target : target - visible + 1)
2328 : wanted;
2329 const auto movement = nextFirst - wanted;
2330 if (movement < 0 && !window->capabilities().backward && wanted == 0) {
2331 return {};
2332 }
2333 auto moved =
2334 movement ? requestMove(movement) : RowAccess::tree(this->scene).invalidate(this->node, Invalidation::PAINT);
2335 if (!moved) {
2336 return moved;
2337 }
2338 this->desiredCellOffset = 0;
2339 this->pendingCells = 0;
2340 this->offsetFromEnd = false;
2341 this->currentSlot = static_cast<std::size_t>(target - nextFirst);
2342 this->selecting = true;
2343 this->dirty = true;
2344 this->blockedAttempt = false;
2345 ++this->intentGeneration;
2346 return {};
2347 }
2348
2349 std::expected<void, TreeError> requestAnchor(SourceAnchor target, SourceDirection traversal) override {
2350 if (!this->active()) {
2351 return std::unexpected(TreeError::CLOSED);
2352 }
2353 auto ready = initialize();
2354 if (!ready) {
2355 return ready;
2356 }
2357 auto allowed = beforeMove(0, true);
2358 if (!allowed) {
2359 return allowed;
2360 }
2361 auto invalidated = RowAccess::tree(this->scene).invalidate(this->node, Invalidation::PAINT);
2362 if (!invalidated) {
2363 return invalidated;
2364 }
2365 auto requested = startLoad(target, traversal, LoadKind::REPLACE);
2366 if (!requested) {
2367 return requested;
2368 }
2369 wanted = 0;
2370 this->lastPage = this->natural() && target.kind == SourceAnchorKind::TAIL;
2371 this->allowEndBackfill = this->lastPage;
2372 this->desiredCellOffset = 0;
2373 this->pendingCells = 0;
2374 deferredCurrentDelta.reset();
2375 initialLoad = false;
2376 entryKnown = target.kind == SourceAnchorKind::ENTRY && traversal == SourceDirection::FORWARD;
2377 ++this->intentGeneration;
2378 this->dirty = true;
2379 this->blockedAttempt = false;
2380 return {};
2381 }
2382
2383 std::expected<void, TreeError> notifyReady(std::uint64_t revision) override {
2384 auto ready = initialize();
2385 if (!ready) {
2386 return ready;
2387 }
2388 auto sent = window->notifyReady(window->stamp(), revision);
2389 return sent ? std::expected<void, TreeError>{} : protocol(sent.error());
2390 }
2391
2392 std::expected<void, TreeError> replaceModel(Model<T>, ModelRebindOptions) override {
2393 return protocol(SourceError::UNSUPPORTED);
2394 }
2395
2396 std::expected<std::optional<portals::detail::ModelViewHistoryChange>, TreeError> captureHistory() {
2397 auto provider = preparedProvider.lock();
2398 if (!provider || this->rows.empty() || !preparedRevision) {
2399 return std::optional<portals::detail::ModelViewHistoryChange>{};
2400 }
2401 auto ready = this->ensureHistory();
2402 if (!ready) {
2403 return std::unexpected(ready.error());
2404 }
2405 auto bookmark = ModelBookmark::create(
2406 preparedResource, {PositionKind::ITEM, this->rows.front()->id, 0, preparedRevision, PositionAffinity::FORWARD},
2407 {}, this->options.checkpoints.bookmarks);
2408 if (!bookmark) {
2409 this->sourceFailure = bookmark.error();
2410 return std::unexpected(rowSourceError(bookmark.error()));
2411 }
2412 portals::detail::ModelViewCheckpoint checkpoint;
2413 checkpoint.reading = *bookmark;
2414 if (this->natural()) {
2415 checkpoint.readingCellOffset = this->firstCellOffset;
2416 }
2417 if (this->position.current) {
2418 auto current = ModelBookmark::create(
2419 preparedResource, {PositionKind::ITEM, *this->position.current, 0, preparedRevision, PositionAffinity::FORWARD},
2420 {}, this->options.checkpoints.bookmarks);
2421 if (!current) {
2422 this->sourceFailure = current.error();
2423 return std::unexpected(rowSourceError(current.error()));
2424 }
2425 checkpoint.current = *current;
2426 }
2427 auto saved = this->history->stageResource(preparedResource, provider, this->historyRole, std::move(checkpoint));
2428 return saved ? std::expected<std::optional<portals::detail::ModelViewHistoryChange>, TreeError>(
2429 std::optional(std::move(*saved)))
2430 : std::unexpected(saved.error());
2431 }
2432 std::expected<void, TreeError> replaceWindowModel(const WindowRowsModel<T> &target,
2433 ModelRebindOptions rebind) override try {
2434 if (!this->active()) {
2435 return std::unexpected(TreeError::CLOSED);
2436 }
2437 if (!target.provider || target.failure || !target.resource.identity.instance || !target.resource.identity.epoch ||
2438 !target.resource.lineage) {
2439 return protocol(target.failure.value_or(SourceError::INVALID_ARGUMENT));
2440 }
2441 auto allowed = beforeMove(0, true);
2442 if (!allowed) {
2443 return allowed;
2444 }
2445 if (declaration.provider == target.provider && declaration.resource == target.resource) {
2446 return rebind.restore == ModelRestorePolicy::RESET ? requestAnchor({}, SourceDirection::FORWARD)
2447 : std::expected<void, TreeError>{};
2448 }
2449 const auto generation = this->intentGeneration;
2450 auto saved = captureHistory();
2451 if (!saved) {
2452 return std::unexpected(saved.error());
2453 }
2454 SourceAnchor restore;
2455 std::optional<RowId> restoreCurrent;
2456 std::int32_t restoreCellOffset{};
2457 if (rebind.restore == ModelRestorePolicy::REMEMBER && this->history) {
2458 auto checkpoint = this->history->find(target.resource, this->historyRole, false);
2459 if (checkpoint && checkpoint->value.reading) {
2460 restore = {SourceAnchorKind::ROW, {}, checkpoint->value.reading->position().row};
2461 restoreCellOffset = this->natural() ? checkpoint->value.readingCellOffset.value_or(0) : 0;
2462 if (checkpoint->value.current) {
2463 restoreCurrent = checkpoint->value.current->position().row;
2464 }
2465 }
2466 }
2467 auto nextDeclaration = target;
2468 if (!nextDeclaration.budget && window) {
2469 nextDeclaration.budget = window->budget();
2470 }
2471 auto created = WindowSource<T>::create(RowAccess::tree(this->scene), this->node, nextDeclaration.provider,
2472 nextDeclaration.options, nextDeclaration.budget);
2473 if (!created) {
2474 return protocol(created.error());
2475 }
2476 if (restore.kind == SourceAnchorKind::ROW && !(*created)->capabilities().seekRow) {
2477 return protocol(SourceError::UNSUPPORTED);
2478 }
2479 auto opened = (*created)->openConsumer();
2480 if (!opened) {
2481 return protocol(opened.error());
2482 }
2483 if (!this->active() || this->intentGeneration != generation || (*saved && !this->history->valid(**saved))) {
2484 return std::unexpected(TreeError::WOULD_BLOCK);
2485 }
2486 auto invalidated = RowAccess::tree(this->scene).invalidate(this->node, Invalidation::LAYOUT);
2487 if (!invalidated) {
2488 return invalidated;
2489 }
2490 auto oldWindow = std::move(window);
2491 auto oldConsumer = std::move(consumer);
2492 auto oldWorker = std::move(worker);
2493 auto oldPending = std::move(pending);
2494 auto oldDeclaration = std::move(declaration);
2495 window = std::move(*created);
2496 consumer.emplace(std::move(*opened));
2497 declaration = std::move(nextDeclaration);
2498 this->restoredCurrent = restoreCurrent;
2499 this->desiredCellOffset = restoreCellOffset;
2500 this->pendingCells = 0;
2501 this->lastPage = false;
2502 this->allowEndBackfill = false;
2503 this->offsetFromEnd = false;
2504 deferredCurrentDelta.reset();
2505 pending.reset();
2506 this->sourceCapabilities = window->capabilities();
2507 this->sourceStatus = WindowStatus::EMPTY;
2508 this->sourceFailure.reset();
2509 this->failure.reset();
2510 requestedRows = 0;
2511 initialLoad = true;
2512 loading = LoadKind::NONE;
2513 anchor = restore;
2514 direction = SourceDirection::FORWARD;
2515 replacementOffset = wanted = 0;
2516 entryKnown = restore.kind == SourceAnchorKind::ENTRY;
2517 lastRows = nullptr;
2518 lastRevision = 0;
2519 seenRevision = declaration.options.initialRevision;
2520 ++this->intentGeneration;
2521 this->dirty = true;
2522 this->blockedAttempt = false;
2523 if (*saved) {
2524 this->history->commit(std::move(**saved));
2525 }
2526 if (oldConsumer) {
2527 oldConsumer->close();
2528 }
2529 if (oldWindow) {
2530 oldWindow->close();
2531 }
2532 if (oldWorker) {
2533 oldWorker->cancel();
2534 }
2535 return {};
2536 } catch (const std::bad_alloc &) {
2537 return protocol(SourceError::NO_MEMORY);
2538 } catch (...) {
2539 return protocol(SourceError::CALLBACK_FAILED);
2540 }
2541
2542 std::expected<void, TreeError> dispatch(WindowRequest<T> request) {
2543 auto *executor = RowAccess::app(this->scene).background();
2544 if (!executor) {
2545 pending = std::move(request);
2546 return std::unexpected(TreeError::WOULD_BLOCK);
2547 }
2548 if (!worker) {
2549 worker = std::make_unique<BackgroundLatest>(*executor);
2550 }
2551 auto admitted = worker->replace(std::make_unique<RowWindowJob<T>>(std::move(request)));
2552 if (!admitted) {
2553 return std::unexpected(admitted.error() == BackgroundError::NO_MEMORY ? TreeError::NO_MEMORY
2554 : TreeError::WOULD_BLOCK);
2555 }
2556 return {};
2557 }
2558
2559 std::expected<void, TreeError> serviceWork() {
2560 if (pending) {
2561 auto request = std::exchange(pending, {});
2562 auto sent = dispatch(*request);
2563 if (!sent) {
2564 return sent;
2565 }
2566 }
2567 if (worker) {
2568 auto serviced = worker->service();
2569 if (!serviced) {
2570 return std::unexpected(serviced.error() == BackgroundError::NO_MEMORY ? TreeError::NO_MEMORY
2571 : TreeError::WOULD_BLOCK);
2572 }
2573 }
2574 auto continuation = consumer->takeRequest();
2575 if (!continuation) {
2576 return protocol(continuation.error());
2577 }
2578 if (*continuation) {
2579 return dispatch(**continuation);
2580 }
2581 return {};
2582 }
2583
2584 std::expected<void, TreeError> refill() {
2585 SourceAnchor target = anchor;
2586 auto local = wanted;
2587 if (segmentCount && offset >= 0 && static_cast<std::size_t>(offset) < storedRows()) {
2588 auto id = rowAt(static_cast<std::size_t>(offset));
2589 if (id && window->capabilities().seekRow) {
2590 target = {SourceAnchorKind::ROW, {}, *id};
2591 local = wanted - offset;
2592 } else {
2593 std::size_t segment{};
2594 std::int64_t first{};
2595 while (segment + 1 < segmentCount &&
2596 offset >= first + static_cast<std::int64_t>(segments[segment].pin.size())) {
2597 first += static_cast<std::int64_t>(segments[segment++].pin.size());
2598 }
2599 target = {SourceAnchorKind::CURSOR, segments[segment].pin.page(0).before(), {}};
2600 local = wanted - first;
2601 }
2602 }
2603 auto requested = startLoad(target, SourceDirection::FORWARD, LoadKind::REPLACE, local);
2604 if (requested) {
2605 wanted = local;
2606 }
2607 return requested;
2608 }
2609
2610 void integrate(WindowPin<T> pin) {
2611 Segment next{pin};
2612 if (direction == SourceDirection::FORWARD) {
2613 next.afterEnd = pin.edge() == SourceEdge::FINAL_END;
2614 next.temporaryAfter = pin.edge() == SourceEdge::TEMPORARY_TAIL;
2615 } else {
2616 next.beforeEnd = pin.edge() == SourceEdge::FINAL_END;
2617 next.temporaryAfter = anchor.kind == SourceAnchorKind::TAIL && loading == LoadKind::REPLACE;
2618 }
2619 if (loading == LoadKind::REPLACE || !segmentCount || bufferRevision != pin.dataRevision()) {
2620 segments[0] = std::move(next);
2621 segments[1] = {};
2622 segmentCount = 1;
2623 segments[0].beforeEnd = segments[0].beforeEnd || entryKnown;
2624 offset = replacementOffset;
2625 if (direction == SourceDirection::BACKWARD && anchor.kind == SourceAnchorKind::TAIL) {
2626 wanted =
2627 std::max<std::int64_t>(0, static_cast<std::int64_t>(pin.size()) - static_cast<std::int64_t>(visibleRows));
2628 offset = wanted;
2629 }
2630 } else if (!pin.size()) {
2631 if (loading == LoadKind::APPEND) {
2632 segments[segmentCount - 1].afterEnd = next.afterEnd;
2633 segments[segmentCount - 1].temporaryAfter = next.temporaryAfter;
2634 } else {
2635 segments[0].beforeEnd = next.beforeEnd;
2636 }
2637 } else if (loading == LoadKind::APPEND) {
2638 if (segmentCount == 2 && wanted >= static_cast<std::int64_t>(segments[0].pin.size())) {
2639 const auto removed = static_cast<std::int64_t>(segments[0].pin.size());
2640 segments[0] = std::move(segments[1]);
2641 segmentCount = 1;
2642 offset -= removed;
2643 wanted -= removed;
2644 entryKnown = false;
2645 }
2646 if (segmentCount < 2) {
2647 segments[segmentCount++] = std::move(next);
2648 }
2649 } else if (loading == LoadKind::PREPEND) {
2650 const auto added = static_cast<std::int64_t>(pin.size());
2651 segments[1] = std::move(segments[0]);
2652 segments[0] = std::move(next);
2653 segmentCount = 2;
2654 offset += added;
2655 wanted += added;
2656 entryKnown = segments[0].beforeEnd;
2657 }
2658 bufferRevision = pin.dataRevision();
2659 lastRows = pin.page(0).rows().data();
2660 lastRevision = pin.dataRevision();
2661 loading = LoadKind::NONE;
2662 ++bufferSerial;
2663 this->dirty = true;
2664 this->blockedAttempt = false;
2665 }
2666
2667 std::expected<bool, TreeError> needDelivery() {
2668 if (loading != LoadKind::NONE) {
2669 return true;
2670 }
2671 const auto total = static_cast<std::int64_t>(storedRows());
2672 if (!segmentCount) {
2673 return true;
2674 }
2675 if (wanted < 0) {
2676 if (segments[0].beforeEnd) {
2677 wanted = 0;
2678 return false;
2679 }
2680 auto requested =
2681 startLoad({SourceAnchorKind::CURSOR, before(), {}}, SourceDirection::BACKWARD, LoadKind::PREPEND);
2682 return requested ? std::expected<bool, TreeError>(true) : std::unexpected(requested.error());
2683 }
2684 const auto &last = segments[segmentCount - 1];
2685 const bool missing = wanted >= total || static_cast<std::uint64_t>(total - wanted) < visibleRows;
2686 if (!missing) {
2687 return false;
2688 }
2689 if (last.afterEnd || last.temporaryAfter) {
2690 wanted = total ? std::min(wanted, total - 1) : 0;
2691 return false;
2692 }
2693 if (this->sourceStatus == WindowStatus::FAILED) {
2694 return false;
2695 }
2696 if (segmentCount == 2 && wanted < static_cast<std::int64_t>(segments[0].pin.size())) {
2697 this->sourceFailure = SourceError::CONTINUATION_LIMIT;
2698 this->sourceStatus = WindowStatus::FAILED;
2699 return false;
2700 }
2701 auto requested = startLoad({SourceAnchorKind::CURSOR, after(), {}}, SourceDirection::FORWARD, LoadKind::APPEND);
2702 return requested ? std::expected<bool, TreeError>(true) : std::unexpected(requested.error());
2703 }
2704
2705 std::expected<void, TreeError> renderBuffer() {
2706 if (wanted < 0 || wanted > static_cast<std::int64_t>(storedRows())) {
2707 return {};
2708 }
2709 if (!this->dirty && renderedSerial == bufferSerial && offset == wanted) {
2710 auto measured = this->refreshNaturalLayout();
2711 if (!measured || !this->dirty) {
2712 return measured;
2713 }
2714 }
2715 if (this->blockedAttempt && failedSerial == bufferSerial && failedIntent == this->intentGeneration &&
2716 failedOffset == wanted &&
2717 (!this->natural() ||
2718 this->blockedGeometryRevision ==
2719 portals::detail::RowTreeAccess::geometryRevision(RowAccess::tree(this->scene)).value_or(0))) {
2720 return {};
2721 }
2722 const auto total = static_cast<std::int64_t>(storedRows());
2723 const bool atEnd =
2724 segmentCount && (segments[segmentCount - 1].afterEnd || segments[segmentCount - 1].temporaryAfter);
2725 const auto readFirst =
2726 this->natural() && this->allowEndBackfill && atEnd && total - wanted < static_cast<std::int64_t>(visibleRows)
2727 ? std::max<std::int64_t>(0, total - static_cast<std::int64_t>(visibleRows))
2728 : wanted;
2729 const auto leadingRows = static_cast<std::size_t>(wanted - readFirst);
2730 std::vector<DeliveredRow<T>> values(0);
2731 values.reserve(visibleRows);
2732 auto skip = static_cast<std::size_t>(readFirst);
2733 for (std::size_t segment = 0; segment < segmentCount && values.size() < visibleRows; ++segment) {
2734 for (std::size_t page = 0; page < segments[segment].pin.pageCount() && values.size() < visibleRows; ++page) {
2735 auto data = segments[segment].pin.page(page);
2736 if (skip >= data.rows().size()) {
2737 skip -= data.rows().size();
2738 continue;
2739 }
2740 auto owner = std::make_shared<WindowPage<T>>(data);
2741 for (const auto &row : data.rows().subspan(skip)) {
2742 if (values.size() == visibleRows) {
2743 break;
2744 }
2745 values.push_back({row.id, &row.value, row.valueRevision, owner});
2746 }
2747 skip = 0;
2748 }
2749 }
2750 failedSerial = bufferSerial;
2751 failedIntent = this->intentGeneration;
2752 failedOffset = wanted;
2753 const bool hasBefore = readFirst > 0 || (window->capabilities().backward && segmentCount && !segments[0].beforeEnd);
2754 const bool hasAfter =
2755 readFirst + static_cast<std::int64_t>(values.size()) < static_cast<std::int64_t>(storedRows()) ||
2756 (segmentCount && !segments[segmentCount - 1].afterEnd && !segments[segmentCount - 1].temporaryAfter);
2757
2758 struct Metadata {
2759 WindowRowsController &host;
2760 std::weak_ptr<WindowProvider<T>> provider;
2761 ModelResource resource;
2762 std::uint64_t revision;
2763 std::int64_t offset;
2764 std::uint64_t serial;
2765 bool before;
2766 bool after;
2767 std::size_t delivered;
2768 } metadata{*this, declaration.provider, declaration.resource, bufferRevision, readFirst, bufferSerial, hasBefore,
2769 hasAfter, values.size()};
2770
2771 auto committed = this->commitRows(
2772 {}, {}, values, ++publication, 0, declaration.resource, window->stamp(), {},
2773 {&metadata,
2774 [](void *context) noexcept {
2775 auto &next = *static_cast<Metadata *>(context);
2776 next.host.preparedProvider.swap(next.provider);
2777 next.host.preparedResource = next.resource;
2778 next.host.preparedRevision = next.revision;
2779 next.host.offset = next.offset + static_cast<std::int64_t>(next.host.first);
2780 next.host.wanted = next.host.offset;
2781 next.host.renderedSerial = next.serial;
2782 next.host.recordHasBefore = next.before || next.host.first > 0;
2783 next.host.recordHasAfter = next.after || next.host.rows.size() + next.host.first < next.delivered;
2784 next.host.position.hasBefore = next.host.recordHasBefore || next.host.firstCellOffset > 0;
2785 next.host.position.hasAfter =
2786 next.host.recordHasAfter ||
2787 (!next.host.placements.empty() &&
2788 static_cast<std::int64_t>(next.host.placements.back().y) + next.host.placements.back().height >
2789 next.host.viewport.height);
2790 }},
2791 leadingRows, !hasAfter, hasBefore);
2792 if (!committed || !this->active()) {
2793 return committed;
2794 }
2795 if (deferredCurrentDelta) {
2796 const auto delta = *std::exchange(deferredCurrentDelta, {});
2797 return moveCurrent(delta);
2798 }
2799 return {};
2800 }
2801
2802 std::expected<void, TreeError> updateWindow() {
2803 auto focus = this->observeFocus();
2804 if (!focus) {
2805 return focus;
2806 }
2807 auto ready = initialize();
2808 if (!ready) {
2809 return ready;
2810 }
2811 const auto demand = this->rowDemand();
2812 if (demand > this->options.maxRows) {
2813 return std::unexpected(TreeError::NODE_LIMIT);
2814 }
2815 if (!demand) {
2816 if (requestedRows) {
2817 (void)consumer->cancel();
2818 if (worker) {
2819 worker->cancel();
2820 }
2821 pending.reset();
2822 loading = LoadKind::NONE;
2823 requestedRows = 0;
2824 initialLoad = true;
2825 }
2826 if (this->rows.empty()) {
2827 this->dirty = false;
2828 return {};
2829 }
2830 auto allowed = beforeMove(0, true);
2831 if (!allowed) {
2832 return allowed;
2833 }
2834 return this->commitRows({}, {}, {}, ++publication, 0, declaration.resource, window->stamp());
2835 }
2836 visibleRows = demand;
2837 const auto windowRows = demand + std::min(this->options.overscanRows, this->options.maxRows - demand);
2838 auto revision = window->dataRevision();
2839 if (!revision) {
2840 return protocol(revision.error());
2841 }
2842 if (requestedRows != windowRows || initialLoad || *revision != seenRevision) {
2843 requestedRows = windowRows;
2844 seenRevision = *revision;
2845 auto requested = initialLoad ? startLoad(anchor, direction, LoadKind::REPLACE, wanted) : refill();
2846 if (!requested) {
2847 return requested;
2848 }
2849 initialLoad = false;
2850 }
2851 auto serviced = serviceWork();
2852 if (!serviced) {
2853 return serviced;
2854 }
2855 auto status = consumer->status();
2856 if (!status) {
2857 return protocol(status.error());
2858 }
2859 this->sourceStatus = *status;
2860 auto failure = consumer->lastError();
2861 if (failure) {
2862 this->sourceFailure = *failure;
2863 }
2864 auto recovery = consumer->recovery();
2865 if (recovery) {
2866 this->sourceRecovery = *recovery;
2867 }
2868 auto pin = consumer->pin();
2869 if (!pin) {
2870 return protocol(pin.error());
2871 }
2872 const bool readyPin = *status == WindowStatus::READY || *status == WindowStatus::FINAL_END ||
2873 *status == WindowStatus::TEMPORARY_TAIL ||
2874 (*status == WindowStatus::FAILED && this->sourceFailure == SourceError::CONTINUATION_LIMIT);
2875 if (readyPin && pin->pageCount() &&
2876 (loading != LoadKind::NONE || pin->page(0).rows().data() != lastRows || pin->dataRevision() != lastRevision)) {
2877 integrate(*pin);
2878 }
2879 if (*status == WindowStatus::LOADING || *status == WindowStatus::PENDING ||
2880 *status == WindowStatus::HISTORY_UNAVAILABLE) {
2881 return {};
2882 }
2883 auto delivery = needDelivery();
2884 if (!delivery) {
2885 return std::unexpected(delivery.error());
2886 }
2887 return *delivery ? std::expected<void, TreeError>{} : renderBuffer();
2888 }
2889
2890 void service() noexcept override {
2891 if (!this->active()) {
2892 retire();
2893 return;
2894 }
2895 if (portals::detail::RowTreeAccess::dispatching(RowAccess::app(this->scene).router())) {
2896 return;
2897 }
2898 try {
2899 auto result = this->applyCellIntent();
2900 if (result) {
2901 result = updateWindow();
2902 }
2903 if (!result) {
2904 this->recordFailure(result.error());
2905 }
2906 } catch (const std::bad_alloc &) {
2907 this->recordFailure(TreeError::NO_MEMORY);
2908 } catch (...) {
2909 this->recordFailure(TreeError::CALLBACK_FAILED);
2910 }
2911 }
2912};
2913
2915} // namespace portals::ui::detail
2916
2917namespace portals::ui {
2926template <class Source, class Factory>
2927 requires requires { typename Source::Row; } &&
2928 (std::same_as<Source, Model<typename Source::Row>> || std::same_as<Source, Navigation<typename Source::Row>>)
2929auto virtualRows(Source source, Factory factory, VirtualRowsOptions options = {},
2930 SizePolicy policy = DEFAULT_VIEWPORT_POLICY) {
2931 using T = typename Source::Row;
2932 auto description = detail::Access::cold<VirtualRows<T>>(
2933 [source = std::move(source), factory = std::move(factory), options,
2934 policy](ManagedScene &scene, Node<Widget> parent,
2935 detail::MountContext &context) mutable -> std::expected<Node<VirtualRows<T>>, ManagedError> {
2936 if (options.rowHeight <= 0 || !options.maxRows || options.maxPendingRows <= 0 ||
2937 options.maxPendingRows > std::numeric_limits<std::int32_t>::max()) {
2938 return std::unexpected(detail::error(parent, TreeError::INVALID_ARGUMENT));
2939 }
2940 auto model = detail::ModelAccess::source(scene, source, context);
2941 if (!model) {
2942 return std::unexpected(model.error());
2943 }
2944 auto controller = std::make_shared<detail::RowsController<T, Source, Factory>>(scene, source, std::move(factory),
2945 context.controls);
2946 controller->options = options;
2947 controller->layoutLease = detail::RowAccess::layoutLease(scene);
2948 controller->initialModel = *model;
2949 auto node = scene.emplace<VirtualRows<T>>(parent, controller, policy);
2950 if (!node) {
2951 return std::unexpected(node.error());
2952 }
2953 controller->node = *node;
2954 detail::ModelAccess::keep(scene, *node, context);
2955 if constexpr (std::same_as<Source, Navigation<T>>) {
2956 auto navigation = detail::ModelAccess::resolve(scene, source, context);
2957 if (!navigation) {
2958 return std::unexpected(navigation.error());
2959 }
2960 auto registered = controller->registerNavigation(*navigation);
2961 if (!registered) {
2962 return std::unexpected(detail::error(*node, registered.error()));
2963 }
2964 }
2965 auto bound = controller->bindInput();
2966 if (!bound) {
2967 return std::unexpected(detail::error(*node, bound.error()));
2968 }
2969 auto admitted = detail::RowAccess::admit(scene, controller);
2970 return admitted ? node : std::unexpected(admitted.error());
2971 });
2972 return detail::Access::configuredControl(std::move(description), "VirtualRows");
2973}
2974
2981template <class T, class Factory>
2982auto virtualRows(WindowRowsModel<T> source, Factory factory, VirtualRowsOptions options = {},
2983 SizePolicy policy = DEFAULT_VIEWPORT_POLICY) {
2984 auto description = detail::Access::cold<VirtualRows<T>>(
2985 [source = std::move(source), factory = std::move(factory), options,
2986 policy](ManagedScene &scene, Node<Widget> parent,
2987 detail::MountContext &context) mutable -> std::expected<Node<VirtualRows<T>>, ManagedError> {
2988 if (!source.provider || source.failure || !source.resource.identity.instance || !source.resource.identity.epoch ||
2989 !source.resource.lineage || options.rowHeight <= 0 || !options.maxRows || options.maxPendingRows <= 0 ||
2990 options.maxPendingRows > std::numeric_limits<std::int32_t>::max()) {
2991 return std::unexpected(detail::error(parent, source.failure ? detail::rowSourceError(*source.failure)
2993 }
2994 auto background = detail::RowAccess::background(scene);
2995 if (!background) {
2996 return std::unexpected(background.error());
2997 }
2998 auto controller = std::make_shared<detail::WindowRowsController<T, Factory>>(
2999 scene, std::move(source), std::move(factory), context.controls);
3000 controller->options = options;
3001 controller->layoutLease = detail::RowAccess::layoutLease(scene);
3002 auto node = scene.emplace<VirtualRows<T>>(parent, controller, policy);
3003 if (!node) {
3004 return std::unexpected(node.error());
3005 }
3006 controller->node = *node;
3007 detail::ModelAccess::keep(scene, *node, context);
3008 auto bound = controller->bindInput();
3009 if (!bound) {
3010 return std::unexpected(detail::error(*node, bound.error()));
3011 }
3012 auto admitted = detail::RowAccess::admit(scene, controller);
3013 return admitted ? node : std::unexpected(admitted.error());
3014 });
3015 return detail::Access::configuredControl(std::move(description), "VirtualRows");
3016}
3017} // namespace portals::ui
consteval auto background(E expression)
Definition style_static.hpp:906
auto live(ManagedScene &scene, const S &description)
Definition style_static.hpp:1703
auto change(T value)
Definition style_static.hpp:1496
std::expected< void, ProcessContextError > initialize(int argc, const char *const *argv)
Capture argv and the environment once, before any concurrent foreign environment mutation....
@ CANCEL
Cancel the current interaction.
Definition action.hpp:12
@ MOVE_DOWN
Move down according to the receiving widget.
Definition action.hpp:16
@ ACTIVATE
Activate the target's primary command.
Definition action.hpp:11
@ MOVE_HOME
Move to the beginning according to the receiving widget.
Definition action.hpp:17
@ MOVE_END
Move to the end according to the receiving widget.
Definition action.hpp:18
@ MOVE_UP
Move up according to the receiving widget.
Definition action.hpp:15
@ REPLACE
Explicit mode only: hide the independently owned body outside READY/REFRESHING.
Definition data_presentation.hpp:65
std::expected< void, TreeError > setScrollOffset(WidgetTree &tree, Node< Widget > node, ScrollAxis axis, ScrollOffset offset)
@ APPEND
Append application bytes to a live value.
Definition secure_string.hpp:72
EventReply
Explicit bubbling decision; ignored continues toward the original root.
Definition action.hpp:49
constexpr SizePolicy DEFAULT_VIEWPORT_POLICY
A bounded data viewport fills both axes without requesting the whole model extent.
Definition layout.hpp:53
@ CLOSED
Owner, node scope, scheduler or completion endpoint is closed.
Definition async.hpp:28
std::expected< void, TreeError > setScrollMetrics(WidgetTree &tree, Node< ScrollBar > node, ScrollAxisMetrics metrics)
SourceError
Source protocol and admission failures, independent of a provider's storage format.
Definition source_budget.hpp:14
SourceDirection
Requested traversal; returned rows remain in display order.
Definition window_source.hpp:47
constexpr SizePolicy DEFAULT_FLEX_WIDTH_POLICY
Fill available width from a zero flex basis while retaining content height.
Definition layout.hpp:47
@ NONE
Caption only, including a single-glyph action button.
Definition controls.hpp:157
Invalidation
Accumulated work; layout always includes painting.
Definition widget_types.hpp:41
@ PAINT
Painting is required; arranged geometry remains usable.
Definition widget_types.hpp:43
TreeError
Checked tree failures; rejected operations never start the requested callback.
Definition widget_types.hpp:26
@ INVALID_ARGUMENT
An option, enum value or operation argument is invalid.
Definition widget_types.hpp:27
InputKey key
Semantic identity.
Definition input.hpp:214
KeyAction action
Observed action; VT does not infer held state.
Definition input.hpp:217
Cold native window delivery capability, with no invented finite extent/current.
Definition ui_virtual_rows.hpp:364
static Description< T > configuredControl(Description< T > description, std::string_view type, bool inherit=true)
Attach a builtin configuration identity to an owning recipe.
Definition ui_description.hpp:3409
Stack-owned transaction bookkeeping, discarded after one description mount.
Definition ui_recipe_context.hpp:554