4#include <portals/data_presentation.hpp>
5#include <portals/detail/list_text.hpp>
7#include <portals/action.hpp>
8#include <portals/layout.hpp>
9#include <portals/model.hpp>
10#include <portals/scroll.hpp>
34std::expected<ListWindow, TreeError> listWindow(std::uint64_t count, std::uint64_t first, CellSize viewport,
35 VirtualListOptions options);
38 std::optional<RowId>
id;
39 std::optional<GraphemeText>
text;
40 std::shared_ptr<const PreparedListText> prepared;
43std::expected<void, TreeError> paintList(PaintContext &context, CellSize viewport, VirtualListOptions options,
44 std::span<const ListRow> rows, std::optional<RowId> selected);
45std::expected<bool, TreeError> listShown(WidgetTree &tree, Node<Widget> node);
67std::expected<std::optional<ModelRequest<T>>,
TreeError>
89 std::optional<RowId> selected);
144 :
SizedWidget(policy), consumer_(std::move(consumer)), delegate_(std::move(delegate)), options_(options) {
153 return scroll_.rasterOffset();
173 return prepared_ ? prepared_->window.visible :
RowRange{};
178 return prepared_ ? prepared_->window.requested :
RowRange{};
190 return prepared_ ?
DataRangeStatus{
true, prepared_->range.state(), prepared_->frame.rowCount(),
191 prepared_->frame.dataRevision(), !request_.stopRequested()}
206 arranged_ = local.
size();
217 if (preparedSuppressed_) {
224 const std::array<RenderCommand, 1> commands{
FillCommand{*bounds, *bounds, style}};
226 return context.
submit(commands);
228 if (!prepared_ || dirty_) {
232 if (arranged_ != prepared_->viewport) {
236 auto options = options_;
239 options.normal = style->normal;
240 options.selected = style->selected;
243 return detail::paintList(context, arranged_, options, prepared_->rows, selected_);
250 result.
normal = options_.normal;
251 result.
selected = options_.selected;
259 bool clearMissingSelection_{};
260 bool detachedCollection_{};
264 const ModelFrame<U> &, CellSize);
269 std::optional<RowId>);
280 const ModelFrame<U> &, RowId);
285 Prepared(
const ModelFrame<T> &owner,
const ModelRange<T> &data, CellSize size, detail::ListWindow interval)
286 : frame(owner), range(data), viewport(size), window(interval) {
292 detail::ListWindow window;
293 std::vector<detail::ListRow> rows = std::vector<detail::ListRow>(std::initializer_list<detail::ListRow>{});
296 std::expected<std::optional<ModelRequest<T>>,
TreeError> prepare(
const ModelFrame<T> &frame, CellSize viewport,
298 auto consumer_range =
299 detachedCollection_ ? std::expected<ModelRange<T>,
TreeError>(ModelRange<T>{}) : frame.range(consumer_.
id());
301 if (!consumer_range) {
302 return std::unexpected(consumer_range.error());
305 auto nextScroll = scroll_;
307 if (anchor_ && anchorRevision_ != frame.dataRevision() && !intent_) {
308 auto location = frame.locateRow(*anchor_);
311 return std::unexpected(location.error());
315 (void)nextScroll.setOffset(location->index, nextScroll.fraction());
320 nextScroll.clamp(frame.rowCount());
322 auto window = detail::listWindow(frame.rowCount(), nextScroll.rasterOffset(), viewport, options_);
324 if (!window || !delegate_) {
328 if (prepared_ && !dirty_ && !retry_ && prepared_->frame.revision() == frame.revision() &&
329 prepared_->viewport == viewport && prepared_->window.visible == window->visible &&
331 !request_.stopRequested())) {
332 return std::optional<ModelRequest<T>>{};
336 auto range = consumer_range;
337 const bool waitingRetry = retryPending_ && !request_.stopRequested() && request_.range() == window->requested &&
338 request_.dataRevision() == frame.dataRevision() &&
341 const bool waitingFailedBase = waitingRetry && retryFailedBase_;
343 if (window->requested.count == 0) {
345 }
else if (!waitingFailedBase &&
346 (retry_ || range->range() != window->requested || range->state() ==
RangeState::PENDING)) {
347 range = frame.read(window->requested);
351 return std::unexpected(range.error());
354 if (!retry_ && !waitingFailedBase && range->state() ==
RangeState::PENDING && window->requested.count != 0) {
355 auto cached = frame.readCached(*consumer_range, prepared_ ? &prepared_->range :
nullptr, window->requested);
358 return std::unexpected(cached.error());
361 if (cached->dataRevision() != 0) {
362 range = std::move(cached);
369 auto next = std::make_unique<Prepared>(frame, *range, viewport, *window);
370 auto selection = selected_;
371 if (clearMissingSelection_ && selection) {
372 auto found = frame.locateRow(*selection);
374 return std::unexpected(found.error());
380 const bool apply_intent = intent_ && intent_revision_ == frame.dataRevision();
382 next->rows.reserve(window->visible.count);
384 for (std::size_t i = 0; i < window->visible.count; ++i) {
385 const auto index = window->visible.first + i;
388 const auto &row = range->rows()[
static_cast<std::size_t
>(index - window->requested.first)];
389 if (row.id.value == 0 || row.id.generation == 0) {
392 if (preparedDelegate_) {
393 auto text = preparedDelegate_(row);
395 if (!
text ||
text->text.policy() != options_.width_policy) {
398 next->rows.push_back({row.id, {}, std::move(
text)});
400 auto text = delegate_(row);
402 if (
text.policy() != options_.width_policy) {
405 next->rows.push_back({row.id, std::move(
text), {}});
408 if (apply_intent && index == *intent_) {
418 next->rows.push_back({{}, std::move(*
text)});
422 std::optional<ModelRequest<T>> dispatch;
424 const bool needs_request = !detachedCollection_ && window->requested.count != 0 &&
426 (retry_ || request_.stopRequested() || request_.range() != window->requested ||
427 request_.dataRevision() != frame.dataRevision());
431 const bool explicitRetry = retry_;
436 auto request = consumer_.request(window->requested);
439 return std::unexpected(request.error());
442 dispatch.emplace(*request);
443 request_ = std::move(*request);
444 }
else if ((!waitingRetry && range->state() !=
RangeState::PENDING) || window->requested.count == 0) {
450 prepared_.swap(next);
452 selected_ = selection;
453 scroll_ = nextScroll;
455 if (!prepared_->rows.empty() && prepared_->rows.front().id) {
456 anchor_ = prepared_->rows.front().id;
457 anchorRevision_ = frame.dataRevision();
458 }
else if (frame.rowCount() == 0) {
463 (explicitRetry && needs_request) || (waitingRetry && window->requested.count && !request_.stopRequested());
464 if (explicitRetry && needs_request) {
465 retryFrameRevision_ = frame.revision();
476 }
catch (
const std::bad_alloc &) {
478 }
catch (
const std::length_error &) {
485 void choose(std::uint64_t position) {
487 const auto count = prepared_->window.visible.count;
490 intent_revision_ = prepared_->frame.dataRevision();
492 (void)scroll_.ensureVisible(position, count, prepared_->frame.rowCount());
497 std::expected<bool, TreeError> scrollBy(
double rows) {
499 return std::unexpected(TreeError::WOULD_BLOCK);
502 auto changed = scroll_.moveBy(rows, prepared_->frame.rowCount());
504 if (changed && *changed) {
514 std::expected<RowLookup, TreeError> ensureVisible(
const ModelFrame<T> &frame, RowId
id) {
516 detachedCollection_ ? std::expected<ModelRange<T>,
TreeError>(ModelRange<T>{}) : frame.range(consumer_.
id());
519 return std::unexpected(range.error());
523 return std::unexpected(TreeError::WOULD_BLOCK);
526 auto location = frame.locateRow(
id);
529 return std::unexpected(location.error());
532 if (location->state != RowLookupState::FOUND) {
536 const auto height = prepared_->viewport.height;
537 const auto capacity =
static_cast<std::uint64_t
>(height == 0 ? 0 : std::max(1, height / options_.row_height));
539 (
void)scroll_.ensureVisible(location->index, capacity, frame.rowCount());
549 if (!prepared_ || prepared_->frame.rowCount() == 0) {
550 return EventReply::IGNORED;
553 auto position = intent_.value_or(scroll_.rasterOffset());
554 bool located = intent_.has_value();
557 if (!located && selected_) {
558 for (std::size_t i = 0; i < prepared_->rows.size(); ++i) {
559 if (prepared_->rows[i].id == selected_) {
560 position = prepared_->window.visible.first + i;
568 const auto last = prepared_->frame.rowCount() - 1;
570 position = std::min(position, last);
573 case Action::MOVE_UP:
574 position -= located && position > 0 ? 1 : 0;
577 case Action::MOVE_DOWN:
578 position += located && position < last ? 1 : 0;
581 case Action::MOVE_HOME:
585 case Action::MOVE_END:
590 return EventReply::IGNORED;
595 return EventReply::HANDLED;
598 ModelConsumer<T> consumer_;
599 std::function<GraphemeText(
const ModelRow<T> &)> delegate_;
600 std::function<std::shared_ptr<const detail::PreparedListText>(
const ModelRow<T> &)> preparedDelegate_;
601 std::function<void(RowId)> activation_;
602 bool clickActivates_{};
603 std::shared_ptr<void> service_;
604 bool preparedSuppressed_{};
605 VirtualListOptions options_;
606 std::unique_ptr<Prepared> prepared_;
607 ModelRequest<T> request_;
608 std::optional<RowId> selected_;
609 std::optional<std::uint64_t> intent_;
610 std::uint64_t intent_revision_{};
612 std::optional<RowId> anchor_;
613 std::uint64_t anchorRevision_{};
617 bool retryPending_{};
618 bool retryFailedBase_{};
619 std::uint64_t retryFrameRevision_{};
623std::expected<std::optional<ModelRequest<T>>,
TreeError>
625 std::expected<std::optional<ModelRequest<T>>,
TreeError> result;
627 auto shown = detail::listShown(tree, node);
630 return std::unexpected(shown.error());
635 view.request_.cancel();
637 view.prepared_.reset();
639 view.intent_.reset();
644 result = view.prepare(frame, viewport, changed);
648 return std::unexpected(edited.error());
651 if (result && changed) {
655 return std::unexpected(invalidated.error());
667 view.anchor_.reset();
669 view.intent_.reset();
670 view.request_.cancel();
679 std::optional<RowId> selected) {
680 if (selected && (selected->value == 0 || selected->generation == 0)) {
685 view.selected_ = selected;
686 view.intent_.reset();
700 view.options_ = options;
702 view.request_.cancel();
711 view.request_.cancel();
723 if (
const auto *action = std::get_if<ActionEvent>(&event)) {
724 reply = view.action(action->action);
725 if (action->action ==
Action::ACTIVATE && view.activation_ && view.selected_ && !view.preparedSuppressed_) {
726 view.activation_(*view.selected_);
729 }
else if (
const auto *mouse = std::get_if<MouseInputEvent>(&event); mouse && view.prepared_) {
730 auto snapshot = tree.
inspect(node);
732 if (!snapshot || !snapshot->geometry.valid || !snapshot->geometry.clip.contains({mouse->column, mouse->row})) {
738 const auto y =
static_cast<std::int64_t
>(mouse->row) - snapshot->geometry.surface.origin().y;
739 const auto offset =
static_cast<std::uint64_t
>(y / view.options_.
row_height);
741 if (offset < view.prepared_->window.visible.count) {
742 const auto clicked = view.prepared_->rows[
static_cast<std::size_t
>(offset)].
id;
743 view.choose(view.prepared_->window.visible.first + offset);
744 if (view.clickActivates_ && view.activation_ && clicked) {
745 view.selected_ = clicked;
746 view.activation_(*clicked);
752 const auto count = view.prepared_->frame.rowCount();
756 (void)view.scroll_.
moveBy(movement, count);
757 view.anchor_.reset();
759 view.intent_.reset();
760 view.request_.cancel();
783 std::expected<bool, TreeError> result;
785 result = view.scrollBy(rows);
793 return std::unexpected(result.error());
813 std::expected<RowLookup, TreeError> result;
815 result = view.ensureVisible(frame,
id);
819 return std::unexpected(edited.error());
826 return std::unexpected(invalidated.error());
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
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
Independent owner for borrowed rows and provider error text.
Definition model.hpp:175
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.
One UI-owned view with bounded owning row text and one independent model consumer....
Definition virtual_list.hpp:133
VirtualList(ModelConsumer< T > consumer, std::function< GraphemeText(const ModelRow< T > &)> delegate, VirtualListOptions options={}, SizePolicy policy=DEFAULT_VIEWPORT_POLICY)
Own consumer, delegate and options; validation happens on preparation.
Definition virtual_list.hpp:142
DataRangeStatus dataStatus() const noexcept
Definition virtual_list.hpp:189
std::optional< RowId > selection() const noexcept
Stable identity, retained across model revisions and hidden views.
Definition virtual_list.hpp:167
std::expected< CellSize, TreeError > measure(CellSize available) override
Viewport-sized intrinsic extent, independent of logical row count.
Definition virtual_list.hpp:198
std::uint64_t firstRow() const noexcept
Integral scroll position, clamped at preparation.
Definition virtual_list.hpp:152
std::expected< void, TreeError > paint(PaintContext &context) override
Emit widget-local commands; caller applies surface translation and ancestor clip.
Definition virtual_list.hpp:216
std::expected< void, TreeError > arrange(CellRect local) override
Remember local bounds without reading/loading/formatting rows.
Definition virtual_list.hpp:205
~VirtualList() override
Cancel work; worker ownership may outlive this view.
Definition virtual_list.hpp:147
RowRange visibleRange() const noexcept
Last successfully prepared visible rows.
Definition virtual_list.hpp:172
RowRange preparedRange() const noexcept
Last successfully prepared viewport plus overscan.
Definition virtual_list.hpp:177
ComputedStyle styleDefaults() const override
Definition virtual_list.hpp:247
std::optional< RowId > anchorRow() const noexcept
Definition virtual_list.hpp:162
RangeState rangeState() const noexcept
Last prepared model readiness; error text is owned by its retained model range.
Definition virtual_list.hpp:182
ScrollState scrollState() const noexcept
Definition virtual_list.hpp:157
consteval auto id(StyleState state=StyleState::ANY, bool readOnly=false)
Definition style_static.hpp:865
Public Portals API.
Definition action.hpp:8
std::expected< void, TreeError > setVirtualListFirst(WidgetTree &tree, Node< VirtualList< T > > node, std::uint64_t first)
Change the integral first row on UI and invalidate paint; prepare before painting again.
Definition virtual_list.hpp:663
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
@ ACTIVATE
Activate the target's primary command.
Definition action.hpp:11
std::expected< ActionBinding, TreeError > bindVirtualList(EventRouter &router, WidgetTree &tree, Node< VirtualList< T > > node)
Bind arrows/Home/End, left press and integral wheel scrolling to the existing router....
Definition virtual_list.hpp:718
std::expected< void, TreeError > retryVirtualList(WidgetTree &tree, Node< VirtualList< T > > node)
Explicitly retry a provider error/pending range at the next preparation; no worker is started.
Definition virtual_list.hpp:708
std::expected< RowLookup, TreeError > ensureVirtualListVisible(WidgetTree &tree, Node< VirtualList< 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_list.hpp:811
@ 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< void, TreeError > scrollVirtualList(WidgetTree &tree, Node< VirtualList< T > > node, double rows)
Accumulate fractional wheel input on UI using the last prepared model count.
Definition virtual_list.hpp:782
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
std::expected< std::optional< ModelRequest< T > >, TreeError > prepareVirtualList(WidgetTree &tree, Node< VirtualList< T > > node, const ModelFrame< T > &frame, CellSize viewport)
Prepare a local final viewport between frames, using the same pin as every sibling view....
Definition virtual_list.hpp:624
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 > setVirtualListOptions(WidgetTree &tree, Node< VirtualList< T > > node, VirtualListOptions options)
Validate settings on UI, invalidate layout and require preparation before the next paint.
Definition virtual_list.hpp:693
std::variant< ActionEvent, KeyEvent, TextInputEvent, PasteInputEvent, MouseInputEvent > RoutedEvent
Synchronous input value; callback borrows it only until return.
Definition action.hpp:47
std::expected< void, TreeError > setVirtualListSelection(WidgetTree &tree, Node< VirtualList< T > > node, std::optional< RowId > selected)
Set stable selection on UI, clear pending navigation, and invalidate paint.
Definition virtual_list.hpp:678
@ FOUND
The index identifies this RowId in the same snapshot.
Definition model.hpp:74
@ NOT_FOUND
Provider supports lookup, but this full RowId is absent.
Definition model.hpp:73
@ 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
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 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
A typed domain row and its stable identity; a table uses a typed record as T.
Definition model.hpp:55
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
Owning fixed-row presentation settings; invalid heights are rejected at preparation.
Definition virtual_list.hpp:18
CellStyle highlight
Prepared match emphasis over normal/selected appearance.
Definition virtual_list.hpp:24
WidthPolicy width_policy
Required policy for delegate and placeholder text.
Definition virtual_list.hpp:21
CellStyle selected
Selected row fill and text.
Definition virtual_list.hpp:23
std::size_t overscan_rows
Extra requested rows on each side, never formatted while invisible.
Definition virtual_list.hpp:20
std::int32_t row_height
Positive cell rows per logical row.
Definition virtual_list.hpp:19
CellStyle normal
Unselected row fill and text.
Definition virtual_list.hpp:22
Owning deterministic width policy; no font or terminal matching promise.
Definition text.hpp:42
Internal bridge for checked access to managed scene and recipe state.
Definition ui_recipe_access.hpp:28