Portals0.7.0 · dev (544a5c68c72e · 2026-11-28 UTC)
Loading...
Searching...
No Matches
virtual_table.hpp
1// Copyright (c) 2026 ttldtor.
2// SPDX-License-Identifier: BSL-1.0
3#pragma once
4#include <portals/data_presentation.hpp>
5
6#include <portals/virtual_list.hpp>
7#include <portals/visible_model.hpp>
8
9namespace portals {
15 std::size_t max_columns{64};
16 std::size_t max_prepared_cells{16384};
17 std::size_t max_prepared_text_bytes{1024 * 1024};
18};
19
25template <class T> struct TableColumn {
28 std::int32_t width{1};
29 std::function<GraphemeText(const T &)>
31};
32
34namespace detail {
35inline constexpr std::int32_t TABLE_HEADER_HEIGHT = 1;
36
37struct TableHeading {
38 std::int32_t x{};
39 std::int32_t width{};
41};
42
43struct TableRow {
44 std::optional<RowId> id;
45 std::vector<GraphemeText> cells = std::vector<GraphemeText>(std::initializer_list<GraphemeText>{});
46};
47
48std::expected<void, TreeError> paintTable(PaintContext &context, CellSize viewport, VirtualTableOptions options,
49 std::span<const TableHeading> headings, std::span<const TableRow> rows,
50 std::optional<RowId> selected);
51} // namespace detail
52
54
55template <class T> class VirtualTable;
72template <class T>
73std::expected<std::optional<ModelRequest<T>>, TreeError>
74prepareVirtualTable(WidgetTree &tree, Node<VirtualTable<T>> node, const ModelFrame<T> &frame, CellSize viewport);
83template <class T>
84std::expected<void, TreeError> setVirtualTableFirst(WidgetTree &tree, Node<VirtualTable<T>> node, std::uint64_t first);
93template <class T>
94std::expected<void, TreeError> setVirtualTableSelection(WidgetTree &tree, Node<VirtualTable<T>> node,
95 std::optional<RowId> selected);
105template <class T>
106std::expected<void, TreeError> setVirtualTableOptions(WidgetTree &tree, Node<VirtualTable<T>> node,
107 VirtualTableOptions options);
118template <class T>
119std::expected<void, TreeError> setVirtualTableColumns(WidgetTree &tree, Node<VirtualTable<T>> node,
120 std::span<const TableColumn<std::type_identity_t<T>>> columns);
121
129template <class T> std::expected<void, TreeError> retryVirtualTable(WidgetTree &tree, Node<VirtualTable<T>> node);
139template <class T>
140std::expected<ActionBinding, TreeError> bindVirtualTable(EventRouter &router, WidgetTree &tree,
141 Node<VirtualTable<T>> node);
142
154template <class T> class VirtualTable : public SizedWidget {
155public:
164 VirtualTable(ModelConsumer<T> consumer, std::span<const TableColumn<std::type_identity_t<T>>> columns,
166 : SizedWidget(policy), consumer_(std::move(consumer)), columns_(columns.begin(), columns.end()),
167 options_(options) {
168 }
169
170 ~VirtualTable() override {
171 request_.cancel();
172 }
173
175 std::uint64_t firstRow() const noexcept {
176 return scroll_.rasterOffset();
177 }
178
180 ScrollState scrollState() const noexcept {
181 return scroll_;
182 }
183
185 std::optional<RowId> anchorRow() const noexcept {
186 return anchor_;
187 }
188
190 std::optional<RowId> selection() const noexcept {
191 return selected_;
192 }
193
195 RowRange visibleRange() const noexcept {
196 return prepared_ ? prepared_->window.visible : RowRange{};
197 }
198
200 RowRange preparedRange() const noexcept {
201 return prepared_ ? prepared_->window.requested : RowRange{};
202 }
203
205 RangeState rangeState() const noexcept {
206 return prepared_ ? prepared_->range.state() : RangeState::PENDING;
207 }
208
215 std::expected<VisibleModelSnapshot<T>, VisibleModelReadError> visibleSnapshot(const NodeGeometry &geometry) const {
216 if (!prepared_ || dirty_ || !geometry.valid || geometry.local.size() != prepared_->viewport) {
218 }
219
220 const auto clipped = geometry.surface.intersection(geometry.clip);
221 const auto top = static_cast<std::int64_t>(geometry.surface.origin().y) + detail::TABLE_HEADER_HEIGHT;
222 const auto firstCell = std::max<std::int64_t>(top, clipped.origin().y);
223 const auto lastCell = static_cast<std::int64_t>(clipped.bottom());
224
225 if (clipped.empty() || firstCell >= lastCell || prepared_->window.visible.count == 0) {
226 return VisibleModelSnapshot<T>{prepared_->range, {}, {prepared_->window.visible.first, 0}};
227 }
228
229 const auto first = static_cast<std::size_t>((firstCell - top) / options_.row_height);
230 const auto end = std::min(prepared_->window.visible.count,
231 static_cast<std::size_t>((lastCell - top - 1) / options_.row_height + 1));
232
233 if (first >= end) {
234 return VisibleModelSnapshot<T>{prepared_->range, {}, {prepared_->window.visible.first + end, 0}};
235 }
236
237 if (prepared_->range.state() != RangeState::READY) {
238 return std::unexpected(VisibleModelReadError{prepared_->range.state() == RangeState::PENDING
241 std::string(prepared_->range.error())});
242 }
243
244 const RowRange interval{prepared_->window.visible.first + first, end - first};
245 const auto offset = static_cast<std::size_t>(interval.first - prepared_->window.requested.first);
246
247 return VisibleModelSnapshot<T>{prepared_->range, prepared_->range.rows().subspan(offset, interval.count), interval};
248 }
249
253 DataRangeStatus dataStatus() const noexcept {
254 return prepared_ ? DataRangeStatus{true, prepared_->range.state(), prepared_->frame.rowCount(),
255 prepared_->frame.dataRevision(), !request_.stopRequested()}
256 : DataRangeStatus{};
257 }
258
262 std::expected<CellSize, TreeError> measure(CellSize available) override {
263 return CellSize{std::max(0, available.width), std::max(0, available.height)};
264 }
265
269 std::expected<void, TreeError> arrange(CellRect local) override {
270 arranged_ = local.size();
271
272 return {};
273 }
274
280 std::expected<void, TreeError> paint(PaintContext &context) override {
281 if (preparedSuppressed_) {
282 auto bounds = CellRect::from({}, arranged_);
283 if (!bounds) {
284 return std::unexpected(TreeError::INVALID_GEOMETRY);
285 }
286 const auto style = computedStyle() ? computedStyle()->normal : options_.normal;
287 const std::array<RenderCommand, 1> commands{FillCommand{*bounds, *bounds, style}};
288 return context.submit(commands);
289 }
290 if (!prepared_ || dirty_) {
291 return std::unexpected(TreeError::WOULD_BLOCK);
292 }
293
294 if (arranged_ != prepared_->viewport) {
295 return std::unexpected(TreeError::INVALID_GEOMETRY);
296 }
297
298 auto options = options_;
299
300 if (const auto &style = computedStyle()) {
301 options.normal = style->normal;
302 options.selected = style->selected;
303 options.header = style->header;
304 }
305
306 return detail::paintTable(context, arranged_, options, prepared_->headings, prepared_->rows, selected_);
307 }
308
310 ComputedStyle styleDefaults() const override {
311 ComputedStyle result;
312
313 result.normal = options_.normal;
314 result.selected = options_.selected;
315 result.header = options_.header;
316
317 return result;
318 }
319
320private:
321 friend class ManagedScene;
323 template <class U>
324 friend std::expected<std::optional<ModelRequest<U>>, TreeError>
326 template <class U>
327 friend std::expected<void, TreeError> setVirtualTableFirst(WidgetTree &, Node<VirtualTable<U>>, std::uint64_t);
328 template <class U>
329 friend std::expected<void, TreeError> setVirtualTableSelection(WidgetTree &, Node<VirtualTable<U>>,
330 std::optional<RowId>);
331 template <class U>
332 friend std::expected<void, TreeError> setVirtualTableOptions(WidgetTree &, Node<VirtualTable<U>>,
334 template <class U> friend std::expected<void, TreeError> retryVirtualTable(WidgetTree &, Node<VirtualTable<U>>);
335 template <class U>
336 friend std::expected<ActionBinding, TreeError> bindVirtualTable(EventRouter &, WidgetTree &, Node<VirtualTable<U>>);
337
338 template <class U>
339 friend std::expected<void, TreeError> setVirtualTableColumns(WidgetTree &, Node<VirtualTable<U>>,
340 std::span<const TableColumn<std::type_identity_t<U>>>);
341
342 template <class U>
343 friend std::expected<void, TreeError> scrollVirtualTable(WidgetTree &, Node<VirtualTable<U>>, double);
344 template <class U>
345 friend std::expected<RowLookup, TreeError> ensureVirtualTableVisible(WidgetTree &, Node<VirtualTable<U>>,
346 const ModelFrame<U> &, RowId);
347
349
350 static std::expected<void, TreeError> validateColumns(std::span<const TableColumn<std::type_identity_t<T>>> columns,
351 VirtualTableOptions options) {
352 if (options.row_height <= 0 || options.max_columns == 0 || options.max_prepared_cells == 0 ||
353 options.max_prepared_text_bytes == 0 || columns.size() > options.max_columns ||
357 return std::unexpected(TreeError::INVALID_ARGUMENT);
358 }
359
360 std::size_t bytes{};
361
362 for (std::size_t i = 0; i < columns.size(); ++i) {
363 const auto &column = columns[i];
364
365 if (column.id.value == 0 || column.id.generation == 0 || column.width <= 0 || !column.format ||
366 column.header.policy() != options.width_policy ||
367 column.header.bytes().size() > options.max_prepared_text_bytes - bytes ||
368 std::ranges::any_of(columns.first(i), [&](const auto &prior) {
369 return prior.id == column.id;
370 })) {
371 return std::unexpected(TreeError::INVALID_ARGUMENT);
372 }
373
374 bytes += column.header.bytes().size();
375 }
376
377 return {};
378 }
379
380 struct Prepared {
381 Prepared(const ModelFrame<T> &owner, const ModelRange<T> &data, CellSize size, detail::ListWindow interval)
382 : frame(owner), range(data), viewport(size), window(interval) {
383 }
384
385 ModelFrame<T> frame;
386 ModelRange<T> range;
387 CellSize viewport;
388 detail::ListWindow window;
389 std::vector<detail::TableRow> rows = std::vector<detail::TableRow>(0);
390 std::vector<detail::TableHeading> headings =
391 std::vector<detail::TableHeading>(std::initializer_list<detail::TableHeading>{});
392 };
393
394 std::expected<std::optional<ModelRequest<T>>, TreeError> prepare(const ModelFrame<T> &frame, CellSize viewport,
395 bool &changed) {
396 auto consumer_range = frame.range(consumer_.id());
397
398 if (!consumer_range) {
399 return std::unexpected(consumer_range.error());
400 }
401
402 auto nextScroll = scroll_;
403
404 if (anchor_ && anchorRevision_ != frame.dataRevision() && !intent_) {
405 auto location = frame.locateRow(*anchor_);
406
407 if (!location) {
408 return std::unexpected(location.error());
409 }
410
411 if (location->state == RowLookupState::FOUND) {
412 (void)nextScroll.setOffset(location->index, nextScroll.fraction());
413 }
414 // Removed anchors and legacy providers retain the old ordinal, clamped below.
415 }
416
417 nextScroll.clamp(frame.rowCount());
418
419 auto valid = validateColumns(columns_, options_);
420
421 if (!valid || viewport.width < 0 || viewport.height < 0) {
422 return std::unexpected(TreeError::INVALID_ARGUMENT);
423 }
424
425 const CellSize body{columns_.empty() ? 0 : viewport.width,
426 std::max(0, viewport.height - detail::TABLE_HEADER_HEIGHT)};
427 auto window = detail::listWindow(frame.rowCount(), nextScroll.rasterOffset(), body, options_);
428
429 if (!window) {
430 return std::unexpected(window.error());
431 }
432
433 if (prepared_ && !dirty_ && !retry_ && prepared_->frame.revision() == frame.revision() &&
434 prepared_->viewport == viewport && prepared_->window.visible == window->visible &&
435 (window->requested.count == 0 || prepared_->range.state() != RangeState::PENDING ||
436 !request_.stopRequested())) {
437 return std::optional<ModelRequest<T>>{};
438 }
439
440 try {
441 auto range = consumer_range;
442 const bool waitingRetry = retryPending_ && !request_.stopRequested() && request_.range() == window->requested &&
443 request_.dataRevision() == frame.dataRevision() &&
444 (frame.revision() == retryFrameRevision_ || range->state() == RangeState::PENDING);
445 // Retain the current explicit lease independently from the provider's base-read policy.
446 const bool waitingFailedBase = waitingRetry && retryFailedBase_;
447
448 if (window->requested.count == 0) {
449 range = ModelRange<T>{};
450 } else if (!waitingFailedBase &&
451 (retry_ || range->range() != window->requested || range->state() == RangeState::PENDING)) {
452 range = frame.read(window->requested);
453 }
454
455 if (!range) {
456 return std::unexpected(range.error());
457 }
458
459 if (!retry_ && !waitingFailedBase && range->state() == RangeState::PENDING && window->requested.count != 0) {
460 auto cached = frame.readCached(*consumer_range, prepared_ ? &prepared_->range : nullptr, window->requested);
461
462 if (!cached) {
463 return std::unexpected(cached.error());
464 }
465
466 if (cached->dataRevision() != 0) {
467 range = std::move(cached);
468 }
469 }
470
471 // Stage all owning data before touching the visible state or issuing provider work.
472 // A delegate may fail halfway through: frame, row identities and text still commit together.
473 // Construct in place: MSVC Debug vector move is noexcept but may allocate an iterator proxy.
474 auto next = std::make_unique<Prepared>(frame, *range, viewport, *window);
475 auto selection = selected_;
476 const bool apply_intent = intent_ && intent_revision_ == frame.dataRevision();
477
478 std::size_t text_bytes{};
479 std::int32_t x{};
480
481 // Column validation bounds this scan independently of the logical row count.
482 // Keep geometry clipped before arithmetic; even INT32_MAX widths cannot overflow x.
483 for (const auto &column : columns_) {
484 text_bytes += column.header.bytes().size();
485
486 if (x >= viewport.width || viewport.height == 0) {
487 continue;
488 }
489
490 const auto width = std::min(column.width, viewport.width - x);
491
492 next->headings.push_back({x, width, column.header});
493 x += width;
494 }
495
496 const auto visible_columns = next->headings.size();
497
498 if (visible_columns != 0 && window->visible.count > options_.max_prepared_cells / visible_columns) {
499 return std::unexpected(TreeError::INVALID_ARGUMENT);
500 }
501
502 next->rows.reserve(window->visible.count);
503
504 for (std::size_t i = 0; i < window->visible.count; ++i) {
505 const auto index = window->visible.first + i;
506 const ModelRow<T> *row = range->state() == RangeState::READY
507 ? &range->rows()[static_cast<std::size_t>(index - window->requested.first)]
508 : nullptr;
509
510 if (row && (row->id.value == 0 || row->id.generation == 0)) {
511 return std::unexpected(TreeError::INVALID_ARGUMENT);
512 }
513
514 // Construct row vectors in place: debug vector moves can allocate bookkeeping.
515 auto &output = next->rows.emplace_back();
516
517 output.id = row ? std::optional{row->id} : std::nullopt;
518 output.cells.reserve(visible_columns);
519
520 for (std::size_t column = 0; column < visible_columns; ++column) {
521 auto text =
522 row ? columns_[column].format(row->value)
523 : *GraphemeText::from(range->state() == RangeState::FAILED ? "!" : "...", options_.width_policy);
524
525 if (text.policy() != options_.width_policy ||
526 text.bytes().size() > options_.max_prepared_text_bytes - text_bytes) {
527 return std::unexpected(TreeError::INVALID_ARGUMENT);
528 }
529
530 text_bytes += text.bytes().size();
531 output.cells.push_back(std::move(text));
532 }
533
534 if (row && apply_intent && index == *intent_) {
535 selection = row->id;
536 }
537 }
538
539 std::optional<ModelRequest<T>> dispatch;
540 const bool needs_request = window->requested.count != 0 && (retry_ || range->state() == RangeState::PENDING) &&
541 (retry_ || request_.stopRequested() || request_.range() != window->requested ||
542 request_.dataRevision() != frame.dataRevision());
543
544 // Work is requested only after every fallible formatting/allocation step succeeded.
545 // Drop our cancelled lease before requesting, so a one-slot budget can recover after caller release.
546 const bool explicitRetry = retry_;
547 if (needs_request) {
548 request_.cancel();
549 request_ = {};
550
551 auto request = consumer_.request(window->requested);
552
553 if (!request) {
554 return std::unexpected(request.error());
555 }
556
557 dispatch.emplace(*request);
558 request_ = std::move(*request);
559 } else if ((!waitingRetry && range->state() != RangeState::PENDING) || window->requested.count == 0) {
560 request_.cancel();
561 request_ = {};
562 }
563
564 // From this point the presentation commit is nonallocating. Old owners survive until all fields agree.
565 prepared_.swap(next);
566 changed = true;
567 selected_ = selection;
568 scroll_ = nextScroll;
569
570 if (!prepared_->rows.empty() && prepared_->rows.front().id) {
571 anchor_ = prepared_->rows.front().id;
572 anchorRevision_ = frame.dataRevision();
573 } else if (frame.rowCount() == 0) {
574 anchor_.reset();
575 }
576
577 retryPending_ =
578 (explicitRetry && needs_request) || (waitingRetry && window->requested.count && !request_.stopRequested());
579 if (explicitRetry && needs_request) {
580 retryFrameRevision_ = frame.revision();
581 retryFailedBase_ = range->state() == RangeState::FAILED;
582 }
583 dirty_ = false;
584 retry_ = false;
585
586 if (intent_ && (!apply_intent || range->state() == RangeState::READY)) {
587 intent_.reset();
588 }
589
590 return dispatch;
591 } catch (const std::bad_alloc &) {
592 return std::unexpected(TreeError::NO_MEMORY);
593 } catch (const std::length_error &) {
594 return std::unexpected(TreeError::INVALID_ARGUMENT);
595 } catch (...) {
596 return std::unexpected(TreeError::CALLBACK_FAILED);
597 }
598 }
599
600 void choose(std::uint64_t position) {
601 // Intent is positional only within one data revision. Publication/reorder never rewrites a stable ID.
602 const auto count = prepared_->window.visible.count;
603
604 intent_ = position;
605 intent_revision_ = prepared_->frame.dataRevision();
606
607 (void)scroll_.ensureVisible(position, count, prepared_->frame.rowCount());
608 anchor_.reset();
609 dirty_ = true;
610 }
611
612 std::expected<bool, TreeError> scrollBy(double rows) {
613 if (!prepared_) {
614 return std::unexpected(TreeError::WOULD_BLOCK);
615 }
616
617 auto changed = scroll_.moveBy(rows, prepared_->frame.rowCount());
618
619 if (changed && *changed) {
620 anchor_.reset();
621 dirty_ = true;
622 intent_.reset();
623 request_.cancel();
624 }
625
626 return changed;
627 }
628
629 std::expected<RowLookup, TreeError> ensureVisible(const ModelFrame<T> &frame, RowId id) {
630 auto range = frame.range(consumer_.id());
631
632 if (!range) {
633 return std::unexpected(range.error());
634 }
635
636 if (!prepared_) {
637 return std::unexpected(TreeError::WOULD_BLOCK);
638 }
639
640 auto location = frame.locateRow(id);
641
642 if (!location) {
643 return std::unexpected(location.error());
644 }
645
646 if (location->state != RowLookupState::FOUND) {
647 return *location;
648 }
649
650 const auto height = std::max(0, prepared_->viewport.height - detail::TABLE_HEADER_HEIGHT);
651 const auto capacity = static_cast<std::uint64_t>(height == 0 ? 0 : std::max(1, height / options_.row_height));
652
653 (void)scroll_.ensureVisible(location->index, capacity, frame.rowCount());
654 anchor_.reset();
655 dirty_ = true;
656 intent_.reset();
657 request_.cancel();
658
659 return *location;
660 }
661
662 EventReply action(Action action) {
663 if (!prepared_ || prepared_->frame.rowCount() == 0) {
664 return EventReply::IGNORED;
665 }
666
667 auto position = intent_.value_or(scroll_.rasterOffset());
668 bool located = intent_.has_value();
669
670 // Locate identities only in bounded visible delegates; global index lookup belongs to the provider.
671 if (!located && selected_) {
672 for (std::size_t i = 0; i < prepared_->rows.size(); ++i) {
673 if (prepared_->rows[i].id == selected_) {
674 position = prepared_->window.visible.first + i;
675 located = true;
676
677 break;
678 }
679 }
680 }
681
682 const auto last = prepared_->frame.rowCount() - 1;
683
684 position = std::min(position, last);
685
686 switch (action) {
687 case Action::MOVE_UP:
688 position -= located && position > 0 ? 1 : 0;
689
690 break;
692 position += located && position < last ? 1 : 0;
693
694 break;
696 position = 0;
697
698 break;
699 case Action::MOVE_END:
700 position = last;
701
702 break;
703 default:
704 return EventReply::IGNORED;
705 }
706
707 choose(position);
708
709 return EventReply::HANDLED;
710 }
711
712 ModelConsumer<T> consumer_;
713 std::vector<TableColumn<T>> columns_;
714 VirtualTableOptions options_;
715 std::unique_ptr<Prepared> prepared_;
716 ModelRequest<T> request_;
717 std::optional<RowId> selected_;
718 std::optional<std::uint64_t> intent_;
719 std::uint64_t intent_revision_{};
720 ScrollState scroll_;
721 std::optional<RowId> anchor_;
722 std::uint64_t anchorRevision_{};
723 CellSize arranged_;
724 bool dirty_{true};
725 bool preparedSuppressed_{};
726 bool retry_{};
727 bool retryPending_{};
728 bool retryFailedBase_{};
729 std::uint64_t retryFrameRevision_{};
730};
731
732template <class T>
733std::expected<std::optional<ModelRequest<T>>, TreeError>
735 std::expected<std::optional<ModelRequest<T>>, TreeError> result;
736 bool changed{};
737 auto shown = detail::listShown(tree, node);
738
739 if (!shown) {
740 return std::unexpected(shown.error());
741 }
742
743 auto edited = tree.edit(node, [&](VirtualTable<T> &view) {
744 if (!*shown) {
745 view.request_.cancel();
746 view.request_ = {};
747 view.prepared_.reset();
748 view.dirty_ = true;
749 view.intent_.reset();
750
751 return;
752 }
753
754 result = view.prepare(frame, viewport, changed);
755 });
756
757 if (!edited) {
758 return std::unexpected(edited.error());
759 }
760
761 if (result && changed) {
762 auto invalidated = tree.invalidate(node, Invalidation::PAINT);
763
764 if (!invalidated) {
765 return std::unexpected(invalidated.error());
766 }
767 }
768
769 return result;
770}
771
772template <class T>
773std::expected<void, TreeError> setVirtualTableFirst(WidgetTree &tree, Node<VirtualTable<T>> node, std::uint64_t first) {
774 auto edited = tree.edit(node, [&](VirtualTable<T> &view) {
775 if (view.scroll_.rasterOffset() != first || view.scroll_.fraction() != 0 || view.anchor_) {
776 (void)view.scroll_.setOffset(first);
777 view.anchor_.reset();
778 view.dirty_ = true;
779 view.intent_.reset();
780 view.request_.cancel();
781 }
782 });
783
784 return edited ? tree.invalidate(node, Invalidation::PAINT) : edited;
785}
786
787template <class T>
788std::expected<void, TreeError> setVirtualTableSelection(WidgetTree &tree, Node<VirtualTable<T>> node,
789 std::optional<RowId> selected) {
790 if (selected && (selected->value == 0 || selected->generation == 0)) {
791 return std::unexpected(TreeError::INVALID_ARGUMENT);
792 }
793
794 auto edited = tree.edit(node, [&](VirtualTable<T> &view) {
795 view.selected_ = selected;
796 view.intent_.reset();
797 });
798
799 return edited ? tree.invalidate(node, Invalidation::PAINT) : edited;
800}
801
802template <class T>
803std::expected<void, TreeError> setVirtualTableOptions(WidgetTree &tree, Node<VirtualTable<T>> node,
804 VirtualTableOptions options) {
805 std::expected<void, TreeError> result;
806 auto edited = tree.edit(node, [&](VirtualTable<T> &view) {
807 result = view.validateColumns(view.columns_, options);
808
809 if (!result) {
810 return;
811 }
812
813 view.options_ = options;
814 view.dirty_ = true;
815 view.request_.cancel();
816 });
817
818 if (!edited || !result) {
819 return edited ? result : edited;
820 }
821
822 return tree.invalidate(node, Invalidation::LAYOUT);
823}
824
825template <class T>
826std::expected<void, TreeError> setVirtualTableColumns(WidgetTree &tree, Node<VirtualTable<T>> node,
827 std::span<const TableColumn<std::type_identity_t<T>>> columns) {
828 std::expected<void, TreeError> result;
829 auto edited = tree.edit(node, [&](VirtualTable<T> &view) {
830 result = view.validateColumns(columns, view.options_);
831
832 if (!result) {
833 return;
834 }
835
836 try {
837 std::vector<TableColumn<T>> next(columns.begin(), columns.end());
838
839 view.columns_.swap(next);
840 } catch (const std::bad_alloc &) {
841 result = std::unexpected(TreeError::NO_MEMORY);
842
843 return;
844 } catch (...) {
845 result = std::unexpected(TreeError::CALLBACK_FAILED);
846
847 return;
848 }
849 view.dirty_ = true;
850 view.request_.cancel();
851 });
852
853 if (!edited || !result) {
854 return edited ? result : edited;
855 }
856
857 return tree.invalidate(node, Invalidation::LAYOUT);
858}
859
860template <class T> std::expected<void, TreeError> retryVirtualTable(WidgetTree &tree, Node<VirtualTable<T>> node) {
861 auto edited = tree.edit(node, [&](VirtualTable<T> &view) {
862 view.retry_ = true;
863 view.request_.cancel();
864 });
865
866 return edited ? tree.invalidate(node, Invalidation::PAINT) : edited;
867}
868
869template <class T>
870std::expected<ActionBinding, TreeError> bindVirtualTable(EventRouter &router, WidgetTree &tree,
871 Node<VirtualTable<T>> node) {
872 return router.bind(node, [&tree, node](VirtualTable<T> &view, const RoutedEvent &event) {
874
875 if (const auto *action = std::get_if<ActionEvent>(&event)) {
876 reply = view.action(action->action);
877 } else if (const auto *mouse = std::get_if<MouseInputEvent>(&event); mouse && view.prepared_) {
878 auto snapshot = tree.inspect(node);
879
880 if (!snapshot || !snapshot->geometry.valid || !snapshot->geometry.clip.contains({mouse->column, mouse->row})) {
881 return EventReply::IGNORED;
882 }
883
884 if (mouse->action == MouseAction::PRESS && mouse->button == MouseButton::LEFT && !view.dirty_) {
885 // Router coordinates are surface cells; translate using the current arranged and clipped geometry.
886 const auto y =
887 static_cast<std::int64_t>(mouse->row) - snapshot->geometry.surface.origin().y - detail::TABLE_HEADER_HEIGHT;
888
889 if (y < 0) {
890 return EventReply::IGNORED;
891 }
892
893 const auto offset = static_cast<std::uint64_t>(y / view.options_.row_height);
894
895 if (offset < view.prepared_->window.visible.count) {
896 view.choose(view.prepared_->window.visible.first + offset);
897 reply = EventReply::HANDLED;
898 }
899 } else if (mouse->action == MouseAction::SCROLL &&
900 (mouse->button == MouseButton::WHEEL_UP || mouse->button == MouseButton::WHEEL_DOWN)) {
901 const auto count = view.prepared_->frame.rowCount();
902
903 const double movement = mouse->button == MouseButton::WHEEL_UP ? -1.0 : 1.0;
904
905 (void)view.scroll_.moveBy(movement, count);
906 view.anchor_.reset();
907 view.dirty_ = true;
908 view.intent_.reset();
909 view.request_.cancel();
910 reply = EventReply::HANDLED;
911 }
912 }
913
914 if (reply == EventReply::HANDLED) {
915 (void)tree.invalidate(node, Invalidation::PAINT);
916 }
917
918 return reply;
919 });
920}
921
930template <class T>
931std::expected<void, TreeError> scrollVirtualTable(WidgetTree &tree, Node<VirtualTable<T>> node, double rows) {
932 std::expected<bool, TreeError> result;
933 auto edited = tree.edit(node, [&](VirtualTable<T> &view) {
934 result = view.scrollBy(rows);
935 });
936
937 if (!edited) {
938 return edited;
939 }
940
941 if (!result) {
942 return std::unexpected(result.error());
943 }
944
945 return *result ? tree.invalidate(node, Invalidation::PAINT) : std::expected<void, TreeError>{};
946}
947
959template <class T>
960std::expected<RowLookup, TreeError> ensureVirtualTableVisible(WidgetTree &tree, Node<VirtualTable<T>> node,
961 const ModelFrame<T> &frame, RowId id) {
962 std::expected<RowLookup, TreeError> result;
963 auto edited = tree.edit(node, [&](VirtualTable<T> &view) {
964 result = view.ensureVisible(frame, id);
965 });
966
967 if (!edited) {
968 return std::unexpected(edited.error());
969 }
970
971 if (result && result->state == RowLookupState::FOUND) {
972 auto invalidated = tree.invalidate(node, Invalidation::PAINT);
973
974 if (!invalidated) {
975 return std::unexpected(invalidated.error());
976 }
977 }
978
979 return result;
980}
981
982} // namespace portals
An owning, invariant-preserving half-open cell rectangle.
Definition geometry.hpp:81
CellSize size() const noexcept
Return the normalized cell extents by value; no errors.
static std::expected< CellRect, GeometryError > from(CellPoint origin, CellSize available) noexcept
Create a rectangle after normalizing negative available extents to zero.
UI-owned focus and synchronous bubbling over an existing WidgetTree. Tree and Scheduler must outlive ...
Definition action.hpp:169
std::expected< ActionBinding, TreeError > bind(Node< T > node, Callback &&callback, bool focusable=true)
Register one typed handler; the scoped token owns disconnect responsibility. Callback must be copy-co...
Definition action.hpp:234
Owning validated UTF-8 and immutable extended grapheme measurements.
Definition text.hpp:145
static std::expected< GraphemeText, TextError > from(std::string_view bytes, WidthPolicy policy={}, TextLimits limits={})
Validate, segment and measure a single logical UTF-8 buffer.
GraphemeText(const GraphemeText &other)=default
Copy bytes and metadata into independent storage; may allocate.
Additive lifecycle owner over one existing Application subtree. UI affine and nonmovable....
Definition managed.hpp:530
Move-only UI-owned range slot. Equal/overlapping consumers are independent. Close/destruction retires...
Definition model.hpp:698
One immutable model revision retained by the frame owner for all its views. Obtain once before Widget...
Definition model.hpp:400
Copyable typed observer; never owns or exposes an unchecked widget pointer.
Definition widget.hpp:92
Borrowed synchronous command sink supplied by the frame owner. submit must consume commands immediate...
Definition widget_types.hpp:66
virtual std::expected< void, TreeError > submit(std::span< const RenderCommand > commands)=0
Borrow commands.
Owning one-dimensional logical position with floor quantization to integral rows. Integral and fracti...
Definition scroll.hpp:15
std::expected< void, TreeError > setOffset(std::uint64_t row, double fraction=0) noexcept
Replace the unbounded intended position; call clamp when row count is known.
double fraction() const noexcept
std::uint64_t rasterOffset() const noexcept
std::expected< bool, TreeError > moveBy(double rows, std::uint64_t count) noexcept
Accumulate signed fractional wheel movement, saturating at the first/last row.
Widget with owning policies, changed only through setSizePolicy on UI.
Definition layout.hpp:68
SizedWidget(SizePolicy policy={})
Own the supplied policies; checked by layout.
One UI-owned table with bounded owning cell text and one independent model consumer....
Definition virtual_table.hpp:154
ComputedStyle styleDefaults() const override
Definition virtual_table.hpp:310
std::optional< RowId > selection() const noexcept
Stable identity, retained across model revisions and hidden views.
Definition virtual_table.hpp:190
RowRange preparedRange() const noexcept
Last successfully prepared viewport plus overscan.
Definition virtual_table.hpp:200
std::expected< CellSize, TreeError > measure(CellSize available) override
Viewport-sized intrinsic extent, independent of logical row count.
Definition virtual_table.hpp:262
RangeState rangeState() const noexcept
Last prepared model readiness; error text is owned by its retained model range.
Definition virtual_table.hpp:205
std::optional< RowId > anchorRow() const noexcept
Definition virtual_table.hpp:185
DataRangeStatus dataStatus() const noexcept
Definition virtual_table.hpp:253
std::expected< void, TreeError > paint(PaintContext &context) override
Emit widget-local commands; caller applies surface translation and ancestor clip.
Definition virtual_table.hpp:280
std::expected< VisibleModelSnapshot< T >, VisibleModelReadError > visibleSnapshot(const NodeGeometry &geometry) const
Capture prepared ready body rows intersecting final arranged geometry.
Definition virtual_table.hpp:215
RowRange visibleRange() const noexcept
Last successfully prepared visible rows.
Definition virtual_table.hpp:195
VirtualTable(ModelConsumer< T > consumer, std::span< const TableColumn< std::type_identity_t< T > > > columns, VirtualTableOptions options={}, SizePolicy policy=DEFAULT_VIEWPORT_POLICY)
Own consumer, columns and options; validation happens on preparation.
Definition virtual_table.hpp:164
std::expected< void, TreeError > arrange(CellRect local) override
Remember local bounds without reading/loading/formatting rows.
Definition virtual_table.hpp:269
~VirtualTable() override
Cancel work; worker ownership may outlive this view.
Definition virtual_table.hpp:170
ScrollState scrollState() const noexcept
Definition virtual_table.hpp:180
std::uint64_t firstRow() const noexcept
Integral scroll position, clamped at preparation.
Definition virtual_table.hpp:175
Copyable immutable ready values for one physically visible table interval.
Definition visible_model.hpp:31
Exclusive parent/child ownership on Scheduler's UI thread. Scheduler must outlive this object....
Definition widget.hpp:179
std::expected< void, TreeError > edit(Node< T > node, Callback &&callback)
Borrow T only during a void callback; nested edit/removal is supported. Forbidden during measure/arra...
Definition widget.hpp:310
std::expected< NodeSnapshot, TreeError > inspect(Node< Widget > node) const
Copy live structure; may allocate.
std::expected< void, TreeError > invalidate(Node< Widget > node, Invalidation kind)
Coalesce one frame request.
const std::shared_ptr< const StyleSnapshot > & computedStyle() const noexcept
Inspect the last atomically installed theme inside tree.read/frame.
Public Portals API.
Definition action.hpp:8
std::expected< void, TreeError > retryVirtualTable(WidgetTree &tree, Node< VirtualTable< T > > node)
Explicitly retry a provider error/pending range at the next preparation; no worker is started.
Definition virtual_table.hpp:860
std::expected< ActionBinding, TreeError > bindVirtualTable(EventRouter &router, WidgetTree &tree, Node< VirtualTable< T > > node)
Bind arrows/Home/End, left press and integral wheel scrolling to the existing router....
Definition virtual_table.hpp:870
ui::ValueText text(std::format_string< const ui::detail::TextArgumentValue< Args > &... > pattern, Args &&...args)
Declare live formatted text over explicit scalar roots, fields or value properties.
Definition ui_value_text.hpp:567
std::expected< void, TreeError > setVirtualTableSelection(WidgetTree &tree, Node< VirtualTable< T > > node, std::optional< RowId > selected)
Set stable selection on UI, clear pending navigation, and invalidate paint.
Definition virtual_table.hpp:788
Action
Frontend-independent commands; text and paste remain distinct data events.
Definition action.hpp:10
@ MOVE_DOWN
Move down according to the receiving widget.
Definition action.hpp:16
@ 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
@ NOT_PREPARED
No current preparation, including after scroll or configuration changes.
Definition visible_model.hpp:12
@ FAILED
The provider rejected the prepared interval.
Definition visible_model.hpp:14
@ PENDING
The provider has not supplied the prepared interval.
Definition visible_model.hpp:13
@ SCROLL
Wheel movement in the direction given by MouseInputEvent::button.
Definition input.hpp:253
@ PRESS
Mouse button press.
Definition input.hpp:250
RangeState
Observable asynchronous range readiness.
Definition model.hpp:45
@ READY
Exactly the requested immutable rows are available.
Definition model.hpp:47
@ FAILED
Provider failure is represented by snapshot-owned text and no rows.
Definition model.hpp:48
@ PENDING
Data is not ready; reading must not block or start work.
Definition model.hpp:46
std::expected< RowLookup, TreeError > ensureVirtualTableVisible(WidgetTree &tree, Node< VirtualTable< T > > node, const ModelFrame< T > &frame, RowId id)
Reveal a stable row using a caller-supplied shared pin and the last prepared viewport.
Definition virtual_table.hpp:960
EventReply
Explicit bubbling decision; ignored continues toward the original root.
Definition action.hpp:49
@ IGNORED
Continue bubbling along the original ancestry.
Definition action.hpp:50
@ HANDLED
Stop bubbling; this registration consumed the event.
Definition action.hpp:51
constexpr SizePolicy DEFAULT_VIEWPORT_POLICY
A bounded data viewport fills both axes without requesting the whole model extent.
Definition layout.hpp:53
std::expected< void, TreeError > setVirtualTableColumns(WidgetTree &tree, Node< VirtualTable< T > > node, std::span< const TableColumn< std::type_identity_t< T > > > columns)
Replace ordered column definitions transactionally and invalidate layout.
Definition virtual_table.hpp:826
std::variant< ActionEvent, KeyEvent, TextInputEvent, PasteInputEvent, MouseInputEvent > RoutedEvent
Synchronous input value; callback borrows it only until return.
Definition action.hpp:47
@ TWO
Use two cells.
Definition text.hpp:32
@ ONE
Use one cell.
Definition text.hpp:30
@ NARROW
Use one cell.
Definition text.hpp:22
@ WIDE
Use two cells.
Definition text.hpp:24
std::expected< std::optional< ModelRequest< T > >, TreeError > prepareVirtualTable(WidgetTree &tree, Node< VirtualTable< T > > node, const ModelFrame< T > &frame, const Geometry &layout)
Prepare a table using its captured local layout extent, including its header.
Definition virtual_preparation.hpp:50
@ FOUND
The index identifies this RowId in the same snapshot.
Definition model.hpp:74
std::expected< void, TreeError > scrollVirtualTable(WidgetTree &tree, Node< VirtualTable< T > > node, double rows)
Accumulate fractional wheel input on UI using the last prepared model count.
Definition virtual_table.hpp:931
std::expected< void, TreeError > setVirtualTableFirst(WidgetTree &tree, Node< VirtualTable< T > > node, std::uint64_t first)
Change the integral first row on UI and invalidate paint; prepare before painting again.
Definition virtual_table.hpp:773
std::expected< void, TreeError > setVirtualTableOptions(WidgetTree &tree, Node< VirtualTable< T > > node, VirtualTableOptions options)
Validate settings on UI, invalidate layout and require preparation before the next paint.
Definition virtual_table.hpp:803
@ WHEEL_UP
Vertical wheel movement upward.
Definition input.hpp:242
@ WHEEL_DOWN
Vertical wheel movement downward.
Definition input.hpp:243
@ LEFT
Left mouse button.
Definition input.hpp:238
@ LAYOUT
Layout and painting are required; old arranged geometry becomes invalid.
Definition widget_types.hpp:44
@ 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_GEOMETRY
Required arranged geometry is absent or translation overflowed.
Definition widget_types.hpp:38
@ CALLBACK_FAILED
A user extension or callback threw.
Definition widget_types.hpp:37
@ WOULD_BLOCK
The current frame/reentry boundary or finite queue/work budget rejects this operation.
Definition widget_types.hpp:32
@ INVALID_ARGUMENT
An option, enum value or operation argument is invalid.
Definition widget_types.hpp:27
@ NO_MEMORY
Allocation failed inside the operation boundary.
Definition widget_types.hpp:33
An owning available extent in terminal columns/rows.
Definition geometry.hpp:44
std::int32_t height
Available number of rows, possibly negative before normalization.
Definition geometry.hpp:48
std::int32_t width
Available number of columns, possibly negative before normalization.
Definition geometry.hpp:46
Small owning paint value, independent of themes and text metrics.
Definition cell_buffer.hpp:35
Provider-assigned column identity; typed row accessors define column values.
Definition model.hpp:24
Owning resolved presentation; no actions or model state are encoded.
Definition style_types.hpp:169
CellStyle normal
Ordinary text and fill.
Definition style_types.hpp:170
CellStyle header
Fixed table heading.
Definition style_types.hpp:174
CellStyle selected
Selected list/table row or editor range.
Definition style_types.hpp:173
Owning facts from the same successful virtual-view preparation, without another model read.
Definition data_presentation.hpp:29
Fill an owning half-open area with styled one-cell ASCII spaces.
Definition render.hpp:42
Owning arranged geometry; invalid geometry must never be used for hit-testing.
Definition widget_types.hpp:48
Provider-assigned row identity, independent of position; increment generation on reuse.
Definition row_id.hpp:9
Half-open logical row interval; arithmetic is checked before provider access.
Definition model.hpp:35
Owning independent policies for width and height.
Definition layout.hpp:35
A typed owning column definition; identity is independent of visual order.
Definition virtual_table.hpp:25
std::function< GraphemeText(const T &)> format
Owning typed accessor/formatter, only called for visible ready cells.
Definition virtual_table.hpp:30
ColumnId id
Nonzero unique value/generation pair within this table configuration.
Definition virtual_table.hpp:26
std::int32_t width
Positive width in cells; columns are contiguous, in vector order.
Definition virtual_table.hpp:28
GraphemeText header
Owning header text, clipped without splitting graphemes.
Definition virtual_table.hpp:27
Owning fixed-row presentation settings; invalid heights are rejected at preparation.
Definition virtual_list.hpp:18
WidthPolicy width_policy
Required policy for delegate and placeholder text.
Definition virtual_list.hpp:21
std::int32_t row_height
Positive cell rows per logical row.
Definition virtual_list.hpp:19
Owning table settings; preparation rejects invalid dimensions and exceeded budgets....
Definition virtual_table.hpp:13
std::size_t max_prepared_cells
Positive bound on visible body cells; no silent truncation.
Definition virtual_table.hpp:16
std::size_t max_prepared_text_bytes
Positive total UTF-8 byte budget for headers and visible cells.
Definition virtual_table.hpp:17
std::size_t max_columns
Positive bound on configured columns, including offscreen columns.
Definition virtual_table.hpp:15
CellStyle header
One fixed cell row of column headings, unaffected by selection.
Definition virtual_table.hpp:14
Owning preparation/provider failure, independent of the table and provider lifetime.
Definition visible_model.hpp:18
EmojiWidth emoji
Width of recognized emoji clusters.
Definition text.hpp:46
AmbiguousWidth ambiguous
Width of printable Ambiguous scalars.
Definition text.hpp:44