5namespace portals::ui::detail {
8template <
class T,
class Source,
class Factory>
9struct RowsController : VirtualRowsState,
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)) {
19 ~RowsController()
override {
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;
39 ModelResource resource;
40 std::uint64_t focusGeneration{};
43 std::optional<EnterIntent> pendingEnter;
44 std::size_t retainedColumn{};
45 std::optional<EditFieldKey> retainedField;
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{};
56 std::optional<bool> desiredAutoHeight;
57 std::uint64_t measuredGeometryRevision{};
58 std::uint64_t blockedGeometryRevision{};
59 bool recordHasBefore{};
60 bool recordHasAfter{};
61 bool allowEndBackfill{};
63 std::int32_t desiredCellOffset{};
64 std::int64_t pendingCells{};
66 bool awaitingCellMove{};
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;
77 std::weak_ptr<portals::detail::ManagedModelSourceOf<T>> source;
78 std::uint64_t revision{};
79 std::uint64_t intent{};
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;
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{};
97 std::expected<void, TreeError> replaceModel(Model<T> target, ModelRebindOptions rebind)
override try {
99 return std::unexpected(TreeError::CLOSED);
101 if constexpr (std::same_as<Source, Navigation<T>>) {
102 auto changed = source.setModel(std::move(target), rebind);
104 return std::unexpected(EditAccess::cause(changed.error()));
107 MountContext context;
108 auto model = ModelAccess::resolve(scene, target, context);
110 return std::unexpected(EditAccess::cause(model.error()));
113 return std::unexpected(TreeError::CLOSED);
115 auto actual = RowAccess::source(*model);
117 return std::unexpected(actual.error());
119 auto allowed = beforeTransition(
nullptr, *actual);
123 auto invalidated = RowAccess::tree(scene).invalidate(node, Invalidation::LAYOUT);
127 auto previous = source;
128 initialModel = *model;
129 source = std::move(target);
130 ModelAccess::publish(context);
132 resetRestoration = rebind.restore == ModelRestorePolicy::RESET;
135 blockedAttempt =
false;
137 }
catch (
const std::bad_alloc &) {
138 return std::unexpected(TreeError::NO_MEMORY);
140 return std::unexpected(TreeError::CALLBACK_FAILED);
143 void closed() noexcept
override {
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) {
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;
158 if (!sameSource || !visibleTarget) {
159 return std::unexpected(TreeError::WOULD_BLOCK);
165 std::expected<void, TreeError> registerNavigation(ManagedNavigation navigation) {
166 auto record = EditAccess::context(navigation);
168 return std::unexpected(record.error());
170 if ((*record)->admittingEdit) {
171 return std::unexpected(TreeError::WOULD_BLOCK);
173 if (!(*record)->editors) {
174 (*record)->editors = std::make_unique<std::vector<std::weak_ptr<portals::detail::EditNavigationParticipant>>>(0);
176 (*record)->editors->push_back(this->shared_from_this());
180 std::expected<void, TreeError> prepareChrome() {
181 auto glyph = GraphemeText::from(
">", scene.widthPolicy());
183 return std::unexpected(TreeError::INVALID_ARGUMENT);
185 this->currentGlyph = std::move(*glyph);
186 auto scope = RowAccess::app(scene).router().focusScope(node, node);
188 return std::unexpected(scope.error());
190 focusBinding.emplace(std::move(*scope));
191 auto composite = portals::detail::RowTreeAccess::focusScope(RowAccess::app(scene).router(), node);
195 if (options.scrollbar) {
196 auto controller = ScrollController::create();
198 return std::unexpected(controller.error());
200 scrollController = *controller;
201 auto bar = scene.scrollBar(node, scrollController);
203 return std::unexpected(EditAccess::cause(bar.error()));
205 this->scrollbar = *bar;
206 auto chrome = portals::detail::RowTreeAccess::focusScope(RowAccess::app(scene).router(), node, {}, *bar);
210 auto hidden = RowAccess::tree(scene).setVisible(*bar,
false);
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) ||
224 auto entered = this->enterEditing();
226 this->failure = entered.error();
228 this->failure.reset();
230 return EventReply::HANDLED;
233 auto left = this->leaveEditing();
235 this->failure = left.error();
237 this->failure.reset();
239 return EventReply::HANDLED;
241 const bool wheel = mouse && mouse->action == MouseAction::SCROLL &&
242 (mouse->button == MouseButton::WHEEL_UP || mouse->button == MouseButton::WHEEL_DOWN);
244 key && key->
action != KeyAction::RELEASE && (key->
key == InputKey::PAGE_UP || key->
key == InputKey::PAGE_DOWN);
246 pendingEnter.reset();
247 const bool backwards = wheel ? mouse->button == MouseButton::WHEEL_UP : key->
key == InputKey::PAGE_UP;
249 (mouse->modifiers.alt || mouse->modifiers.control || mouse->modifiers.super || mouse->modifiers.shift)) {
250 return EventReply::IGNORED;
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);
257 this->failure = changed.error();
259 return EventReply::HANDLED;
263 return EventReply::IGNORED;
265 auto focused = RowAccess::app(this->scene).router().focused();
266 if (!focused || *focused != this->node) {
269 return EventReply::HANDLED;
271 std::expected<void, TreeError> changed;
272 pendingEnter.reset();
274 changed = this->moveCurrent(-1);
276 changed = this->moveCurrent(1);
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);
282 if (this->sourceCapabilities && (!this->sourceCapabilities->tail || !this->sourceCapabilities->backward)) {
283 return EventReply::HANDLED;
285 changed = this->selectAnchor({SourceAnchorKind::TAIL, {}, {}}, SourceDirection::BACKWARD);
288 this->failure = changed.error();
290 return EventReply::HANDLED;
293 std::expected<void, TreeError> bindInput() {
294 auto prepared = prepareChrome();
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;
304 return std::unexpected(binding.error());
306 inputBinding.emplace(std::move(*binding));
310 std::expected<void, TreeError> publishPosition() {
311 if (this->positionState) {
312 auto changed = this->positionState->value.set(this->position);
314 return std::unexpected(changed.error());
320 std::expected<void, TreeError> enterEditing() {
321 if (rows.empty() || !this->position.current) {
324 const auto found = std::ranges::find(rows, *this->position.current, [](
const auto &row) {
327 if (found == rows.end()) {
328 const auto generation = portals::detail::RowTreeAccess::focusGeneration(RowAccess::app(scene).router());
330 return std::unexpected(TreeError::WOULD_BLOCK);
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};
340 for (
const auto &weak : (*found)->edit->bindings) {
341 auto binding = weak.lock();
342 if (!binding || binding->closed) {
345 const auto definition = std::ranges::find_if((*found)->edit->definitions, [&](
const auto &entry) {
346 return entry.get() == binding->definition && entry->key == *retainedField;
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;
355 this->position.editing =
true;
356 return publishPosition();
361 portals::detail::RowTreeAccess::enterRow(RowAccess::app(scene).router(), node, (*found)->root, retainedColumn);
363 return std::unexpected(entered.error());
365 this->position.editing = *entered != node;
366 return publishPosition();
369 std::expected<void, TreeError> leaveEditing() {
370 pendingEnter.reset();
371 auto observed = observeFocus();
375 for (
const auto &row : rows) {
376 if (focusedNode == node || !RowAccess::tree(scene).contains(row->root, focusedNode).value_or(
false)) {
379 for (
const auto &participant : row->participants) {
380 auto allowed = participant->beforeLeave();
385 if (row->dirty() && row->edit->options.mode == EditMode::ON_COMPLETION) {
386 return std::unexpected(TreeError::WOULD_BLOCK);
389 auto collapsed = portals::detail::RowTreeAccess::focusScope(RowAccess::app(scene).router(), node);
393 auto focused = RowAccess::app(scene).router().setFocus(node);
397 this->position.editing =
false;
398 return publishPosition();
401 std::expected<void, TreeError> selectCurrent(std::uint64_t target,
bool endPage =
false) {
402 if (!this->exactCount) {
403 return std::unexpected(TreeError::INVALID_ARGUMENT);
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) {
410 }
else if (target - nextFirst >= visible) {
411 nextFirst = natural() ? target : target - visible + 1;
413 auto allowed = requestFirst(nextFirst);
417 desiredCurrent = target;
418 lastPage = natural() && endPage;
419 desiredCellOffset = 0;
421 offsetFromEnd =
false;
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);
430 return selectCurrent(current - std::min(current, amount));
432 return selectCurrent(current + std::min(amount, std::numeric_limits<std::uint64_t>::max() - current));
435 std::expected<void, TreeError> selectAnchor(SourceAnchor anchor, SourceDirection direction) {
436 auto admitted = this->requestAnchor(anchor, direction);
440 this->currentSlot = direction == SourceDirection::BACKWARD ? options.maxRows - 1 : 0;
445 std::expected<void, TreeError> syncScrollBar() {
446 if (!scrollController) {
449 auto snapshot = scrollController->snapshot();
451 return std::unexpected(snapshot.error());
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);
460 scrollRevision = snapshot->revision;
463 if (scrollRevision && snapshot->revision != scrollRevision && this->exactCount &&
464 snapshot->vertical.offset.raster != desiredFirst) {
465 auto admitted = requestFirst(snapshot->vertical.offset.raster);
469 auto restored =
setScrollOffset(RowAccess::tree(scene), this->scrollbar, ScrollAxis::VERTICAL, {first});
471 auto current = scrollController->snapshot();
473 scrollRevision = current->revision;
479 scrollRevision = snapshot->revision;
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;
503 next.current.reset();
504 next.currentIndex.reset();
506 recordHasBefore = first > 0;
507 recordHasAfter = first + rows.size() < *this->exactCount;
508 next.hasBefore = recordHasBefore || firstCellOffset > 0;
510 recordHasAfter || (!placements.empty() &&
511 static_cast<std::int64_t
>(placements.back().y) + placements.back().height > viewport.height);
513 next.currentIndex.reset();
515 this->currentSlot = 0;
516 next.current = restoredCurrent;
517 restoredCurrent.reset();
519 const auto found = next.current ? std::ranges::find(rows, *next.current,
520 [](
const auto &row) {
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();
539 this->position = next;
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();
548 return std::unexpected(EditAccess::cause(navigation.error()));
550 auto channel = navigation->current();
552 return std::unexpected(channel.error());
554 auto current = channel->snapshot();
556 return std::unexpected(current.error());
558 if ((*current)->value.resource != resource) {
559 return std::unexpected(TreeError::WOULD_BLOCK);
561 if (observedCurrent && *observedCurrent != (*current)->value && (*current)->value.row != row) {
562 return std::unexpected(TreeError::WOULD_BLOCK);
564 if ((*current)->value.row == row) {
565 observedCurrent = (*current)->value;
568 auto moved = row ? navigation->navigate(*row) : navigation->clearCurrent();
572 auto accepted = channel ? channel->snapshot()
573 : std::expected<std::shared_ptr<const PropertyChange<NavigationPosition>>,
TreeError>(
574 std::unexpected(channel.error()));
576 return std::unexpected(accepted.error());
578 if ((*accepted)->value.resource == resource && (*accepted)->value.row == row) {
579 observedCurrent = (*accepted)->value;
589 std::expected<void, TreeError> publishScrollBar() {
590 if (scrollController && this->exactCount) {
591 if (natural() && *this->exactCount == 1 && placements.size() == 1) {
593 RowAccess::tree(scene), this->scrollbar,
594 {
static_cast<std::uint64_t
>(placements.front().height),
static_cast<std::uint64_t
>(viewport.height)});
598 auto moved =
setScrollOffset(RowAccess::tree(scene), this->scrollbar, ScrollAxis::VERTICAL,
599 {
static_cast<std::uint64_t
>(firstCellOffset)});
603 auto snapshot = scrollController->snapshot();
605 return std::unexpected(snapshot.error());
607 scrollRevision = snapshot->revision;
611 {*this->exactCount,
static_cast<std::uint64_t
>(rows.size())});
615 auto offset =
setScrollOffset(RowAccess::tree(scene), this->scrollbar, ScrollAxis::VERTICAL, {first});
619 auto snapshot = scrollController->snapshot();
621 return std::unexpected(snapshot.error());
623 scrollRevision = snapshot->revision;
628 std::expected<void, TreeError> publishOrientation(ModelResource resource,
bool announce =
true) {
629 updateOrientation(resource);
633 auto bar = publishScrollBar();
634 return bar ? publishPosition() : bar;
637 bool active() const noexcept
override {
638 if (retiredHost || lifetime.expired()) {
641 return RowAccess::tree(scene)
643 [](
const UiScope &) {
648 virtual bool acceptedResource(ModelResource resource) {
652 auto actual = currentSource();
653 return actual && (*actual)->navigationResource == resource;
656 void cancel() noexcept
override {
660 void retire() noexcept
override {
663 finiteRequest->cancel();
665 if (finiteConsumer) {
666 (void)finiteConsumer->close();
668 pendingViewport.reset();
669 for (
auto &row : rows) {
677 bool natural() const noexcept {
678 return desiredAutoHeight.value_or(options.autoRowHeight);
681 std::expected<void, TreeError> autoHeight(
bool enabled)
override {
683 return std::unexpected(TreeError::CLOSED);
685 if (natural() == enabled) {
688 if (!enabled && std::ranges::any_of(placements, [&](
const auto &value) {
689 return value.height > options.rowHeight;
691 return std::unexpected(TreeError::INVALID_GEOMETRY);
693 auto invalidated = RowAccess::tree(scene).invalidate(node, Invalidation::LAYOUT);
697 desiredAutoHeight = enabled;
698 desiredCellOffset = 0;
700 offsetFromEnd =
false;
703 blockedAttempt =
false;
707 std::size_t rowDemand() const noexcept {
708 if (viewport.width <= 0 || viewport.height <= 0) {
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));
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));
721 std::expected<void, TreeError> refreshNaturalLayout() {
722 if (!natural() || dirty || rows.empty() || !rowDemand()) {
725 auto styled = RowAccess::flushStyles(scene);
729 auto geometry = portals::detail::RowTreeAccess::geometryRevision(RowAccess::tree(scene));
731 return std::unexpected(geometry.error());
733 if (*geometry == measuredGeometryRevision) {
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});
741 return std::unexpected(size.error());
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);
754 measuredGeometryRevision = *geometry;
758 std::expected<void, TreeError> admitDraft(
const RowAssignment<T> *candidate) {
760 return std::unexpected(TreeError::CLOSED);
762 if (editPin && editPin.get() != candidate && editPin->dirty()) {
763 return std::unexpected(TreeError::WOULD_BLOCK);
765 for (
const auto &row : rows) {
766 if (row.get() != candidate && row->dirty()) {
767 return std::unexpected(TreeError::WOULD_BLOCK);
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();
785 if ((ordinal < target || ordinal - target >= visible) && row->dirty() &&
786 row->edit->options.mode == EditMode::ON_COMPLETION) {
787 return std::unexpected(TreeError::WOULD_BLOCK);
793 std::expected<void, TreeError> requestFirst(std::uint64_t target)
override {
795 return std::unexpected(TreeError::CLOSED);
797 const auto visible = rowDemand();
798 auto allowed = preflight(target, visible);
802 auto invalidated = RowAccess::tree(scene).invalidate(node, Invalidation::PAINT);
806 if (desiredFirst != target) {
807 desiredCellOffset = 0;
808 offsetFromEnd =
false;
810 desiredFirst = target;
812 allowEndBackfill =
true;
818 virtual bool rowMovePending() const noexcept {
819 return desiredFirst != first;
822 std::expected<void, TreeError> requestCells(std::int64_t delta) {
824 return std::unexpected(TreeError::CLOSED);
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);
831 auto invalidated = RowAccess::tree(scene).invalidate(node, Invalidation::LAYOUT);
835 pendingCells += delta;
836 allowEndBackfill =
true;
838 blockedAttempt =
false;
843 std::expected<void, TreeError> applyCellIntent() {
844 if (!natural() || !pendingCells || rows.empty() || rowMovePending() || awaitingCellMove || lastPage) {
847 auto remaining = pendingCells;
848 auto offset =
static_cast<std::int64_t
>(desiredCellOffset);
849 std::int64_t movement{};
852 const auto consumed = std::min(-remaining, offset);
854 remaining += consumed;
855 if (remaining && recordHasBefore) {
860 }
else if (remaining) {
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));
869 while (remaining && index < placements.size()) {
870 const auto available =
static_cast<std::int64_t
>(placements[index].height) - offset;
871 if (remaining < available) {
876 if (index + 1 == placements.size() && !recordHasAfter) {
877 offset = placements[index].height - 1;
881 remaining -= available;
888 auto moved = requestMove(movement);
892 awaitingCellMove = rowMovePending();
894 pendingCells = remaining;
895 desiredCellOffset =
static_cast<std::int32_t
>(offset);
896 offsetFromEnd = fromEnd;
901 std::expected<void, TreeError> requestWheel(
double magnitude,
bool backwards) {
902 if (!std::isfinite(magnitude) || magnitude <= 0) {
903 return std::unexpected(TreeError::INVALID_ARGUMENT);
905 const auto accumulated = wheelFraction + (backwards ? -magnitude : magnitude);
906 if (!std::isfinite(accumulated) || std::abs(accumulated) >= 0x1p63) {
907 return std::unexpected(TreeError::INVALID_ARGUMENT);
909 const auto whole = std::trunc(accumulated);
911 wheelFraction = accumulated;
915 natural() ? requestCells(
static_cast<std::int64_t
>(whole)) : requestMove(static_cast<std::int64_t>(whole));
917 wheelFraction = accumulated - whole;
922 std::expected<void, TreeError> requestMove(std::int64_t delta)
override {
924 const auto amount =
static_cast<std::uint64_t
>(-(delta + 1)) + 1;
925 return requestFirst(desiredFirst - std::min(desiredFirst, amount));
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);
931 return requestFirst(desiredFirst + amount);
934 std::expected<void, TreeError> requestPage(
bool backwards)
override {
936 return requestCells(backwards ? -viewport.height : viewport.height);
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);
942 return requestFirst(backwards ? desiredFirst - std::min(desiredFirst, step) : desiredFirst + step);
945 void prepared() noexcept
override {
949 void layoutCompleted() noexcept
override {
950 if (dirty && active()) {
955 void layoutPrepared(
const LayoutSnapshot &layout)
noexcept override {
956 if (natural() && this->position.editing && !rowMovePending() && !pendingCells && !rows.empty()) {
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
972 if (delta && bounds.size().height <= host.size().height) {
973 auto admitted = requestCells(delta);
975 failure = admitted.error();
980 }
catch (
const std::bad_alloc &) {
981 failure = TreeError::NO_MEMORY;
983 failure = TreeError::CALLBACK_FAILED;
986 auto next = layout.viewport(node);
987 if (next && *next != viewport) {
991 (void)RowAccess::tree(scene).invalidate(node, Invalidation::LAYOUT);
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();
1000 return std::unexpected(EditAccess::cause(handle.error()));
1002 auto record = EditAccess::context(*handle);
1004 return std::unexpected(record.error());
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)
1010 return RowAccess::source(initialModel);
1014 void dispose(
const std::shared_ptr<RowAssignment<T>> &row)
noexcept {
1016 if (!lifetime.expired()) {
1017 (void)scene.remove(row->root);
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>>();
1028 return std::unexpected(EditAccess::cause(root.error()));
1033 RowsController &host;
1034 std::shared_ptr<RowAssignment<T>> row;
1042 } rollback{*
this, row};
1045 row->value = value.value;
1046 row->valueRevision = row->snapshotRevision = value.valueRevision;
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);
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);
1071 auto sequence = EditAccess::sequence(target->model);
1072 if (!sequence || !sequence->current) {
1073 return std::unexpected(TreeError::INVALID_ARGUMENT);
1075 auto lookup = sequence->current->locateRow(target->id);
1076 if (lookup.state != RowLookupState::FOUND) {
1077 return std::unexpected(TreeError::STALE_NODE);
1079 auto removed = target->model.erase(lookup.index);
1080 return removed ? std::expected<void, TreeError>{} : std::unexpected(EditAccess::cause(removed.error()));
1082 auto hidden = RowAccess::tree(scene).setVisible(row->root,
false);
1085 return std::unexpected(hidden.error());
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);
1095 return std::unexpected(EditAccess::cause(mounted.error()));
1097 auto supported = RowAccess::validateEditors(scene, row->root, row->edit->bindings, !row->participants.empty());
1100 return std::unexpected(supported.error());
1102 if (!active() || !row->origin->check()) {
1104 return std::unexpected(TreeError::CLOSED);
1106 rollback.committed =
true;
1114 std::expected<void, TreeError> observeFocus() {
1115 if (editPin && !editPin->dirty()) {
1117 blockedAttempt =
false;
1119 auto focused = RowAccess::app(scene).router().focused();
1121 return std::unexpected(focused.error());
1123 if (focusedNode != *focused && deferredRefresh) {
1125 blockedAttempt =
false;
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);
1136 return std::unexpected(column.error());
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) {
1145 const auto definition = std::ranges::find_if(row->edit->definitions, [&](
const auto &entry) {
1146 return entry.get() == binding->definition && entry->key.persistent();
1148 if (definition != row->edit->definitions.end()) {
1149 retainedField = (*definition)->key;
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;
1158 auto local = portals::detail::RowTreeAccess::focusScope(RowAccess::app(scene).router(), node, row->root);
1167 auto collapsed = portals::detail::RowTreeAccess::focusScope(RowAccess::app(scene).router(), node);
1172 this->position.editing = editing;
1173 return publishPosition();
1176 std::expected<void, TreeError> ensureHistory() {
1180 auto created = portals::detail::ModelViewHistory::create(lifetime, options.checkpoints);
1182 return std::unexpected(created.error());
1184 auto role = (*created)->role();
1186 return std::unexpected(role.error());
1188 historyRole = *role;
1189 history = std::move(*created);
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>{};
1199 auto ready = ensureHistory();
1201 return std::unexpected(ready.error());
1203 portals::detail::ModelViewCheckpoint checkpoint;
1204 checkpoint.first = first;
1206 checkpoint.readingCellOffset = firstCellOffset;
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);
1214 return std::unexpected(portals::detail::navigationTreeError(bookmark.error()));
1216 checkpoint.current = *bookmark;
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);
1224 return std::unexpected(portals::detail::navigationTreeError(bookmark.error()));
1226 checkpoint.reading = *bookmark;
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());
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;
1241 desiredCellOffset = 0;
1244 allowEndBackfill =
false;
1246 }
else if (!selecting && this->position.current) {
1247 auto located = frame.locateRow(*this->position.current);
1249 return std::unexpected(located.error());
1251 if (located->state == RowLookupState::FOUND) {
1252 desiredCurrent = located->index;
1253 desiredCurrentRow = this->position.current;
1255 desiredCurrent = frame.rowCount() ? std::min(this->position.currentIndex.value_or(0), frame.rowCount() - 1) : 0;
1258 if (switched && history && !resetRestoration) {
1259 auto saved = history->find(actual, historyRole);
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);
1267 return std::unexpected(portals::detail::navigationTreeError(resolver.error()));
1269 auto restored = resolver->resolve({incarnation, frame.dataRevision(), 1, *saved->value.current}, {});
1271 return std::unexpected(portals::detail::navigationTreeError(restored.error()));
1273 if (restored->state == PositionResolution::EXACT || restored->state == PositionResolution::NEAREST) {
1274 desiredCurrent = restored->position.offset;
1275 desiredCurrentRow = restored->position.row;
1278 if (saved->value.reading) {
1279 auto resolver = FinitePositionResolver<T>::create(actual->navigationResource, incarnation, frame.snapshot(),
1280 actual->navigationChanges);
1282 return std::unexpected(portals::detail::navigationTreeError(resolver.error()));
1284 auto resolved = resolver->resolve({incarnation, frame.dataRevision(), 1, *saved->value.reading}, {});
1286 return std::unexpected(portals::detail::navigationTreeError(resolved.error()));
1288 if (resolved->state == PositionResolution::EXACT || resolved->state == PositionResolution::NEAREST) {
1289 target = resolved->position.offset;
1293 }
else if (!switched && committedIntent == intentGeneration && revision != frame.revision() && !rows.empty()) {
1294 auto anchor = frame.locateRow(rows.front()->id);
1296 return std::unexpected(anchor.error());
1298 if (anchor->state == RowLookupState::FOUND) {
1299 target = anchor->index;
1302 if constexpr (std::same_as<Source, Navigation<T>>) {
1303 auto navigation = source.managed();
1305 return std::unexpected(EditAccess::cause(navigation.error()));
1307 const auto binding = ModelAccess::bindings(source);
1308 auto observe = [&](
bool enabled,
bool reading,
1309 std::optional<NavigationPosition> &observed) -> std::expected<void, TreeError> {
1313 auto channel = reading ? navigation->readingAnchor() : navigation->current();
1315 return std::unexpected(channel.error());
1317 auto value = channel->snapshot();
1319 return std::unexpected(value.error());
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);
1327 return std::unexpected(found.error());
1329 if (!reading && found->state == RowLookupState::FOUND) {
1330 desiredCurrent = found->index;
1331 desiredCurrentRow = position.row;
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;
1341 auto current = observe(binding.current,
false, observedCurrent);
1343 return std::unexpected(current.error());
1345 auto reading = observe(binding.readingAnchor,
true, observedReading);
1347 return std::unexpected(reading.error());
1350 return frame.rowCount() ? std::min(target, frame.rowCount() - 1) : 0;
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);
1358 return std::unexpected(range.error());
1360 if (range->state() == RangeState::PENDING) {
1361 if (consumerSource.lock() != actual) {
1362 auto opened = actual->model->openRange();
1364 return std::unexpected(opened.error());
1366 finiteRequest.reset();
1367 finiteConsumer.emplace(std::move(*opened));
1368 consumerSource = actual;
1370 const bool sameRequest = finiteRequest && finiteRevision == frame.dataRevision() &&
1371 finiteRange.first == requested.first && finiteRange.count == requested.count;
1373 auto completed = frame.range(finiteConsumer->id());
1375 return std::unexpected(completed.error());
1377 range = std::move(completed);
1379 auto action = actual->preparation;
1381 return std::unexpected(TreeError::INVALID_ARGUMENT);
1383 auto work = finiteConsumer->request(requested);
1385 return std::unexpected(work.error());
1387 finiteRange = requested;
1388 finiteRevision = frame.dataRevision();
1389 finiteRequest = std::move(*work);
1390 auto sent = (*action)(frame, finiteRequest);
1392 return std::unexpected(sent.error());
1394 return std::optional<ModelRange<T>>{};
1397 if (range->state() == RangeState::PENDING) {
1398 return std::optional<ModelRange<T>>{};
1400 if (range->state() != RangeState::READY) {
1401 return std::unexpected(TreeError::CALLBACK_FAILED);
1403 return std::optional<ModelRange<T>>(std::move(*range));
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();
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;
1419 if (desiredCurrentRow) {
1424 auto point = readFiniteRange(actual, frame, {index, 1});
1426 return std::unexpected(point.error());
1431 desiredCurrentRow = (**point).rows().front().id;
1435 std::expected<void, TreeError> update() {
1436 auto scrolled = syncScrollBar();
1440 auto actual = currentSource();
1441 if (!actual || (*actual)->retired || !(*actual)->model) {
1442 return std::unexpected(actual ? TreeError::CLOSED : actual.error());
1444 auto resource = portals::detail::modelNavigationResource(**actual);
1446 return std::unexpected(resource.error());
1448 auto frame = (*actual)->model->pin();
1450 return std::unexpected(frame.error());
1452 auto focus = observeFocus();
1456 const auto count = frame->rowCount();
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))) {
1464 auto incarnation = EditAccess::sourceSession<T>(*actual);
1466 return std::unexpected(incarnation.error());
1468 auto saved = stageHistory(*actual);
1470 return std::unexpected(saved.error());
1472 auto restored = restoredFirst(*actual, *frame, *incarnation);
1474 return std::unexpected(restored.error());
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());
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()))
1485 if (visible > options.maxRows) {
1486 return std::unexpected(TreeError::NODE_LIMIT);
1488 if (!dirty && previousSource.lock() == *actual && revision == frame->revision() && target == first) {
1489 auto measured = refreshNaturalLayout();
1494 if (!dirty && previousSource.lock() == *actual && revision == frame->revision() && target == first &&
1495 desiredCurrent == this->position.currentIndex) {
1498 auto allowed = preflight(target, visible);
1503 pendingViewport.reset();
1504 return commitRows(*actual, {}, {}, frame->revision(), target, (*actual)->navigationResource, *incarnation,
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});
1513 return std::unexpected(range.error());
1518 pin = std::make_shared<ModelRange<T>>(std::move(**range));
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()});
1526 auto current = prepareFiniteCurrent(*actual, *frame, target, values);
1528 return std::unexpected(current.error());
1533 pendingViewport = pin;
1534 pendingViewportSource = *actual;
1535 pendingViewportRows = {target, visible};
1536 pendingViewportRevision = frame->dataRevision();
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);
1544 struct NaturalGeometry {
1545 std::vector<RowPlacement> placements = std::vector<RowPlacement>(0);
1546 std::size_t first{};
1547 std::int32_t offset{};
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());
1561 const auto height = std::max(1, measured->height);
1562 result.placements.push_back({row->root, 0, height});
1564 if (result.placements.empty()) {
1565 return std::expected<NaturalGeometry, TreeError>(std::in_place, result);
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;
1576 if (finalWindow && (lastPage || (allowEndBackfill && remaining < viewport.height))) {
1577 result.first = result.placements.size();
1579 while (result.first && remaining < viewport.height) {
1580 remaining += result.placements[--result.first].height;
1582 result.offset =
static_cast<std::int32_t
>(std::max<std::int64_t>(0, remaining - viewport.height));
1584 if (remaining < viewport.height && staging.size() == options.maxRows &&
1585 (!finalWindow || beforeWindow || result.first > 0)) {
1586 return std::unexpected(TreeError::NODE_LIMIT);
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);
1595 placement.y =
static_cast<std::int32_t
>(y);
1596 y += placement.height;
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);
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);
1620 std::shared_ptr<RowAssignment<T>> row;
1622 std::uint64_t revision{};
1623 std::shared_ptr<const void> next;
1624 std::shared_ptr<const void> retired;
1627 std::vector<Refresh> refresh(0);
1628 refresh.reserve(visible);
1630 auto rollback = [&] {
1631 for (
auto &row : staging) {
1632 if (std::ranges::find(rows, row) == rows.end() && row != editPin) {
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)));
1647 if (found != rows.end()) {
1649 }
else if (editPin && editPin->id == value.id && editPin->edit->fixed->source == actual &&
1650 editPin->edit->fixed->sourceSession == incarnation) {
1653 auto created = construct(actual, value.pin ? value.pin : pin, value, resource, incarnation);
1656 return std::unexpected(created.error());
1658 row = std::move(*created);
1660 if (row->value != value.value || row->valueRevision != value.valueRevision) {
1661 refresh.push_back({row, value.value, value.valueRevision, value.pin ? value.pin : pin, {}});
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));
1668 if (desiredAutoHeight && !*desiredAutoHeight && options.autoRowHeight) {
1669 auto styled = RowAccess::flushStyles(scene);
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) {
1679 return std::unexpected(measured ? TreeError::INVALID_GEOMETRY : measured.error());
1683 std::int32_t nextCellOffset{};
1684 if (natural() && !staging.empty()) {
1685 auto styled = RowAccess::flushStyles(scene);
1690 const bool reserveBar = this->scrollbar != Node<ScrollBar>{} && this->exactCount && viewport.width > 1;
1691 auto measured = measureNaturalRows(staging, leadingRows, finalWindow, reserveBar, beforeWindow);
1694 return std::unexpected(measured.error());
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]);
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;
1709 std::erase_if(refresh, [&](
const auto &value) {
1710 return std::ranges::find(staging, value.row) == staging.end();
1713 for (
const auto &row : rows) {
1714 if (std::ranges::find(staging, row) != staging.end()) {
1717 for (
const auto &participant : row->participants) {
1718 auto allowed = participant->beforeLeave();
1724 if (row->dirty() && row->edit->options.mode == EditMode::ON_COMPLETION) {
1726 return std::unexpected(TreeError::WOULD_BLOCK);
1729 std::shared_ptr<RowAssignment<T>> nextPin;
1730 if (editPin && editPin->dirty() && std::ranges::find(staging, editPin) == staging.end()) {
1733 for (
const auto &row : rows) {
1734 if (row->dirty() && std::ranges::find(staging, row) == staging.end()) {
1735 if (nextPin && nextPin != row) {
1737 return std::unexpected(TreeError::WOULD_BLOCK);
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);
1746 if (!active() || intentGeneration != stagedIntent) {
1748 return std::unexpected(TreeError::WOULD_BLOCK);
1750 auto admitted = admitCurrent(desiredCurrentRow, resource);
1755 if (!active() || intentGeneration != stagedIntent) {
1757 return std::unexpected(TreeError::WOULD_BLOCK);
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;
1767 this->position.editing =
false;
1769 if (!active() || intentGeneration != stagedIntent) {
1771 return std::unexpected(TreeError::WOULD_BLOCK);
1773 auto nextDataRevision = dataRevision;
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) {
1780 return std::unexpected(TreeError::WOULD_BLOCK);
1782 nextDataRevision = latestFrame->dataRevision();
1784 auto &tree = RowAccess::tree(scene);
1786 for (
const auto &row : rows) {
1787 auto live = tree.inspect(row->root);
1790 return std::unexpected(
live.error());
1793 for (
const auto &row : staging) {
1794 auto live = tree.inspect(row->root);
1797 return std::unexpected(
live.error());
1801 auto live = tree.inspect(editPin->root);
1804 return std::unexpected(
live.error());
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);
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;
1816 visibleNodes.push_back(this->scrollbar);
1818 if (saved && !history->valid(*saved)) {
1820 return std::unexpected(TreeError::WOULD_BLOCK);
1822 auto published = portals::detail::RowTreeAccess::publish(tree, node, visibleNodes);
1825 return std::unexpected(published.error());
1827 for (
auto &change : refresh) {
1834 placements.swap(placement);
1835 if (desiredAutoHeight) {
1836 options.autoRowHeight = *desiredAutoHeight;
1837 desiredAutoHeight.reset();
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;
1845 this->firstCellOffset = desiredCellOffset = nextCellOffset;
1846 offsetFromEnd =
false;
1847 awaitingCellMove =
false;
1851 ((actual && this->exactCount == std::optional<std::uint64_t>{0}) ||
1852 (!actual && finalWindow &&
1853 (this->sourceStatus == WindowStatus::FINAL_END || this->sourceStatus == WindowStatus::TEMPORARY_TAIL)))) {
1856 allowEndBackfill =
false;
1858 this->scrollbarVisible = showBar;
1859 editPin.swap(nextPin);
1860 first = desiredFirst = target;
1861 previousSource = actual;
1862 revision = publication;
1863 dataRevision = nextDataRevision;
1865 blockedAttempt =
false;
1866 committedIntent = intentGeneration;
1867 deferredRefresh = deferred;
1868 resetRestoration =
false;
1870 if (metadata.publish) {
1871 metadata.publish(metadata.context);
1874 history->commit(std::move(*saved));
1876 auto orientation = publishOrientation(resource,
false);
1881 for (
const auto &row : staging) {
1882 if (std::ranges::find(rows, row) == rows.end() && row != editPin) {
1886 if (nextPin && std::ranges::find(rows, nextPin) == rows.end() && nextPin != editPin) {
1892 orientation = publishOrientation(resource);
1893 if (!orientation || !active()) {
1896 if constexpr (std::same_as<Source, Navigation<T>>) {
1897 if (!rows.empty() && ModelAccess::bindings(source).readingAnchor) {
1898 auto navigation = source.managed();
1900 return std::unexpected(EditAccess::cause(navigation.error()));
1902 auto bookmark = ModelBookmark::create(
1904 {PositionKind::ITEM, rows.front()->id, target, rows.front()->valueRevision, PositionAffinity::FORWARD}, {},
1905 options.checkpoints.bookmarks);
1907 return std::unexpected(portals::detail::navigationTreeError(bookmark.error()));
1909 auto anchored = navigation->setReadingAnchor(*bookmark);
1918 for (
const auto &row : rows) {
1919 for (
const auto label : row->reactiveLabels) {
1920 auto synced = RowAccess::syncCaption(scene, label);
1922 return std::unexpected(EditAccess::cause(synced.error()));
1929 measuredGeometryRevision = portals::detail::RowTreeAccess::geometryRevision(RowAccess::tree(scene)).value_or(0);
1930 if (natural() && pendingCells && !rows.empty()) {
1932 auto invalidated = RowAccess::tree(scene).invalidate(node, Invalidation::LAYOUT);
1938 const auto requested = *std::exchange(pendingEnter, {});
1939 auto focused = RowAccess::app(scene).router().focused();
1941 return std::unexpected(focused.error());
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();
1957 void recordFailure(TreeError error)
noexcept {
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;
1965 offsetFromEnd =
false;
1966 awaitingCellMove =
false;
1967 desiredAutoHeight.reset();
1972 void service() noexcept
override {
1977 if (portals::detail::RowTreeAccess::dispatching(RowAccess::app(scene).router())) {
1981 auto result = applyCellIntent();
1986 recordFailure(result.error());
1988 }
catch (
const std::bad_alloc &) {
1989 recordFailure(TreeError::NO_MEMORY);
1991 recordFailure(TreeError::CALLBACK_FAILED);
1996inline TreeError rowSourceError(SourceError error)
noexcept {
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;
2011 return TreeError::INVALID_ARGUMENT;
2015template <
class T>
class RowWindowJob final :
public BackgroundJob {
2017 explicit RowWindowJob(WindowRequest<T> request) : request_(std::move(request)) {
2020 void run(std::stop_token stop)
noexcept override {
2022 result_ = request_.load(stop);
2023 }
catch (
const std::bad_alloc &) {
2024 result_ = std::unexpected(SourceError::NO_MEMORY);
2026 result_ = std::unexpected(SourceError::CALLBACK_FAILED);
2030 std::expected<void, AsyncError> publish()
override {
2031 auto sent = request_.complete(result_);
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);
2043 return std::unexpected(AsyncError::CALLBACK_FAILED);
2048 WindowRequest<T> request_;
2049 std::expected<SourceReadReply<T>,
SourceError> result_{std::unexpected(SourceError::WOULD_BLOCK)};
2052template <
class T,
class Factory>
struct WindowRowsController final : RowsController<T, Model<T>, Factory> {
2053 using Base = RowsController<T, Model<T>, Factory>;
2055 bool acceptedResource(ModelResource resource)
override {
2056 return this->active() && declaration.resource == resource;
2058 enum class LoadKind {
2069 bool temporaryAfter{};
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)) {
2076 ~WindowRowsController()
override {
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;
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;
2112 std::expected<void, TreeError> protocol(SourceError error) {
2113 this->sourceFailure = error;
2114 return std::unexpected(rowSourceError(error));
2117 void retire() noexcept
override {
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();
2139 SourceCursor before() const noexcept {
2140 return segmentCount ? segments[0].pin.page(0).before() : SourceCursor{};
2143 SourceCursor after() const noexcept {
2144 if (!segmentCount) {
2147 const auto &pin = segments[segmentCount - 1].pin;
2148 return pin.page(pin.pageCount() - 1).after();
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;
2158 index -= rows.size();
2164 std::expected<void, TreeError>
initialize() {
2166 auto created = WindowSource<T>::create(RowAccess::tree(this->scene), this->node, declaration.provider,
2167 declaration.options, declaration.budget);
2169 return protocol(created.error());
2171 this->sourceCapabilities = (*created)->capabilities();
2172 seenRevision = declaration.options.initialRevision;
2173 window = std::move(*created);
2176 auto opened = window->openConsumer();
2178 return protocol(opened.error());
2180 consumer.emplace(std::move(*opened));
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)) {
2191 const auto &row = this->rows[index];
2192 for (
const auto &participant : row->participants) {
2193 auto allowed = participant->beforeLeave();
2198 if (row->dirty() && row->edit->options.mode == EditMode::ON_COMPLETION) {
2199 return std::unexpected(TreeError::WOULD_BLOCK);
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));
2209 return protocol(request.error());
2211 if (!this->active()) {
2213 return std::unexpected(TreeError::CLOSED);
2217 replacementOffset = replacement;
2219 direction = traversal;
2220 this->sourceStatus = WindowStatus::LOADING;
2221 this->sourceFailure.reset();
2225 std::expected<void, TreeError> requestFirst(std::uint64_t)
override {
2226 return protocol(SourceError::UNSUPPORTED);
2229 std::expected<void, TreeError> requestMove(std::int64_t delta)
override {
2230 if (!this->active()) {
2231 return std::unexpected(TreeError::CLOSED);
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);
2241 auto target = wanted + delta;
2242 if (target < 0 && entryKnown) {
2245 if (target < 0 && !window->capabilities().backward) {
2246 return protocol(SourceError::UNSUPPORTED);
2248 if (target < offset - this->options.maxPendingRows || target > offset + this->options.maxPendingRows) {
2249 return protocol(SourceError::WOULD_BLOCK);
2251 auto allowed = beforeMove(target, loading == LoadKind::REPLACE);
2255 if (target == wanted) {
2258 auto invalidated = RowAccess::tree(this->scene).invalidate(this->node, Invalidation::PAINT);
2263 this->lastPage =
false;
2264 this->allowEndBackfill =
true;
2265 this->desiredCellOffset = 0;
2266 this->offsetFromEnd =
false;
2267 ++this->intentGeneration;
2269 this->blockedAttempt =
false;
2273 bool rowMovePending() const noexcept
override {
2274 return wanted != offset;
2277 std::expected<void, TreeError> requestPage(
bool backwards)
override {
2278 if (this->natural()) {
2279 return this->requestCells(backwards ? -this->viewport.height : this->viewport.height);
2281 const auto page =
static_cast<std::int64_t
>(std::max<std::size_t>(1, visibleRows));
2282 return requestMove(backwards ? -page : page);
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);
2291 *deferredCurrentDelta += delta;
2294 if (this->rows.empty()) {
2295 return requestMove(delta);
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) {
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);
2313 deferredCurrentDelta = std::clamp(delta, -limit, limit);
2316 return protocol(SourceError::UNSUPPORTED);
2319 const auto boundedDelta = std::clamp(delta, -limit, limit);
2320 auto target = current + boundedDelta;
2322 target = std::max(std::int64_t{}, target);
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)
2329 const auto movement = nextFirst - wanted;
2330 if (movement < 0 && !window->capabilities().backward && wanted == 0) {
2334 movement ? requestMove(movement) : RowAccess::tree(this->scene).invalidate(this->node,
Invalidation::
PAINT);
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;
2344 this->blockedAttempt =
false;
2345 ++this->intentGeneration;
2349 std::expected<void, TreeError> requestAnchor(SourceAnchor target, SourceDirection traversal)
override {
2350 if (!this->active()) {
2351 return std::unexpected(TreeError::CLOSED);
2357 auto allowed = beforeMove(0,
true);
2361 auto invalidated = RowAccess::tree(this->scene).invalidate(this->node, Invalidation::PAINT);
2365 auto requested = startLoad(target, traversal, LoadKind::REPLACE);
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;
2379 this->blockedAttempt =
false;
2383 std::expected<void, TreeError> notifyReady(std::uint64_t revision)
override {
2388 auto sent = window->notifyReady(window->stamp(), revision);
2389 return sent ? std::expected<void, TreeError>{} : protocol(sent.error());
2392 std::expected<void, TreeError> replaceModel(Model<T>, ModelRebindOptions)
override {
2393 return protocol(SourceError::UNSUPPORTED);
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>{};
2401 auto ready = this->ensureHistory();
2403 return std::unexpected(ready.error());
2405 auto bookmark = ModelBookmark::create(
2406 preparedResource, {PositionKind::ITEM, this->rows.front()->id, 0, preparedRevision, PositionAffinity::FORWARD},
2407 {}, this->options.checkpoints.bookmarks);
2409 this->sourceFailure = bookmark.error();
2410 return std::unexpected(rowSourceError(bookmark.error()));
2412 portals::detail::ModelViewCheckpoint checkpoint;
2413 checkpoint.reading = *bookmark;
2414 if (this->natural()) {
2415 checkpoint.readingCellOffset = this->firstCellOffset;
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);
2422 this->sourceFailure = current.error();
2423 return std::unexpected(rowSourceError(current.error()));
2425 checkpoint.current = *current;
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());
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);
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));
2441 auto allowed = beforeMove(0,
true);
2445 if (declaration.provider == target.provider && declaration.resource == target.resource) {
2446 return rebind.restore == ModelRestorePolicy::RESET ? requestAnchor({}, SourceDirection::FORWARD)
2449 const auto generation = this->intentGeneration;
2450 auto saved = captureHistory();
2452 return std::unexpected(saved.error());
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;
2467 auto nextDeclaration = target;
2468 if (!nextDeclaration.budget && window) {
2469 nextDeclaration.budget = window->budget();
2471 auto created = WindowSource<T>::create(RowAccess::tree(this->scene), this->node, nextDeclaration.provider,
2472 nextDeclaration.options, nextDeclaration.budget);
2474 return protocol(created.error());
2476 if (restore.kind == SourceAnchorKind::ROW && !(*created)->capabilities().seekRow) {
2477 return protocol(SourceError::UNSUPPORTED);
2479 auto opened = (*created)->openConsumer();
2481 return protocol(opened.error());
2483 if (!this->active() || this->intentGeneration != generation || (*saved && !this->history->valid(**saved))) {
2484 return std::unexpected(TreeError::WOULD_BLOCK);
2486 auto invalidated = RowAccess::tree(this->scene).invalidate(this->node, Invalidation::LAYOUT);
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();
2506 this->sourceCapabilities = window->capabilities();
2507 this->sourceStatus = WindowStatus::EMPTY;
2508 this->sourceFailure.reset();
2509 this->failure.reset();
2512 loading = LoadKind::NONE;
2514 direction = SourceDirection::FORWARD;
2515 replacementOffset = wanted = 0;
2516 entryKnown = restore.kind == SourceAnchorKind::ENTRY;
2519 seenRevision = declaration.options.initialRevision;
2520 ++this->intentGeneration;
2522 this->blockedAttempt =
false;
2524 this->history->commit(std::move(**saved));
2527 oldConsumer->close();
2533 oldWorker->cancel();
2536 }
catch (
const std::bad_alloc &) {
2537 return protocol(SourceError::NO_MEMORY);
2539 return protocol(SourceError::CALLBACK_FAILED);
2542 std::expected<void, TreeError> dispatch(WindowRequest<T> request) {
2543 auto *executor = RowAccess::app(this->scene).background();
2545 pending = std::move(request);
2546 return std::unexpected(TreeError::WOULD_BLOCK);
2549 worker = std::make_unique<BackgroundLatest>(*executor);
2551 auto admitted = worker->replace(std::make_unique<RowWindowJob<T>>(std::move(request)));
2553 return std::unexpected(admitted.error() == BackgroundError::NO_MEMORY ? TreeError::NO_MEMORY
2554 : TreeError::WOULD_BLOCK);
2559 std::expected<void, TreeError> serviceWork() {
2561 auto request = std::exchange(pending, {});
2562 auto sent = dispatch(*request);
2568 auto serviced = worker->service();
2570 return std::unexpected(serviced.error() == BackgroundError::NO_MEMORY ? TreeError::NO_MEMORY
2571 : TreeError::WOULD_BLOCK);
2574 auto continuation = consumer->takeRequest();
2575 if (!continuation) {
2576 return protocol(continuation.error());
2578 if (*continuation) {
2579 return dispatch(**continuation);
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;
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());
2599 target = {SourceAnchorKind::CURSOR, segments[segment].pin.page(0).before(), {}};
2600 local = wanted - first;
2603 auto requested = startLoad(target, SourceDirection::FORWARD, LoadKind::REPLACE, local);
2610 void integrate(WindowPin<T> pin) {
2612 if (direction == SourceDirection::FORWARD) {
2613 next.afterEnd = pin.edge() == SourceEdge::FINAL_END;
2614 next.temporaryAfter = pin.edge() == SourceEdge::TEMPORARY_TAIL;
2616 next.beforeEnd = pin.edge() == SourceEdge::FINAL_END;
2617 next.temporaryAfter = anchor.kind == SourceAnchorKind::TAIL && loading == LoadKind::REPLACE;
2619 if (loading == LoadKind::REPLACE || !segmentCount || bufferRevision != pin.dataRevision()) {
2620 segments[0] = std::move(next);
2623 segments[0].beforeEnd = segments[0].beforeEnd || entryKnown;
2624 offset = replacementOffset;
2625 if (direction == SourceDirection::BACKWARD && anchor.kind == SourceAnchorKind::TAIL) {
2627 std::max<std::int64_t>(0,
static_cast<std::int64_t
>(pin.size()) -
static_cast<std::int64_t
>(visibleRows));
2630 }
else if (!pin.size()) {
2631 if (loading == LoadKind::APPEND) {
2632 segments[segmentCount - 1].afterEnd = next.afterEnd;
2633 segments[segmentCount - 1].temporaryAfter = next.temporaryAfter;
2635 segments[0].beforeEnd = next.beforeEnd;
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]);
2646 if (segmentCount < 2) {
2647 segments[segmentCount++] = std::move(next);
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);
2656 entryKnown = segments[0].beforeEnd;
2658 bufferRevision = pin.dataRevision();
2659 lastRows = pin.page(0).rows().data();
2660 lastRevision = pin.dataRevision();
2661 loading = LoadKind::NONE;
2664 this->blockedAttempt =
false;
2667 std::expected<bool, TreeError> needDelivery() {
2668 if (loading != LoadKind::NONE) {
2671 const auto total =
static_cast<std::int64_t
>(storedRows());
2672 if (!segmentCount) {
2676 if (segments[0].beforeEnd) {
2681 startLoad({SourceAnchorKind::CURSOR, before(), {}}, SourceDirection::BACKWARD, LoadKind::PREPEND);
2682 return requested ? std::expected<bool, TreeError>(
true) : std::unexpected(requested.error());
2684 const auto &last = segments[segmentCount - 1];
2685 const bool missing = wanted >= total ||
static_cast<std::uint64_t
>(total - wanted) < visibleRows;
2689 if (last.afterEnd || last.temporaryAfter) {
2690 wanted = total ? std::min(wanted, total - 1) : 0;
2693 if (this->sourceStatus == WindowStatus::FAILED) {
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;
2701 auto requested = startLoad({SourceAnchorKind::CURSOR, after(), {}}, SourceDirection::FORWARD, LoadKind::APPEND);
2702 return requested ? std::expected<bool, TreeError>(
true) : std::unexpected(requested.error());
2705 std::expected<void, TreeError> renderBuffer() {
2706 if (wanted < 0 || wanted >
static_cast<std::int64_t
>(storedRows())) {
2709 if (!this->dirty && renderedSerial == bufferSerial && offset == wanted) {
2710 auto measured = this->refreshNaturalLayout();
2711 if (!measured || !this->dirty) {
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))) {
2722 const auto total =
static_cast<std::int64_t
>(storedRows());
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))
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();
2740 auto owner = std::make_shared<WindowPage<T>>(data);
2741 for (
const auto &row : data.rows().subspan(skip)) {
2742 if (values.size() == visibleRows) {
2745 values.push_back({row.id, &row.value, row.valueRevision, owner});
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);
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;
2767 std::size_t delivered;
2768 } metadata{*
this, declaration.provider, declaration.resource, bufferRevision, readFirst, bufferSerial, hasBefore,
2769 hasAfter, values.size()};
2771 auto committed = this->commitRows(
2772 {}, {}, values, ++publication, 0, declaration.resource, window->stamp(), {},
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);
2791 leadingRows, !hasAfter, hasBefore);
2792 if (!committed || !this->active()) {
2795 if (deferredCurrentDelta) {
2796 const auto delta = *std::exchange(deferredCurrentDelta, {});
2797 return moveCurrent(delta);
2802 std::expected<void, TreeError> updateWindow() {
2803 auto focus = this->observeFocus();
2811 const auto demand = this->rowDemand();
2812 if (demand > this->options.maxRows) {
2813 return std::unexpected(TreeError::NODE_LIMIT);
2816 if (requestedRows) {
2817 (void)consumer->cancel();
2822 loading = LoadKind::NONE;
2826 if (this->rows.empty()) {
2827 this->dirty =
false;
2830 auto allowed = beforeMove(0,
true);
2834 return this->commitRows({}, {}, {}, ++publication, 0, declaration.resource, window->stamp());
2836 visibleRows = demand;
2837 const auto windowRows = demand + std::min(this->options.overscanRows, this->options.maxRows - demand);
2838 auto revision = window->dataRevision();
2840 return protocol(revision.error());
2842 if (requestedRows != windowRows || initialLoad || *revision != seenRevision) {
2843 requestedRows = windowRows;
2844 seenRevision = *revision;
2845 auto requested = initialLoad ? startLoad(anchor, direction, LoadKind::REPLACE, wanted) : refill();
2849 initialLoad =
false;
2851 auto serviced = serviceWork();
2855 auto status = consumer->status();
2857 return protocol(status.error());
2859 this->sourceStatus = *status;
2860 auto failure = consumer->lastError();
2862 this->sourceFailure = *failure;
2864 auto recovery = consumer->recovery();
2866 this->sourceRecovery = *recovery;
2868 auto pin = consumer->pin();
2870 return protocol(pin.error());
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)) {
2879 if (*status == WindowStatus::LOADING || *status == WindowStatus::PENDING ||
2880 *status == WindowStatus::HISTORY_UNAVAILABLE) {
2883 auto delivery = needDelivery();
2885 return std::unexpected(delivery.error());
2887 return *delivery ? std::expected<void, TreeError>{} : renderBuffer();
2890 void service() noexcept
override {
2891 if (!this->active()) {
2895 if (portals::detail::RowTreeAccess::dispatching(RowAccess::app(this->scene).router())) {
2899 auto result = this->applyCellIntent();
2901 result = updateWindow();
2904 this->recordFailure(result.error());
2906 }
catch (
const std::bad_alloc &) {
2907 this->recordFailure(TreeError::NO_MEMORY);
2909 this->recordFailure(TreeError::CALLBACK_FAILED);
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 = {},
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,
2936 if (options.rowHeight <= 0 || !options.maxRows || options.maxPendingRows <= 0 ||
2937 options.maxPendingRows > std::numeric_limits<std::int32_t>::max()) {
2940 auto model = detail::ModelAccess::source(scene, source, context);
2942 return std::unexpected(model.error());
2944 auto controller = std::make_shared<detail::RowsController<T, Source, Factory>>(scene, source, std::move(factory),
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);
2951 return std::unexpected(node.error());
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);
2958 return std::unexpected(navigation.error());
2960 auto registered = controller->registerNavigation(*navigation);
2962 return std::unexpected(detail::error(*node, registered.error()));
2965 auto bound = controller->bindInput();
2967 return std::unexpected(detail::error(*node, bound.error()));
2969 auto admitted = detail::RowAccess::admit(scene, controller);
2970 return admitted ? node : std::unexpected(admitted.error());
2981template <
class T,
class Factory>
2982auto virtualRows(
WindowRowsModel<T> source, Factory factory, VirtualRowsOptions options = {},
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,
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)
2994 auto background = detail::RowAccess::background(scene);
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);
3004 return std::unexpected(node.error());
3006 controller->node = *node;
3007 detail::ModelAccess::keep(scene, *node, context);
3008 auto bound = controller->bindInput();
3010 return std::unexpected(detail::error(*node, bound.error()));
3012 auto admitted = detail::RowAccess::admit(scene, controller);
3013 return admitted ? node : std::unexpected(admitted.error());
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